美文网首页
grpc + protocol/buf 打通 node 和 go

grpc + protocol/buf 打通 node 和 go

作者: Joah_l | 来源:发表于2019-09-29 11:57 被阅读0次

    一. 安装 protocol/buf 编译器

    • wget "https://github.com/protocolbuffers/protobuf/releases/download/v3.9.1/protobuf-all-3.9.1.tar.gz"

    • tar zxvf protobuf-all-3.9.1.tar.gz

    • cd protobuf-3.9.1

    • ./configure

    • make && sudo make install

    如果 protoc --version ; 则说明安装成功

    二. 在 Golang 和 Node 服务器中同时配置相同的 .proto 文件

      syntax = "proto3";
    
      package message;
    
      service HelloService {
        rpc SayHello (HelloRequest) returns (HelloResponse);
      }
    
      message HelloRequest {
        string code = 1;
        string message = 2;
      }
    
      message HelloResponse {
        string code = 1;
        string message = 2;
      }
    

    三. golang server 安装依赖

    • google.golang.org/grpc : grpc 框架

      • go get -u -v google.golang.org/grpc
    • go get -u github.com/golang/protobuf/protoc-gen-go

      **安转 golang protocol buffers plugin **

    • 编译项目中 .proto 文件

      • protoc -I message/ message/hello.proto --go_out=plugins=grpc:message

        • -I 源文件包, --go_out=plugins=grpc:(${packageName}), 将会生成 hello.pb.go 文件

        • 编译时可能会报错: protoc: error while loading shared libraries: libprotoc.so.9: cannot open shared obje

          • 解决: 在 bash 中添加环境变量 export LD_LIBRARY_PATH=/usr/local/lib;
    • Golang Server:

      package main
      
      import (
        "context"
        "fmt"
        "net"
      
        "mpa-dance-push/src/logger"
        pb "mpa-dance-push/src/message"
      
        "google.golang.org/grpc"
      )
      
      const port = ":50001"
      
      type server struct{}
      
      func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloResponse, error) {
        logger.Info.Printf("Received: %v", in.GetMessage())
        return &pb.HelloResponse{Message: "Hello " + in.GetMessage()}, nil
      }
      
      // InitRPCServer 初始化 rpc server
      func InitRPCServer() {
        lis, err := net.Listen("tcp", port)
        if err != nil {
          logger.Error.Println("fail")
          return
        }
        fmt.Printf("[Init Tcp Server: Port => %s] \n", port)
        s := grpc.NewServer()
        pb.RegisterHelloServiceServer(s, &server{})
        if err := s.Serve(lis); err != nil {
          logger.Error.Printf("failed to serve: %v", err)
        }
      }
      
      func main() {
        InitRPCServer()
      }
      

    四. 创建 Node 客户端 koa + ts

    • 安装依赖 @grpc/proto-loader, grpc

      • yarn add @grpc/proto-loader grpc --save-dev
    • 代码如下:

      import { loadSync } from '@grpc/proto-loader'
      import { BaseService } from '@services/BaseService'
      import { credentials, loadPackageDefinition, PackageDefinition } from 'grpc'
      import { PROTO_PATH } from 'scretConfig'
      import { Server } from '../../server'
      import { WxProtoMessage } from './rpcMessageModel'
    
      export class GRPCService extends BaseService {
    
        private packageDefinition: PackageDefinition
    
        constructor(server: Server) {
          super(server)
          this.packageDefinition = loadSync(PROTO_PATH, {
            keepCase: true,
            longs: String,
            enums: String,
            defaults: true,
            oneofs: true
          })
    
          let message = loadPackageDefinition(this.packageDefinition).message as WxProtoMessage
          const client = new message.HelloService('localhost:50001', credentials.createInsecure())
    
          client.SayHello({ message: 'world' }, (_err: any, response: any) => {
            console.log(response.message)
          })
        }
      }
    
    

    五, proto3 语法

    相关文章

      网友评论

          本文标题:grpc + protocol/buf 打通 node 和 go

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