gRPCとは
2015年にGoogleが開発したHTTP2.0ベースのプロトコルです。データのシリアライズにはProtocolBuffersがデフォルトで使われています。
特徴として下記があります。
- Streemが使える(単方向、双方向)
- C++, Java, Node.js, Goなど多くの言語でgRPCをサポート
- テキストベースのHTTP/1.1と異なりバイナリベースのHTTP/2.0を使っているので高速

Protocol Buffers
構造化データをバイト列に変換(シリアライズ)するソフトウェアで、バイナリを扱うのでプログラミング言語に依存しません。またDSLから生成されたソースコードを使用して、様々なデータストリームとプログラミング言語を使用して構造化データを簡単に読み書きできるようになります。最近だとgRPCと一緒に使われることが多いみたいです。
サンプルコード
サンプルコードは本家gRPCのGitHubのものです。Node.jsはv8.10.0を使っています。
$ git clone -b v1.11.x https://github.com/grpc/grpc $ cd grpc/examples/node/dynamic_codegen $ npm instal
Protpcol Buffersの定義を下記helloworld.protoにしています。helowworld.protoにはserviceとmessageを定義しています。
messageにはリクエスト時に送るデータとレスポンスで帰ってくるデータを定義し、serviceにはgRPCサーバで実行するservce名とリクエストとレスポンスのデータをマッピングしています。
//helloworld.proto syntax = "proto3"; option java_multiple_files = true; option java_package = "io.grpc.examples.helloworld"; option java_outer_classname = "HelloWorldProto"; option objc_class_prefix = "HLW"; package helloworld; // The greeting service definition. service Greeter { // Sends a greeting 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; }
greeter_client.jsからgRPCサーバにリクエストします。.protoで定義したsayHelloを呼び出しています。
//greeter_client.js var PROTO_PATH = __dirname + '/../../protos/helloworld.proto'; var grpc = require('grpc'); var hello_proto = grpc.load(PROTO_PATH).helloworld; function main() { var client = new hello_proto.Greeter('localhost:50051', grpc.credentials.createInsecure()); var user; if (process.argv.length >= 3) { user = process.argv[2]; } else { user = 'world'; } client.sayHello({name: user}, function(err, response) { console.log('Greeting:', response.message); }); } main();
greeter_server.jsには実際いsayHelloのserviceを実装し、gRPCサーバに登録しています。
//greeter_server.js var PROTO_PATH = __dirname + '/../../protos/helloworld.proto'; var grpc = require('grpc'); 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 */ function main() { var server = new grpc.Server(); server.addService(hello_proto.Greeter.service, {sayHello: sayHello}); server.bind('0.0.0.0:50051', grpc.ServerCredentials.createInsecure()); server.start(); } main();
1対1のリクエストとレスポンス方式だとすごく簡単ですね。初見でも読めないところはないし、結構簡単に実装できそうです。
Streem通信を行ってみる
ここは出来次第追記します!
髙妻智一
最新記事 by 髙妻智一 (全て見る)
- Polkadot(Substrate)のアドレスとトランザクションについて - 2023-03-09
- 【無料公開】「Goで始めるBitcoin」3章 Bitcoinノードとの通信 技術書典8 - 2020-03-08
- エンジニアがゼロから技術ブログを書くための方法をまとめました - 2019-05-25
コメントを残す