先安装一个库吧,没有这个库,那是肯定不行的。
$ gem install amqp
consumer
然后做一个读消息的程序
| 123456789101112131415161718192021 |
require
'amqp'
def
run
config
=
{
:host
=>
'localhost'
}
AMQP
.
start
(
config
)
do
|
connection
|
channel
=
AMQP
:
:Channel
.
new
(
connection
)
queue
=
channel
.
queue
(
''
,
:auto_delete
=>
true
)
exchange
=
channel
.
direct
'ex.direct'
queue
.
bind
(
exchange
,
:routing_key
=>
'tasks'
)
.
subscribe
do
|
headers
,
payload
|
puts
payload
end
stopper
=
Proc
.
new
{
connection
.
close
{
EventMachine
.
stop
}
}
Signal
.
trap
"INT"
,
stopper
end
end
run
|
producer
然后做一个发布消息的程序
| 123456789101112131415161718 |
require
'amqp'
def
run
config
=
{
:host
=>
'localhost'
}
AMQP
.
start
(
config
)
do
|
connection
,
open_ok
|
channel
=
AMQP
:
:Channel
.
new
(
connection
)
exchange
=
channel
.
direct
'ex.direct'
msg
=
'Hello, world'
exchange
.
publish
(
msg
,
:routing_key
=>
'tasks'
)
do
puts
"sent:
#{
msg
}
"
connection
.
close
{
EventMachine
.
stop
}
end
end
end
run
|
実行
先 ruby consumer.rb 打开读程序端
然后 ruby producer.rb 打开写程序端
你就会看到程序两端都出现hello world !!
这是最最简单的。