twn39 / code

:memo: 代码笔记,通过 issue 的方式记录日常遇到的问题和学习笔记
13 stars 1 forks source link

Grpc Nodejs server #309

Open twn39 opened 4 years ago

twn39 commented 4 years ago
syntax = "proto3";

package App;

message Empty {};

message Response {
  int32 code = 1;
  string message = 2;
}

service EchoService {
    rpc Greet(Empty) returns (Response);
}

Node server :

const PROTO_PATH = __dirname + '/proto/echo.proto';

const grpc = require('grpc');
const protoLoader = require('@grpc/proto-loader');
const packageDefinition = protoLoader.loadSync(
    PROTO_PATH,
    {
        keepCase: true,
        longs: String,
        enums: String,
        defaults: true,
        oneofs: true
    });
const echo_proto = grpc.loadPackageDefinition(packageDefinition);

/**
 * @param call  proto 定义的函数参数
 * @param callback 第二个为 proto 定义的函数返回的参数
 * @constructor
 */
function Greet(call, callback) {
    callback(null, {code: 0, message: "Hello node gRPC."});
}

function main() {
    const server = new grpc.Server();
    console.log(echo_proto);
    server.addService(echo_proto.App.EchoService.service, {Greet});
    server.bind('0.0.0.0:50051', grpc.ServerCredentials.createInsecure());
    server.start();
}

main();

Node 端代码会自动编译 protobuf 文件,所以不需要手动生成。

依赖:

    "@grpc/proto-loader": "^0.1.0",
    "async": "^1.5.2",
    "google-protobuf": "^3.0.0",
    "grpc": "^1.11.0",
    "lodash": "^4.6.1",
    "minimist": "^1.2.0"
twn39 commented 4 years ago

PHP Client

PHP Grpc 暂时不支持 Server 端,只支持生成 Client 代码,而且需要通过 grpc_php_plugin 插件手动将 protobuf 文件转换成 PHP 代码。

编译:

protoc --proto_path=proto --php_out=src --grpc_out=src --plugin=protoc-gen-grpc=../grpc/bins/opt/grpc_php_plugin proto/echo.proto

生成之后将其加入 composer autoload ,示例:

    "autoload": {
        "psr-4": {
            "App\\": "src/App",
            "GPBMetadata\\": "src/GPBMetadata"
        }
    },

根据实际目录定义 autoload 加载方式,确保能够正确引入 PHP 文件,依赖:

    "require": {
        "grpc/grpc": "^1.27",
        "google/protobuf": "^3.11"
    }

客户端代码:

<?php
require "vendor/autoload.php";

$client = new \App\EchoServiceClient("0.0.0.0:50051", [
    'credentials' => Grpc\ChannelCredentials::createInsecure(),
]);

list($res, $status) = $client->Greet(new \App\PBEmpty())->wait();
var_dump($res->getMessage());
echo "-------------";
var_dump($status);