10.调用http api:引入protobuf、生成参数和响应模型

调用http api:引入protobuf、生成参数和响应模型,定义proto文件

syntax = "proto3";
package Models;

message ProdModel {
    // @inject_tag: json:"pid"
    int32 ProdID = 1;
    // @inject_tag: json:"pname"
    string ProdName = 2;
}

message ProdRequest {
    int32 size = 1;
}

message ProdListResponse {
    repeated ProdModel data = 1;
}

根据proto文件生成pb文件

protoc --micro_out=../ --go_out=../ Prods.proto

在客户端中使用生成的pb文件中的model去请求服务端

package main

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"
    "go-micro/Models"
    "log"
)

func callAPI(s selector.Selector) {
    myCli := myhttp.NewClient(
        client.Selector(s),
        client.ContentType("application/json"),
    )
    req := myCli.NewRequest("prodservice", "/v1/prods", Models.ProdRequest{Size: 2}) //使用生成的pb文件中的结构体作为参数封装到请求体中

    var resp Models.ProdListResponse  //使用生成的响应体去解析服务端返回数据
    err := myCli.Call(context.Background(), req, &resp)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(resp)
}

func main() {
    consulReg := consul.NewRegistry(
        registry.Addrs("localhost:8500"),
    )
    mySelector := selector.NewSelector(
        selector.Registry(consulReg),
        selector.SetStrategy(selector.RoundRobin), //设置查询策略,这里是轮询
    )
    callAPI(mySelector)
}




猜你喜欢

转载自www.cnblogs.com/hualou/p/12103688.html
10.