Skip to main content

gin+gomicro

坑1 grpc 报错,版本问题 go.mod 改为

replace google.golang.org/grpc => google.golang.org/grpc v1.27.1

main.go

package main

import (
"asdasd.cn/say/producer"
"github.com/asim/go-micro/plugins/registry/etcd/v3"
"github.com/asim/go-micro/v3/registry"
"github.com/asim/go-micro/v3/web"
"github.com/gin-gonic/gin"
"net/http"
)

func main() {
//启动一个consul服务
RegCon := etcd.NewRegistry(
registry.Addrs("127.0.0.1:2379"),
)

r := gin.Default()
//创建一个路由组,目的是便于管理
V1group := r.Group("/v1")
{
V1group.Handle("GET", "/user", func(ctx *gin.Context) {
ctx.String(http.StatusOK, "newsapi")
})
V1group.Handle("POST", "/book", func(ctx *gin.Context) {
ctx.JSON(http.StatusOK, gin.H{
"data": producer.Producer(),
})
})
}
service := web.NewService(
web.Name("first"),
web.Address(":8080"),
web.Handler(r),
web.Registry(RegCon),
web.Metadata(map[string]string{"protocol": "http"}),
)

service.Init()
service.Run()
}

producer.go

package producer

import "fmt"

type Booke struct {
Bookename string
Bookevalue int64
}

func Produce(BN string, BV int64) *Booke {
return &Booke{Bookename: BN, Bookevalue: BV}
}

func Producer() []*Booke {
store := make([]*Booke, 0)
for i := 0; i < 5; i++ {
store = append(store, Produce((fmt.Sprintf("booke%d", i)), int64(i)))
}
return store
}

api.go

package main

import (
"context"
"fmt"
"github.com/asim/go-micro/plugins/registry/etcd/v3"
"log"

//使用http连接
httpClient "github.com/asim/go-micro/plugins/client/http/v3"
"github.com/asim/go-micro/v3/client"
"github.com/asim/go-micro/v3/registry"
"github.com/asim/go-micro/v3/selector"
)

func CallAPI(s selector.Selector) {
myclient := httpClient.NewClient(
client.Selector(s),
client.ContentType("application/json"),
)
//第一参数为服务名,第二个为方法名
req := myclient.NewRequest("first", "/v1/book", map[string]string{})
var rsp map[string]interface{}
//call方法得到请求响应之后会把值给rsp所以传地址所以类型要对应起来
err := myclient.Call(context.Background(), req, &rsp)
if err != nil {
log.Fatal(err)
}
fmt.Println(rsp["data"])
}

func main() {
Regcon := etcd.NewRegistry(
registry.Addrs("127.0.0.1:2379"),
)
//通过函数的方式创建选择器
myselect := selector.NewSelector(
selector.Registry(Regcon),
//选择的方式是随机的 selector.Random
selector.SetStrategy(selector.Random),
)
CallAPI(myselect)
}