gRPC( Remote Procedure Call by Google)

Tags
httpnetwork
Created
May 8, 2018 7:03 AM

服务端 proto 手写,可以自动生成需要实现的代码https://medium.com/blokur/how-to-implement-a-grpc-client-and-server-in-typescript-fa3ac807855e

proto 文件定义服务以及消息类型:

syntax = "proto3";

...

package helloworld;

// The greeting service definition.

service Greeter {

// Sends a greeting // 提供|开放 sayHello 接口 // 接口逻辑写在服务中

rpc SayHello (HelloRequest) returns (HelloReply) {}

}

// The request message containing the user's name.

message HelloRequest {

string name = 1;

}

// The response message containing the greetings

message HelloReply {

string message = 1;

}

开启服务器:

var PROTO_PATH = __dirname + '/../../protos/helloworld.proto';

var hello_proto = grpc.load(PROTO_PATH).helloworld;

/**

* Implements the SayHello RPC method.

*/

function sayHello(call, callback) {

callback(null, {message: 'Hello ' + call.request.name});

}

/**

* Starts an RPC server that receives requests for the Greeter service at the

* sample server port

*/

var server = new grpc.Server();

server.addProtoService(hello_proto.Greeter.service, {sayHello: sayHello}); // 这里定义了接口还要在proto文件中rpc提供

server.bind('0.0.0.0:50051', grpc.ServerCredentials.createInsecure());

server.start();

开启客户端:

// load proto

...

var client = new hello_proto.Greeter('localhost:50051', grpc.credentials.createInsecure());

client.sayHello({name: 'world'}, function(err, response) {

console.log('Greeting:', response.message);

});

SuperMade with Super