Skip to content

Client: Synchronized Calls

Shaun McCormick edited this page Jun 17, 2019 · 1 revision

Gruf::SynchronizedClient wraps Gruf::Client with some additional behavior to help prevent generating spikes of redundant requests. If multiple calls to the same endpoint with the same parameters are made, the first one will be executed and the following ones will block, waiting for the first result.

require 'gruf'
require 'thwait'

id = args[:id].to_i.presence || 1
client = ::Gruf::SynchronizedClient.new(service: ::Demo::ThingService)
thread1 = Thread.new { client.call(:GetMyThing, id: id) }
thread2 = Thread.new { client.call(:GetMyThing, id: id) }
ThreadsWait.all_waits(thread1, thread2)

In the above example, thread1 will make the rpc call, thread2 will block until the call is complete, and then will get the same value without making a second rpc call.

You can also skip this behavior for certain methods if desired.

require 'gruf'
require 'thwait'

id = args[:id].to_i.presence || 1
client = ::Gruf::SynchronizedClient.new(service: ::Demo::ThingService, options: { unsynchronized_methods: [:GetMyThing] })
thread1 = Thread.new { client.call(:GetMyThing, id: id) }
thread2 = Thread.new { client.call(:GetMyThing, id: id) }
ThreadsWait.all_waits(thread1, thread2)

In the above example, thread1 and thread2 will make rpc calls in parallel, in the same way as if you had used Gruf::Client.