前面一章已經介紹了rabbitmq在python中傳遞消息,那麼作爲比較強大的rabbitmq中間件,他如何實現在ruby上傳遞消息以及和python中間傳遞消息呢?
1.安裝rabbtmq的服務器,(前一篇已經介紹過了)
2. gem install bunny --安裝bunny的gem包,這樣就可以在客戶端用ruby訪問了
我們寫一個send.rb
require "bunny" --引入bunny
conn = Bunny.new(:hostname => "localhost") conn.start --鏈接服務器
ch = conn.create_channel --創建通道
q = ch.queue("hello") --創建隊列hello ch.default_exchange.publish("Hello World!", :routing_key => q.name) puts " [x] Sent 'Hello World!'"conn.close
然後在寫一個 receive.rb
require "bunny"
conn = Bunny.new conn.start ch = conn.create_channel q = ch.queue("hello")
puts " [*] Waiting for messages in #{q.name}. To exit press CTRL+C"
q.subscribe(:block => true) do |delivery_info, properties, body|
puts " [x] Received #{body}"
# cancel the consumer to exit
delivery_info.consumer.cancel
end
好了,運行下就好了!
$ ruby send.rb
" [x] Sent 'Hello World!'"
$ ruby receive.rb
”[x] Received Hello World!"
這是ruby和ruby之間通信,那麼我們在加入python的代碼
send.py
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel()
channel.queue_declare(queue='hello')
channel.basic_publish(exchange='',
routing_key='hello',
body='Hello World!')
print " [x] Sent 'Hello World!'"
connection.close()
我們在運行下python send.py
" [x] Sent 'Hello World!'"
ruby receive.rb
" [x] Receive 'Hello World!'"