問題基本上是:兩個路由密鑰都未設置,顯然交換和隊列需要密鑰。
發件人:
require "bunny"
NAME_OF_QUEUE = "yomtvraps"
NAME_OF_EXCHANGE = "yomtvraps"
conn = Bunny.new(:automatically_recover => false)
conn.start
ch = conn.create_channel
q = ch.queue("yomtvraps")
puts "\tthere was already a queue named \"#{NAME_OF_QUEUE}\"" if conn.queue_exists?(NAME_OF_QUEUE)
puts "\tthere was already a exchange named \"#{NAME_OF_EXCHANGE}\"" if conn.exchange_exists?(NAME_OF_EXCHANGE)
exchange = ch.direct(NAME_OF_EXCHANGE, :durable => true)
exchange.publish("Hello World!", :routing_key => NAME_OF_QUEUE)
puts " [x] Sent 'Hello World!'"
conn.close
接收機:
require "bunny"
NAME_OF_QUEUE = "yomtvraps"
NAME_OF_EXCHANGE = "yomtvraps"
conn = Bunny.new(:automatically_recover => false)
conn.start
ch = conn.create_channel
q = ch.queue(NAME_OF_QUEUE)
exchange = ch.direct(NAME_OF_EXCHANGE, :durable => true) # this is how logstash
begin
puts " [*] Waiting for messages. To exit press CTRL+C"
q.bind(exchange, :routing_key => NAME_OF_QUEUE).subscribe(:block => true) do |delivery_info, properties, body|
puts " [x] Received #{body}"
end
rescue Interrupt => _
conn.close
exit(0)
end
輸出(在兩個不同的終端):
$ ruby send_exchange.rb
there was already a queue named "yomtvraps"
there was already a exchange named "yomtvraps"
[x] Sent 'Hello World!'
$ ruby receive_queue.rb
[*] Waiting for messages. To exit press CTRL+C
[x] Received Hello World!