Go微服务实战|第2章:gRPC Unary RPC

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

Go 微服务实战.png

Synopsis: gRPC Unary RPC 就是我们所熟悉的客户端发起一次 Request、服务端响应一次 Response,即客户端发送一个请求 message 给服务端,然后再从服务端接收到一个响应 message。Unary RPC 调用将成为你的 API 中最通用的 RPC 调用,它非常适合要传输的结构化数据很小的场景,我们构建 API 时应当首先实现为 Unary RPC,当它的性能出现瓶颈时,才考虑将它改写成 Streaming RPC

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

1. Protocol Buffers 定义

每个 gRPC Unary RPC 需要定义一个 Request message 和一个 Response message

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 {
    // Sum is unary RPC.
    rpc Sum(SumRequest) returns (SumResponse) {};
}

// The request message for Sum.
message SumRequest {
    int32 first_num = 1;
    int32 second_num = 2;
}

// The response message for Sum.
message SumResponse {
    int32 result = 1;
}

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

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

将会生成 math.pb.go 文件,它包含了服务端需要实现的接口和客户端 Stub

2. 实现 gRPC 服务端

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

// MathServer is the server API for Math service.
type MathServer interface {
    // Sum is unary RPC.
    Sum(context.Context, *SumRequest) (*SumResponse, error)
}

所以,新增 grpc-go-tutorial/math/math_server/main.go 文件:

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

import (
    "context"
    "flag"
    "fmt"
    "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{}

// Sum implements mathpb.MathServer
func (s *server) Sum(ctx context.Context, in *pb.SumRequest) (*pb.SumResponse, error) {
    fmt.Printf("--- gRPC Unary RPC ---\n")
    fmt.Printf("request received: %v\n", in)
    return &pb.SumResponse{Result: in.FirstNum + in.SecondNum}, nil
}

func main() {
    port := flag.Int("port", 50051, "the port to serve on")
    
                                
                            
  • alexander-guan-2839963870
  • gnawh
  • wuleiyzu
  • 37144698
  • blake
  • 42952091
  • 31787219
  • zhouyi
  • chenfan
  • abc127546
  • 13273073
  • leon133
  • voidnil0
  • fissh
  • 38198038
  • sailing
  • 2962285897
  • henry
  • 47849342
  • tomy113
  • 23610880
  • john
  • kejuana
  • karmelo
未经允许不得转载: LIFE & SHARE - 王颜公子 » Go微服务实战|第2章:gRPC Unary RPC

分享

作者

作者头像

Madman

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

0 条评论

暂时还没有评论.

专题系列