[b]1, 安装ruby-protobuf[/b]
[b]2, 定义rpc service的rpc.proto文件[/b]
[b]3, 编译[/b]
[b]4, 完成service和client代码[/b]
rpc_service.rb
client_search.rb
[b]5, 运行[/b]
启动Service
[code]
ruby start_rpc_service
// :port参数名改为:Port
[/code]
调用Client
[code]
ruby client_search.rb
// result
"www.google.com"
"www.freewheel.tv"
[/code]
gem install ruby_protobuf
[b]2, 定义rpc service的rpc.proto文件[/b]
package demo;
message SearchRequest {
required string keyword = 1;
}
message SearchResponse {
required string result = 1;
}
service RpcService {
rpc Search (SearchRequest) returns (SearchResponse);
}
[b]3, 编译[/b]
rprotoc rpc.proto
[b]4, 完成service和client代码[/b]
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
[b]5, 运行[/b]
启动Service
[code]
ruby start_rpc_service
// :port参数名改为:Port
[/code]
调用Client
[code]
ruby client_search.rb
// result
"www.google.com"
"www.freewheel.tv"
[/code]