node 实现 rpc

image

// index.js
const diplomat = require('js-diplomat');
const grpc = require('@grpc/grpc-js');
const { randomUUID } = require('crypto');

const { cupAdmin } = require('../proto');

let discoverServer = null;
let client = null;
const initDiscoverServer = () => (discoverServer = diplomat());

function getAddress(name, options) {
  if (!discoverServer) initDiscoverServer();
  return discoverServer.service(name, options);
}

function getClient() {
  return new Promise((resolve, reject) => {
    // 保持单例需要确保地址可靠,consul 返回的是 ip + port
    // 本来想通过 ha 地址访问,保持地址可靠,不过 consul 没返回
    // 做成在 error 的时候,通过 discard 的形式重新触发服务发现
    if (client) {
      resolve(client);
      return;
    }
    getAddress('cup-admin-mg-grpc')
      .then((data) => {
        console.log(data);
        const serverPath = !!data?.address
          ? `${data.address}:${data.port}`
          : '';
        if (!serverPath) {
          reject('can not find rpc server');
          return;
        }
        client = new cupAdmin.ModelGatewayService(
          serverPath,
          grpc.credentials.createInsecure(),
        );
        resolve(client);
      })
      .catch((e) => {
        console.error(e);
      });
  });
}


getClient()
  .then((client) => {
      const params = {}
      client.SyncProcessTask(params, (err, res) => {
      if (err) {
        console.error('err:', err);
      }
      console.log(res);
      console.log(JSON.stringify(res));
    });
  })
  .catch((e) => console.error(e));
//proto.js

const path = require("path");
const grpc = require("@grpc/grpc-js");
const protoLoader = require("@grpc/proto-loader");

const cupAdminProtoPath = path.join(__dirname, "./cupAdmin/main.proto");
const cupPackageDefinition = protoLoader.loadSync(cupAdminProtoPath, {
 keepCase: true,
 longs: String,
 enums: String,
 defaults: true,
 oneofs: true,
});
const cupProtoDescriptor = grpc.loadPackageDefinition(cupPackageDefinition);
const cupAdmin = cupProtoDescriptor.cup_admin.rpc;

// cupAdmin/main.proto
// 这个是 服务的 pb 文件
syntax = "proto3";
package cup_admin.rpc;

option java_package = "com.xx.cup_admin.rpc";
option go_package = "./model_gateway";
//import "validate/validate.proto";
// const string __VERSION__ = '1.2.2'

service ModelGatewayService {
rpc SyncProcessTask(Request) returns (Response);         //同步接口
}
posted @ 2023-04-22 21:08  地铁程序员  阅读(30)  评论(0编辑  收藏  举报