Skip to content

Instantly share code, notes, and snippets.

@carlhoerberg
Created May 2, 2014 02:06
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carlhoerberg/96eb730f4c533f61a856 to your computer and use it in GitHub Desktop.
Save carlhoerberg/96eb730f4c533f61a856 to your computer and use it in GitHub Desktop.
#!/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