Created
May 2, 2014 02:06
-
-
Save carlhoerberg/96eb730f4c533f61a856 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
#!/usr/bin/env ruby | |
require 'bunny' | |
require 'securerandom' | |
conn = Bunny.new | |
conn.start | |
class FibonacciClient | |
def initialize(conn, server_queue) | |
ch = conn.create_channel | |
@x = ch.default_exchange | |
@reply_queue = ch.queue("", :exclusive => true) | |
@server_queue = server_queue | |
@results = Hash.new { |h,k| h[k] = Queue.new } | |
@reply_queue.subscribe(block: false) do |delivery_info, properties, payload| | |
@results[properties[:correlation_id]].push(payload.to_i) | |
end | |
end | |
def call(n) | |
correlation_id = SecureRandom.uuid | |
@x.publish(n.to_s, | |
:routing_key => @server_queue, | |
:correlation_id => correlation_id, | |
:reply_to => @reply_queue.name) | |
result = @results[correlation_id].pop | |
@results.delete correlation_id # to prevent memory leak | |
result | |
end | |
end | |
client = FibonacciClient.new(conn, "rpc_queue") | |
puts " [x] Requesting fib(30)" | |
response = client.call(30) | |
puts " [.] Got #{response}" | |
conn.close | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment