Go微服务实战|第4章:gRPC Client-side Streaming RPC

  • 原创
  • Madman
  • /
  • /
  • 0
  • 1636 次阅读

Go 微服务实战.png

Synopsis: gRPC Client-side Streaming RPC 是指客户端发送多个请求 messages,客户端发送 Streaming 数据流,而从服务端接收一个响应 message

代码已上传到 https://github.com/wangy8961/grpc-go-tutorial/tree/v0.4 ,欢迎 star

1. Protocol Buffers 定义

gRPC Unary RPC

我们将为 Math 服务添加一个新的 RPC 调用,计算一系列的整数的平均值

修改 grpc-go-tutorial/math/mathpb/math.proto 文件:

syntax = "proto3";

option go_package="mathpb";

package math;

// The math service definition.
service Math {
    ...

    // Average is client-side streaming RPC
    rpc Average(stream AverageRequest) returns (AverageResponse) {};
}

...

// The request message for Average.
message AverageRequest {
    int32 num = 1;
}

// The response message for Average.
message AverageResponse {
    double result = 1;
}

然后切换到 .proto 文件所在的目录:

[root@CentOS ~]# cd grpc-go-tutorial/math/mathpb/
[root@CentOS mathpb]# protoc --go_out=plugins=grpc:. *.proto

将会更新 math.pb.go 文件

2. 实现 gRPC 服务端

服务端需要实现 math.pb.go 中的 server API:

// MathServer is the server API for Math service.
type MathServer interface {
    ...

    // Average is client-side streaming RPC
    Average(Math_AverageServer) error
}

所以,修改 grpc-go-tutorial/math/math_server/main.go 文件:

// Package main implements a server for Math service.
package main

import (
    "context"
    "flag"
    "fmt"
    "io"
    "log"
    "net"

    pb "github.com/wangy8961/grpc-go-tutorial/math/mathpb"
    "google.golang.org/grpc"
)

// server is used to implement mathpb.MathServer.
type server struct{}

...

// Average implements mathpb.MathServer
func (s *server) Average(stream pb.Math_AverageServer) error {
    fmt.Printf("--- gRPC Client-side Streaming RPC ---\n")

    // Read requests and send responses
    var sum int32
    count := 0

    for {
        in, err := stream.Recv()

        if err == io.EOF {
            fmt.Printf("Receiving client streaming data completed\n")
            average := float64(sum) / float64(count)
            return stream.SendAndClose(&pb.AverageResponse{Result: average})
        }

        fmt.Printf("request received: %v\n", in)

        if err != nil {
            log.Fatalf("Error while receiving client streaming data: %v", err)
        }

        sum += in.Num
        count++
    }
}

func main() {
    port := flag.Int("port", 50051, "the port to serve on")
    flag.Parse()

    lis, err := net.Listen("tcp", fmt.Sprintf(":%d", *port)) // Specify the port we want to use to listen for client requests
    if err != nil {
        log.Fatalf("failed to listen: %v", err)
    }
    fmt.Printf
                                
                            
未经允许不得转载: LIFE & SHARE - 王颜公子 » Go微服务实战|第4章:gRPC Client-side Streaming RPC

分享

作者

作者头像

Madman

如需 Linux / Python 相关问题付费解答,请按如下方式联系我

0 条评论

暂时还没有评论.