美文网首页
golang Protobuf 和 gRPC

golang Protobuf 和 gRPC

作者: 王宣成 | 来源:发表于2021-10-16 13:29 被阅读0次

安装 protobuf
https://github.com/protocolbuffers/protobuf/releases

下载解压bin目录加入系统环境变量, D:\protoc\bin

命令行执行

go get -u github.com/golang/protobuf/protoc-gen-go



*.proto 语法

syntax = "proto3"; // PB协议版本

import "google/protobuf/any.proto"; // 引用外部的message,可以是本地的,也可以是此处比较特殊的 Any

package person; // 包名

option go_package = "./person_package"; // 生成类的包名,注意:会在指定路径下按照该包名的定义来生成文件夹

message PersonTest {  
    int32 id = 1; // int 类型  
    string name = 2; // string 类型  
    string email = 3;  
    Sex sex = 4; // 枚举类型  
    repeated PhoneNumber phone = 5; // 引用下面定义的 PhoneNumber 类型的 message  
    map<string, string> tags = 6; // map 类型  
    repeated google.protobuf.Any details = 7; // 使用 google 的 any 类型  

    // 定义一个枚举  
    enum Sex {      
        DEFAULT = 0;      
        MALE = 1;      
        Female = 2;  
    }  
    
    // 定义一个 message  
    message PhoneNumber {    
        string number = 1;    
        PhoneType type = 2;    
        
        enum PhoneType {      
            MOBILE = 0;      
            HOME = 1;      
            WORK = 2;    
        }  
    }
}

下面来写一个例子

# go mod 初始化项目
go mod init demo

创建hello.proto文件,定义HelloService接口

syntax = "proto3";

option  go_package = "./hello";

package hello;

message String{
  string value = 1;
}

service  HelloService{
  rpc Hello (String) returns(String);
}
# 命令窗口使用protoc-gen-go内置的gRPC插件生成gRPC代码
protoc --go_out=plugins=grpc:. hello.proto

创建 server.go

package main

import (
    "context"
    . "demo/hello"
    "google.golang.org/grpc"
    "log"
    "net"
)

type HelloServiceImpl struct {
}

func (p *HelloServiceImpl) Hello(ctx context.Context, args *String) (*String, error) {
    reply := &String{Value: "hello: " + args.GetValue()}
    return reply, nil
}

func main() {
    grpcServer := grpc.NewServer()
    RegisterHelloServiceServer(grpcServer, new(HelloServiceImpl))

    lis, err := net.Listen("tcp", ":880")
    if err != nil {
        log.Fatal(err)
    }
    grpcServer.Serve(lis)
}

创建 client.go

package main

import (
    "context"
    . "demo/hello"
    "fmt"
    "google.golang.org/grpc"
    "log"
)

func main() {
    conn, err := grpc.Dial("localhost:880", grpc.WithInsecure())
    if err != nil {
        log.Fatal(err)
    }

    defer conn.Close()

    client := NewHelloServiceClient(conn)
    reply, err := client.Hello(context.Background(), &String{Value: "wangxuancheng"})
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(reply.GetValue())

}

先运行 server.go 再运行 client.go 查看结果

# 输出
hello:wangxuancheng

相关文章

网友评论

      本文标题:golang Protobuf 和 gRPC

      本文链接:https://www.haomeiwen.com/subject/jchboltx.html