ruby - rabbitmq, bunny 与 amqp 入门 快速入门, 1小时吧.

访问量: 33

rabbitmq:  是消息处理服务器.     https://www.rabbitmq.com

amqp:  advanced message queue protocel  . 有各种语言的实现, 包括ruby的.  https://github.com/ruby-amqp/amqp

bunny:  对 ruby-amqp 的封装, 让其对rabbitmq的使用更加方便.   https://github.com/ruby-amqp/bunny

rabbitmq的安装: 

参考: https://www.rabbitmq.com/install-debian.html

sudo apt-add-repository 'deb http://www.rabbitmq.com/debian/ testing main'
curl http://www.rabbitmq.com/rabbitmq-signing-key-public.asc | sudo apt-key add -

# 安装
sudo apt-get update
sudo apt-get install rabbitmq-server

# 启动服务器
sudo rabbitmq-plugins enable rabbitmq_management
sudo service rabbitmq-server restart

# 安装rabbitmqadmin
wget http://localhost:15672/cli/rabbitmqadmin
chmod +x rabbitmqadmin
sudo mv rabbitmqadmin /usr/local/sbin

这个东东跟 cache server 一样 . 类似于: memcached.    都是底层的服务.  

也类似于数据库, exchange就是 table, queue 就是 row(一条记录)

我们可以使用命令行来查看:  

$ 登陆 , 跟mysql 一样.

$ rabbitmqadmin -H localhost -u guest -p guest list vhosts
+------+----------+
| name | messages |
+------+----------+
| /    | 32       |
+------+----------+

(注意, 默认的用户名和密码都是guest ,  可以在启动的时候进行配置)

如果输错了用户名和密码, 会看到: *** Access refused: /api/vhosts?columns=name,messages
  
下面,是列出所有的 exchanges:  

$ rabbitmqadmin list exchanges
+---------------------+---------+
|        name         |  type   |
+---------------------+---------+
| nba.score           | fanout  |   
+---------------------+---------+

可以看出, rabbitmq 保存消息 跟mysql是差不多的. 类似于数据库.
fanout:  最简单的模式, 像风扇一样出去. (传递给所有人)
direct:  传递给某个人. (具备对应的routing key ) 
topic:  把内容传递给关心这个话题的人. (例如: 发送天气消息,给所有关心 weather的人)

具体的解释参考:  https://blog.csdn.net/chendaoqiu/article/details/48440633

也可以只列出几个列:

$ rabbitmqadmin list queues name node messages 
+-----------------------------+-------------------+----------+
|            name             |       node        | messages |
+-----------------------------+-------------------+----------+
| aaron                       | rabbit@instance-2 | 0        |
| bob                         | rabbit@instance-2 | 0        |
| joe                         | rabbit@instance-2 | 0        |


一个非常简单的例子: 

require "rubygems"
require "bunny"

STDOUT.sync = true

# 链接 rabbit mq 服务器
conn = Bunny.new("amqp://guest:guest@localhost:5672")
conn.start

ch  = conn.create_channel
x   = ch.fanout("nba.scores")

# 开始 入队
ch.queue("joe",   :auto_delete => true).bind(x).subscribe do |delivery_info, metadata, payload|
  puts "#{payload} => joe"
end

ch.queue("aaron", :auto_delete => true).bind(x).subscribe do |delivery_info, metadata, payload|
  puts "#{payload} => aaron"
end

ch.queue("bob",   :auto_delete => true).bind(x).subscribe do |delivery_info, metadata, payload|
  puts "#{payload} => bob"
end

# 发送消息.   所有人都会听到.
x.publish("BOS 101, NYK 89").publish("ORL 85, ALT 88")

运行到这里就会出现结果: 

conn.close

订阅/RSS Feed

Subscribe

分类/category