September 2, 2019

building a gRPC application (part 5)

We can finally write some interesting business logic at this point. It may seem like a lot of boiler plate up until now, but it will have saved you quite a bit of time in the long-run as you will not need to worry about client creation or proxy configuration.

We can create a class in lib/demo/friendly.rb and give it methods corresponding to our gRPC service declaration:

require './lib/user_services_pb'

module Demo
  class Friendly < UserActivity::Service
    def acknowledge(user_information, _extra)
      UserInformation.new(username: user_information.username)
    end
  end
end

This matches the gRPC signature declaration of the protocol and will be runnable as an endpoint. A simple script will suffice to run the endpoint:

#!/usr/bin/env ruby

require 'grpc'
require './lib/demo/friendly'

server = GRPC::RpcServer.new
server.add_http2_port('localhost:50051', :this_port_is_insecure)
server.handle(Demo::Friendly)
server.run_till_terminated

Open two terminal windows. In the first, run:

chmod +x bin/friendly
bundle exec bin/fiendly

In the second, run in pry:

pry(main)> friendly.acknowledge alice
=> <UserInformation: username: "alice">
pry(main)> friendly.acknowledge steve 
=> <UserInformation: username: "steve">

It works! Your client - running within pry - sends messages to the service, and the service responds with a new, identical message.

Browse the completed code for this lesson on Gitlab: https://gitlab.com/1ijk/guided-demo/tree/24300d5be6611595497e9f260502c9bbd848347c

Content by © Jared Davis 2019-2020

Powered by Hugo & Kiss.