RabbitMQ須要 erlang 和pikapython
1.RabbitMQ和erlang版本必須匹配,不然就報沒有進程錯誤windows
2.RabbitMQ的erlang.cookie和windows下的erlang.cookie必須一致cookie
在windows安裝RabbitMQ須要配置環境變量,一個是erlang環境變量,一個是RabbitMQ的環境變量切記!函數
發送端:生產者spa
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
import
pika
connection
=
pika.BlockingConnection(
pika.ConnectionParameters(
'localhost'
))
channel
=
connection.channel()
#聲明一個管道,在管道里發消息
#聲明queue
channel.queue_declare(queue
=
'hello'
)
#在管道里還得聲明一個隊列
channel.basic_publish(exchange
=
'',
routing_key
=
'hello'
,
#就是列隊queue名字
body
=
'Hello World'
#消息內容
)
print
(
" [x] Sent 'Hello World!'"
)
connection.close()
#不用關閉管道,關閉鏈接就行
|
接收端:消費者code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
import
pika
# 創建到達RabbitMQ Server的connection
# 此處RabbitMQ Server位於本機-localhost
connection
=
pika.BlockingConnection(pika.ConnectionParameters(
'localhost'
))
channel
=
connection.channel()
# 聲明queue,確認要從中接收message的queue
# queue_declare函數是冪等的,可運行屢次,但只會建立一次
# 若能夠確信queue是已存在的,則此處可省略該聲明,如producer已經生成了該queue
# 但在producer和consumer中重複聲明queue是一個好的習慣
channel.queue_declare(queue
=
'hello'
)
print
(
' [*] Waiting for messages. To exit press CTRL+C'
)
# 定義回調函數
# 一旦從queue中接收到一個message回調函數將被調用
# ch:channel
# method:
# properties:
# body:message
def
callback(ch, method, properties, body):
print
(
" [x] Received %r"
%
body)
# 從queue接收message的參數設置
# 包括從哪一個queue接收message,用於處理message的callback,是否要確認message
# 默認狀況下是要對消息進行確認的,以防止消息丟失。
# 此處將no_ack明確指明爲True,不對消息進行確認。
channel.basic_consume(callback,
queue
=
"hello"
,
no_ack
=
True
)
# 開始循環從queue中接收message並使用callback進行處理
channel.start_consuming()
|