gRPCのサンプルコードをNode.jsで動かしてみる




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通信を行ってみる

ここは出来次第追記します!

The following two tabs change content below.

髙妻智一

2013年CyberAgent新卒入社 スマホゲームを作る子会社に所属し、サーバーサイドのエンジニアを担当。2年目の終わりから新規子会社の立ち上げに参加し、サーバーサイドのエンジニアリーダーとしてサービースのリリースから運用までを担当。 2018年仮想通貨のスマホウォレットを提供するGinco Incにブロックチェーンエンジニアとして入社。






よく読まれている関連記事はこちら




コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です