RabbitMQ & bunny

 

安装RabbitMQ, 安装成功后,RAMQ已经启动好了,访问localhost:5672进入到欢迎界面,表示安装成功

也可以通过命令:rabbitmqctl status查看状态

$ sudo apt-get install rabbitmq-server
rabbitmqctl status

 

安装client:

https://github.com/ruby-amqp/bunny

gem install bunny

 

sender.rb 发送消息,bunny将消息交给rabbitmq保管,等待处理

这里向队列中发送了10000个"hello, world"

执行 ruby sender.rb后,通过sudo rabbitmqctl list_queues查看队列情况

Listing queues ...
hello    10000
...done.

 

#!/usr/bin/env ruby
# encoding: utf-8

require "bunny"

conn = Bunny.new(:automatically_recover => false)
conn.start

ch = conn.create_channel
q = ch.queue("hello")

1.upto 10000 do 
ch.default_exchange.publish("Hello World!", :routing_key => q.name)
puts " [x] Sent 'Hello World!'"
end

conn.close

 

recevier.rb 接收消息, 可以启动多个worker,同时接收消息,假设消息处理的时间比较长,(这里用了sleep 10),  查看是否接收正常,发现只有1个worker能接收到消息,而且如果中断这个worker后,执行

ruby recevier.rb 发现没有执行的消息不见了。。。

 

#!/usr/bin/env ruby
# encoding: utf-8

require "bunny"

conn = Bunny.new(:automatically_recover => false)
conn.start

ch = conn.create_channel
q = ch.queue("hello")

begin
  puts " [*] Waiting for messages. To exit press CTRL+C"
  q.subscribe(:block => true) do |delivery_info, properties, body|
    puts " [x] Received #{Time.now} #{body}"
    #sleep 1
  end
rescue Interrupt => _
  conn.close

  exit(0)
end

 

其他资料:

http://rubybunny.info/articles/connecting.html

 

http://www.rabbitmq.com/tutorials/tutorial-one-ruby.html

http://cloudfoundry-doc.csdn.net/services/rabbitmq/ruby-rabbitmq.html

你可能感兴趣的:(rabbitmq,消息队列,bunny)