一年前给同事做了一场关于RabbitMQ的简单介绍,PPT在这里。
里面涉及的演示代码粘贴如下,语言是ruby,MQ库是bunny。跟流行的名为AMQP的库不同,bunny是同步的,使用相对简单。AMQP主要是异步,使用它需要异步编程的知识,参考这篇。
Fanout交换机的produce程序:
#!/usr/bin/env ruby # encoding: utf-8 require "bunny" conn = Bunny.new conn.start ch = conn.create_channel x = ch.fanout("test_fanout") 1000.times do data = rand.to_s x.publish(data) sleep 0.01 end
Fanout交换机的consume程序:
#!/usr/bin/env ruby # encoding: utf-8 require "bunny" conn = Bunny.new conn.start ch = conn.create_channel x = ch.fanout("test_fanout") q = ch.queue("").bind(x) q.subscribe(:block => true) do |delivery_info, metadata, payload| puts "Received #{payload}" end
Direct交换机的produce程序:
#!/usr/bin/env ruby # encoding: utf-8 require "bunny" conn = Bunny.new conn.start ch = conn.create_channel x = ch.direct("test_exchange") 1000.times do data = rand.to_s x.publish(data, :routing_key => 'test') sleep 0.01 end
Direct交换机的consume程序:
#!/usr/bin/env ruby # encoding: utf-8 require "bunny" conn = Bunny.new conn.start ch = conn.create_channel x = ch.direct("test_exchange") q = ch.queue("test_queue").bind(x, :routing_key => "test") q.subscribe(:block => true) do |delivery_info, metadata, payload| puts "Received #{payload}" end