• go简单使用grpc


    0.相关链接

    grpc github:https://github.com/grpc/grpc-go

    官方文档:https://grpc.io/docs/languages/go/

    案例代码:https://github.com/tenqaz/go-examples

    1. 定义proto文件

    proto文件是用来预先定义的消息格式。数据包会按照proto文件所定义的消息格式完成二进制码流的编码和解码。

    syntax = "proto3";
    
    // 指定生成的 go 文件存放位置及其包名
    option go_package = "./;proto";
    
    // 定义User rpc服务
    service User {
      // 定义rpc服务的方法
      rpc AddUser (UserRequest) returns (UserResponse);
      rpc GetUser (GetUserRequest) returns (GetUserResponse);
    }
    
    // 请求的结构体
    message UserRequest {
      string name = 1;
      uint32 age = 2;
    }
    
    // 响应的结构体
    message UserResponse {
      string msg = 1;
      int32 code = 2;
    }
    
    message GetUserRequest {
      string name = 1;
    }
    
    message GetUserResponse {
      string name = 1;
      string age = 2;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    2. 编译proto文件

    首先需要安装protoc的二进制文件,是用来编译proto的。

    下载地址:https://github.com/protocolbuffers/protobuf/releases

    然后再下载安装编译proto文件的插件

    $ go install google.golang.org/protobuf/cmd/protoc-gen-go@v1.28
    $ go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@v1.2
    
    • 1
    • 2

    进入proto目录下使用以下命令对proto文件进行编译,会生成两个文件user.pb.gouser_grpc.pb.go两个文件

    protoc --go_out=. --go-grpc_out=. user.proto
    
    • 1
    • –go_out=. protobuf相关代码文件生成在该目录下
    • –go-grpc_out=. grpc相关代码文件生成在该目录下

    编译后:

    • user.pb.go:主要是请求与相应数据包的结构体定义,客户端和服务端都可以通过该结构体进行序列化与反序列化。
    • user_grpc.pb.go:主要是grpc的服务端和客户端代码,通过实现及调用接口来互相沟通。

    3. 创建grpc服务端

    我们首先要实现user_grpc.pb.go中的UserServer接口,该接口中的方法是我们在proto文件中定义的rpc服务AddUser和GetUser。

    不过,你会发现其中还多了个mustEmbedUnimplementedUserServer方法,但是我们proto文件中并没有定义,这个是用来兼容使用的。你看可以文件中UnimplementedUserServer结构体实现了UserServer接口,自己定义UserService包含UnimplementedUserServer,即使没有实现UserServer所有接口,也不会报错。

    package main
    
    import (
    	"context"
    	"fmt"
    	"google.golang.org/grpc"
    	"log"
    	"net"
    	"simple_example/proto"
    )
    
    // UserService 定义结构体,实现UserServer
    type UserService struct {
    	proto.UnimplementedUserServer
    }
    
    func NewUserService() *UserService {
    	return &UserService{}
    }
    
    // AddUser 实现rpc方法
    func (us *UserService) AddUser(ctx context.Context, request *proto.UserRequest) (*proto.UserResponse, error) {
    	fmt.Printf("add user success. name = %s, age = %d\n", request.GetName(), request.GetAge())
    	return &proto.UserResponse{Msg: "success", Code: 0}, nil
    }
    
    func (us *UserService) GetUser(ctx context.Context, request *proto.GetUserRequest) (*proto.GetUserResponse, error) {
    	fmt.Printf("get user. name = %s\n", request.GetName())
    	return &proto.GetUserResponse{Name: request.GetName(), Age: 1999}, nil
    }
    
    func main() {
    	// 监听端口
    	lis, err := net.Listen("tcp", fmt.Sprintf("localhost:%d", 8000))
    	if err != nil {
    		log.Fatalf("failed to listen: %v", err)
    	}
    	grpcServer := grpc.NewServer()
    
    	// 注册rpc服务
    	proto.RegisterUserServer(grpcServer, NewUserService())
    	grpcServer.Serve(lis)
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44

    4. 创建grpc客户端

    调用user_grpc.pb.go文件中的NewUserClient方法来创建调用rpc服务的客户端,调用rpc方法时使用user.pb.go中的结构体作为输入与输出。

    package main
    
    import (
    	"context"
    	"fmt"
    	"google.golang.org/grpc"
    	"google.golang.org/grpc/credentials/insecure"
    	"log"
    	"simple_example/proto"
    )
    
    func main() {
    	var opts []grpc.DialOption
    	opts = append(opts, grpc.WithTransportCredentials(insecure.NewCredentials()))
    
    	conn, err := grpc.Dial("localhost:8000", opts...)
    	if err != nil {
    		log.Fatalf("fail to dial: %v", err)
    	}
    	defer conn.Close()
    
    	client := proto.NewUserClient(conn)
    
    	// 调用rpc服务AddUser方法
    	resp, err := client.AddUser(context.Background(), &proto.UserRequest{Name: "zhengwenfeng", Age: 18})
    	if err != nil {
    		log.Fatalf("fail to AddUser: %v", err)
    	}
    	fmt.Printf("AddUser, msg = %s, code = %d\n", resp.Msg, resp.Code)
    
    	// 调用rpc服务GetUser方法
    	getuserResp, err := client.GetUser(context.Background(), &proto.GetUserRequest{Name: "zhangsan"})
    	if err != nil {
    		log.Fatalf("fail to GetUser: %v", err)
    	}
    	fmt.Printf("GetUser, Name = %s, Age = %d", getuserResp.Name, getuserResp.Age)
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39

    5. 运行结果

    首先运行服务端监听rpc服务
    然后再运行客户端调用服务。
    服务端输出:

    add user success. name = zhengwenfeng, age = 18
    get user success. name = zhangsan
    
    • 1
    • 2

    客户端输出:

    AddUser, msg = success, code = 0
    GetUser, Name = zhangsan, Age = 1999
    
    • 1
    • 2

    欢迎关注,互相学习,共同进步~

    我的个人博客

    我的微信公众号:编程黑洞

  • 相关阅读:
    如何写一篇百万阅读量的文章
    【苹果推位置推iMessage】Apple Notification Center Service (ANCS)
    web server apache tomcat11-04-manager 如何管理?
    【Elasticsearch专栏 11】深入探索:Elasticsearch如何支持多租户架构
    SAP system copy 操作流程笔记
    kubelet源码分析 创建/更新/调谐 pod
    界面组件DevExpress Reporting v22.1 - 可自定义参数面板
    准备用HashMap存1W条数据,构造时传10000还会触发扩容吗?存1000呢?
    动态资源如何生成
    知识变现海哥:打造爆款课程的底层逻辑
  • 原文地址:https://blog.csdn.net/qq_22918243/article/details/126827997