LoginSignup
10
11

More than 5 years have passed since last update.

gRPCをRubyで試してみる

Last updated at Posted at 2017-07-02

対象読者

  • gRPCの概要は理解しているが、Rubyでの実装に困っている

概要はこちら→http://qiita.com/oohira/items/63b5ccb2bf1a913659d6

ゴール

  • サービス定義を自由にカスタマイズできるようになる

参考

環境

  • macOS Sierra 10.12.5
  • Ruby 2.4.1

手順

gRPCリポジトリをクローン

git clone https://github.com/grpc/grpc.git
  • 実際使うのはこのディレクトリだけ→ grpc/examples

Ruby用Gemインストール

$ gem install grpc
$ gem install grpc-tools

サービス定義の説明

/examples/protos/helloworld.proto
// サービスの振る舞いを定義
service Greeter {
  // nameというフィールドを持ったHelloRequestを受け取って、messageを持ったHellowReplyを返す
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}

// メッセージを定義
message HelloRequest {
  string name = 1;
}

// メッセージを定義
message HelloReply {
  string message = 1;
}

サービス定義を変更

/examples/protos/helloworld.proto
// 大豆から豆腐を作る
service Greeter {
  rpc CreateTofu (Daizu) returns (Tofu) {}
}

// 大豆を定義
message Daizu {
  string name = 1;
  int32 count = 2;
}

// 豆腐を定義
message Tofu {
  string name = 1;
  int32 size = 2;
}

変更したサービス定義を適用

$ grpc_tools_ruby_protoc -I ../protos --ruby_out=lib --grpc_out=lib ../protos/helloworld.proto

サーバーの定義を変更

/examples/ruby/greeter_server.rb
class GreeterServer < Helloworld::API::Service
  def create_tofu(daizu, _unused_call)
    name = "#{daizu.name}_tofu" # リクエストのフィールドはドットで呼び出せる
    size = daizu.count * 2
    return Helloworld::Tofu.new(name: name, size: size) #レスポンスはメッセージのインスタンス生成をするだけ
  end
end

クライアントの定義を変更

/examples/ruby/greeter_client.rb
def main(name, count)
  stub = Helloworld::Greeter::Stub.new('localhost:50051', :this_channel_is_insecure)
  tofu = stub.create_tofu(Helloworld::Daizu.new(name: name, count: count))
  p "豆腐の名前は#{tofu.name}"
  p "豆腐の大きさは#{tofu.size}"
end
p 豆腐の名前は?
input_name = gets.chomp
p 豆腐の数は?
input_count = gets.to_i
main(input_name, input_count)

起動

サーバー

$ ruby examples/ruby/greeter_server.rb

クライアント

$ ruby examples/ruby/greeter_client.rb

【番外編】REST機能を持ったサーバー実装してみた

10
11
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
11