RabbitMQ向项目主机广播事件通知

我们这有许多项目,每个项目的服务器组,需要接受一些公共通知,可以里用RabbitMQ的fanout交换机来广播通知。具体做法是,项目里的每个主机都订阅到broker,并创建fanout交换机,中央控制台需要发通知时,也连到这个交换机,并发送消息,这条消息就会被广播到每一个项目主机。结构图如下:

fanout

如图,在项目主机创建了fanout交换机后,控制台如何访问这个交换机呢?这里有个关键因素,即交换机的名字必须双方都知道。可以用项目名作为交换机的名字。如下是consume代码参考:

#!/usr/bin/env ruby
# encoding: utf-8
require "bunny"
 
while true
  begin
    conn = Bunny.new(:host => "1.1.1.1", :port => 5672, :vhost => "/", :user => "guest", :pass => "***")
    conn.start
    ch = conn.create_channel
    x  = ch.fanout("project_name")
    q  = ch.queue("").bind(x)
    q.subscribe(:block => true) do |delivery_info, metadata, payload|
        puts "Received #{payload}"
    end
 
  rescue Exception => e 
    puts e.message 
  end
end

如下是publish代码参考:

#!/usr/bin/env ruby
# encoding: utf-8
require "bunny"
 
conn = Bunny.new(:host => "1.1.1.1", :port => 5672, :vhost => "/", :user => "guest", :pass => "***")
conn.start
ch = conn.create_channel
x  = ch.fanout("project_name")
1000.times do 
  data = rand.to_s
  x.publish(data)
end

上述consume和publish代码,约定使用project_name作为交换机名字,这样控制台和项目服务器的消息通道,就通过RabbitMQ连通起来了。

此条目发表在Common分类目录,贴了标签。将固定链接加入收藏夹。