Skip to content

Commit 3ef59c7

Browse files
author
Michael Klishin
committed
Tutorial 6 ported to Bunny
1 parent 6e2773c commit 3ef59c7

File tree

2 files changed

+113
-0
lines changed

2 files changed

+113
-0
lines changed

ruby/rpc_client.rb

+62
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
#!/usr/bin/env ruby
2+
# encoding: utf-8
3+
4+
require "bunny"
5+
6+
conn = Bunny.new
7+
conn.start
8+
9+
ch = conn.create_channel
10+
11+
class FibonacciClient
12+
attr_reader :reply_queue
13+
14+
def initialize(ch, server_queue)
15+
@ch = ch
16+
@x = ch.default_exchange
17+
18+
@server_queue = server_queue
19+
@reply_queue = ch.queue("", :exclusive => true)
20+
end
21+
22+
def call(n)
23+
correlation_id = self.generate_uuid
24+
25+
@x.publish(n.to_s,
26+
:routing_key => @server_queue,
27+
:correlation_id => correlation_id,
28+
:reply_to => @reply_queue.name)
29+
30+
response = nil
31+
@reply_queue.subscribe(:block => true) do |delivery_info, properties, payload|
32+
if properties[:correlation_id] == correlation_id
33+
response = payload.to_i
34+
35+
delivery_info.consumer.cancel
36+
end
37+
end
38+
39+
response
40+
end
41+
42+
protected
43+
44+
def generate_uuid
45+
# very naive but good enough for code
46+
# examples
47+
"#{rand}#{rand}#{rand}"
48+
end
49+
end
50+
51+
52+
begin
53+
client = FibonacciClient.new(ch, "rpc_queue")
54+
puts " [x] Requesting fib(30). Collecting replies from #{client.reply_queue.name}"
55+
response = client.call(30)
56+
puts " [.] Got #{response}"
57+
rescue Interrupt => _
58+
puts " [*] Shutting down..."
59+
60+
ch.close
61+
conn.close
62+
end

ruby/rpc_server.rb

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
#!/usr/bin/env ruby
2+
# encoding: utf-8
3+
4+
require "bunny"
5+
6+
conn = Bunny.new
7+
conn.start
8+
9+
ch = conn.create_channel
10+
11+
class FibonacciServer
12+
13+
def initialize(ch)
14+
@ch = ch
15+
end
16+
17+
def start(queue_name)
18+
@q = @ch.queue(queue_name)
19+
@x = @ch.default_exchange
20+
21+
@q.subscribe(:block => true) do |delivery_info, properties, payload|
22+
n = payload.to_i
23+
r = self.class.fib(n)
24+
25+
puts " [*] Serving a request: #{n} => #{r}. Replying to #{properties.reply_to}"
26+
27+
@x.publish(r.to_s, :routing_key => properties.reply_to, :correlation_id => properties.correlation_id)
28+
end
29+
end
30+
31+
32+
def self.fib(n)
33+
case n
34+
when 0 then 0
35+
when 1 then 1
36+
else
37+
fib(n - 1) + fib(n - 2)
38+
end
39+
end
40+
end
41+
42+
begin
43+
server = FibonacciServer.new(ch)
44+
puts " [*] Waiting for requests..."
45+
server.start("rpc_queue")
46+
rescue Interrupt => _
47+
puts " [*] Shutting down..."
48+
49+
ch.close
50+
conn.close
51+
end

0 commit comments

Comments
 (0)