grpc + protocol/buf 打通 node 和 go

2019-09-29  本文已影响0人  Joah_l

一. 安装 protocol/buf 编译器

如果 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 安装依赖

四. 创建 Node 客户端 koa + ts

  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 语法

上一篇下一篇

猜你喜欢

热点阅读