1.服务提供者
// 数据模型
type ProdsRequest struct {
Size int `form:"size"`
}
import ( "github.com/gin-gonic/gin" "github.com/micro/go-micro/registry" "github.com/micro/go-micro/web" "github.com/micro/go-plugins/registry/consul" ) // 使用gin框架 func main() { consulReg := consul.NewRegistry( registry.Addrs("127.0.0.1:8500"), ) ginRouter := gin.Default() v1Group := ginRouter.Group("/v1") { v1Group.Handle("POST", "/prods", func(context *gin.Context) { //声明变量 var gr ProdsRequest //获取绑定数据到gr变量中,底层用的指针这里要传变量地址 err := context.Bind(&gr) if err!=nil || gr.Size<=0 { gr=ProdsRequest{Size:2} } context.JSON(200, gin.H{ "data": NewProdList(gr.Size), "size":gr.Size, }) }) } web.NewService(web.Address(":8001"), web.Handler(ginRouter), web.Registry(consulReg), web.Name("product")).Run() }
2.服务消费者
import ( "context" "fmt" "github.com/micro/go-micro/client" "github.com/micro/go-micro/client/selector" "github.com/micro/go-micro/registry" myhttp "github.com/micro/go-plugins/client/http" "github.com/micro/go-plugins/registry/consul" _ "io/ioutil" "log" _ "net/http" ) type RequestParam struct { //消费者服务的数据模型可以不加`form:"size"` Size int /*`form:"size"`*/ } func callApi2(s selector.Selector) { myclient := myhttp.NewClient( client.Selector(s), client.ContentType("application/json"), ) //消费者传参用map //req := myclient.NewRequest("product", "/v1/prods", map[string]int{"size":5}) req := myclient.NewRequest("product", "/v1/prods", RequestParam{Size: 1}) var rsp map[string]interface{} err := myclient.Call(context.Background(), req, &rsp) if err != nil { log.Fatal(err) } fmt.Println(rsp) } func main() { consulReg := consul.NewRegistry( registry.Addrs("127.0.0.1:8500")) mySelector := selector.NewSelector( selector.Registry(consulReg), selector.SetStrategy(selector.RoundRobin), ) callApi2(mySelector) }