Last active
April 11, 2020 18:49
-
-
Save art-solopov/66183eb94b26f207e0866c9c80afe208 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'securerandom' | |
require 'bundler' | |
Bundler.require(:default) | |
class RPCClient | |
def initialize | |
@var_store = {} | |
@connection = Bunny.new | |
start_connection! | |
end | |
def send(request) | |
p "Sending message <<#{request}>>" | |
request_key = SecureRandom.hex(4) | |
@exchange.publish(request, headers: { 'X-Request-Key' => request_key }) | |
var = Concurrent::MVar.new | |
@var_store[request_key] = var | |
var.take | |
end | |
def shutdown | |
@connection.close | |
end | |
private | |
def start_connection! | |
@connection.start | |
@channel = @connection.create_channel | |
@exchange = @channel.direct('rpcc-rb') | |
@rpc_request_queue = @channel.queue('rpc_request') | |
@rpc_response_queue = @channel.queue('rpc_response') | |
@rpc_request_queue.bind('rpcc-rb') | |
@rpc_response_queue.subscribe do |_dlvr, props, body| | |
headers = props[:headers] | |
response_for = headers['X-Response-For'] | |
@var_store.delete(response_for).put(body) | |
end | |
end | |
end | |
client = RPCClient.new | |
t1 = Thread.new do | |
reply = client.send('Hello from handler 1') | |
p "[1] Received message <<#{reply}>>" | |
end | |
t2 = Thread.new do | |
reply = client.send('Hello from handler 2') | |
p "[2] Received message <<#{reply}>>" | |
end | |
t1.join | |
t2.join | |
client.shutdown |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment