I would like to practice gRPC while making a simple app using Ruby.
This time we will create a calculator CLI application.
If you enter 1 + 2 etc. on the terminal, the client will send the character string "1 + 2" to the server, and the server will calculate the answer and return it as a response. Implement this with gRPC.
Install the grpc and grpc-tools gems.
$ gem install grpc
$ gem install grpc-tools
Create a directory for your app. The name can be anything, but for now let's call it grpc_calc.
$ mkdir grpc_calc
$ cd grpc_calc
We will create a proto file.
grpc_calc $ mkdir protos
grpc_calc $ vi protos/calc.proto
// Create this proto file with the proto3 syntax.
syntax = "proto3";
// Create with the package name example. (* The name can be anything.)
package example;
// Define the computer service.
service Calc {
// Define a method called solve.
// If you pass Input as an argument, it will return Output.
rpc Solve (Input) returns (Output) {}
}
// This is the formula passed from the client.
message Input {
// Define a string with the name question. The tag is 1.
string question = 1;
}
// The answer returned by the server.
message Output {
// Define a number with the name answer. The tag is 1.
int32 answer = 1;
}
Create a lib directory.
grpc_calc $ mkdir lib
Compile protps/calc.proto and output it under lib.
grpc_calc $ grpc_tools_ruby_protoc -I protos --ruby_out=lib --grpc_out=lib protos/calc.proto
Then, I think that calc_pb.rb and calc_services_pb.rb are created under lib.
We will implement it from the server side.
require 'grpc'
require_relative 'lib/calc_services_pb.rb'
class CalcServer < Example::Calc::Service
def solve(input, _unused_call)
answer = eval(input.question)
return Example::Output.new(answer: answer)
end
end
def main
s = GRPC::RpcServer.new
s.add_http2_port('0.0.0.0:50051', :this_port_is_insecure)
s.handle(CalcServer)
s.run_till_terminated_or_interrupted([1, 'int', 'SIGQUIT'])
end
main
We will also implement it on the client side.
require 'grpc'
require_relative 'lib/calc_services_pb.rb'
def main(input)
stub = Example::Calc::Stub.new('localhost:50051', :this_channel_is_insecure)
output = stub.solve(Example::Input.new(question: input))
p "The answer is # {output.answer}"
end
p "Write the formula"
input = gets.chomp
main(input)
This completes the implementation.
Server startup
grpc_calc $ ruby calc_server.rb
Client execution
grpc_calc $ ruby calc_client.rb
"Write the formula"
10 + 20 + 30
"The answer is 60"
If it looks like the above, you are successful!
Recommended Posts