基于ruby-protobuf的rpc示例 博客分类: Ruby RubyGoogle
程序员文章站
2024-02-22 16:45:40
...
1, 安装ruby-protobuf
2, 定义rpc service的rpc.proto文件
3, 编译
4, 完成service和client代码
rpc_service.rb
client_search.rb
5, 运行
启动Service
调用Client
gem install ruby_protobuf
2, 定义rpc service的rpc.proto文件
package demo; message SearchRequest { required string keyword = 1; } message SearchResponse { required string result = 1; } service RpcService { rpc Search (SearchRequest) returns (SearchResponse); }
3, 编译
rprotoc rpc.proto
4, 完成service和client代码
rpc_service.rb
require 'protobuf/rpc/server' require 'protobuf/rpc/handler' require 'rpc.pb' class Demo::SearchHandler < Protobuf::Rpc::Handler request Demo::SearchRequest response Demo::SearchResponse def self.process_request(request, response) if request.keyword == 'google' response.result = 'www.google.com' elsif request.keyword == 'freewheel' response.result = 'www.freewheel.tv' else response.result = '' end end end class Demo::RpcService < Protobuf::Rpc::Server def setup_handlers @handlers = { :search => Demo::SearchHandler, } end end
client_search.rb
#!/usr/bin/env ruby require 'protobuf/rpc/client' require 'rpc.pb' # build request request1 = Demo::SearchRequest.new request1.keyword = 'google' request2 = Demo::SearchRequest.new request2.keyword = 'freewheel' # create blunk response response1 = Demo::SearchResponse.new response2 = Demo::SearchResponse.new # execute rpc Protobuf::Rpc::Client.new('localhost', 9999).call :search, request1, response1 Protobuf::Rpc::Client.new('localhost', 9999).call :search, request2, response2 p response1.result p response2.result
5, 运行
启动Service
ruby start_rpc_service // :port参数名改为:Port
调用Client
ruby client_search.rb // result "www.google.com" "www.freewheel.tv"