zoukankan      html  css  js  c++  java
  • 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)
    }
    




  • 相关阅读:

    决斗(Headshot )
    密码(Password)
    线性表
    hdu 5409 CRB and Graph(边双联通分量)
    无向图的边双连通分量(EBC)
    hdu 3461 Code Lock 并查集(有点难想到)★★
    hdu 1558 Segment set 计算几何+并查集★
    交表(Send a Table)
    杨辉三角与二项式定理
  • 原文地址:https://www.cnblogs.com/hualou/p/12103688.html
Copyright © 2011-2022 走看看