douqiao6563 2017-06-09 14:28
浏览 38

使用protobuf简化对瘦golang api的grpc调用

I am currently playing around with grpc on golang and trying to figure out the best way to make an extensible 'thin' api that i can use to pass all requests to their relevant services.

I currently have the structure of:

  • Service 1
    • routes.go
    • rpc.go
  • Service 2
    • routes.go
    • rpc.go

Within the routes files, it creates a new routeGroup that i then register in main, then each handler for a route parses any params etc into a protobuf request and calls a function within RPC:

func showFeed(c *gin.Context) {
    message, err := RpcFeedGet(&social.ShowRequest{LocationId: 1})

    resp := http.HttpResponse{c, "feed", err, message} 
    http.ParseResponse(&resp) //Checks if there is an error and handles response headers etc.
}

Now within rpc im currently defining the below for each service which seems to be really inefficient to me as there is a lot of code reuse, how would i optimize/reduce the code reuse within this method

func connect() (*grpc.ClientConn, pb.Service1Client) {

    //Consul is being used for discovery, this just gets the address to dial
    consul := discovery.Init()
    service, err := consul.Lookup("service1", "")

    if err != nil {
        log.Fatalf("Unable to get service definition: %w", err)
    }

    //Dial the connection to the service
    conn, err := grpc.Dial(service.Address(), grpc.WithInsecure())

    if err != nil {
        log.Fatalf("Unable to connect to client service: %v", err)
    }

    //Creates the service client (service1) and returns it
    client := pb.NewService1Client(conn)

    return conn, client
}

func RpcFeedGet(data *pb.ShowRequest) (string, error) {
    conn, client := connect()
    defer conn.Close()

    //This line calls the protobuf GetFeed rpc service
    resp, err := client.GetFeed(context.Background(), data)

    return rpcHelp.CheckResponse(resp, err) //Handles any errors returned
}

Is there a way i can pass a function to a sub function that calls the connect/defer within the Rpc function and also normalise the connect() method so i dont have to redeclare it for each service? bearing in mind it returns a different client on each instance?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 HLs设计手写数字识别程序编译通不过
    • ¥15 Stata外部命令安装问题求帮助!
    • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
    • ¥15 TYPCE母转母,插入认方向
    • ¥15 如何用python向钉钉机器人发送可以放大的图片?
    • ¥15 matlab(相关搜索:紧聚焦)
    • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
    • ¥15 路易威登官网 里边的参数逆向
    • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
    • ¥50 需求一个up主付费课程