producer生產者
Python代碼實現
import pika
# 指定遠程rabbitmq的用戶名密碼
username = 'admin'
pwd = '123123'
user_pwd = pika.PlainCredentials(username, pwd)
# 創建連接
s_conn = pika.BlockingConnection(pika.ConnectionParameters('120.27.221.81', credentials=user_pwd))
# 在連接上創建一個頻道
chan = s_conn.channel()
# 聲明一個隊列,生產者和消費者都要聲明一個相同的隊列,用來防止萬一某一方掛了,另一方能正常運行
chan.queue_declare(queue='hello')
chan.basic_publish(exchange='', # 交換機
routing_key='hello', # 路由鍵,寫明將消息發往哪個隊列,本例是將消息發往隊列hello
body='hello Arvin') # 生產者要發送的消息
print('[生產者] hello Arvin.')
# 當生產者發送完消息後,可選擇關閉連接
s_conn.close()
執行代碼:
python ./RabbitMQ/send.py
打印消息:
[生產者] hello Arvin.
Ubuntu服務器查看消息
$ rabbitmqctl list_queues
Listing queues ...
hello 1
consumer消費者
代碼實現
import pika
# 指定遠程rabbitmq的用戶名密碼
username = 'admin'
pwd = '123123'
user_pwd = pika.PlainCredentials(username, pwd)
# 創建連接
s_conn = pika.BlockingConnection(pika.ConnectionParameters('192.168.1.240', credentials=user_pwd))
# 在連接上創建一個頻道
chan = s_conn.channel()
# 聲明一個隊列,生產者和消費者都要聲明一個相同的隊列,用來防止萬一某一方掛了,另一方能正常運行
chan.queue_declare(queue='hello')
# 定義一個回調函數,用來接收生產者發送的消息
def callback(ch, method, properties, body):
print("[消費者] recv %s" % body)
chan.basic_consume(callback, # 調用回調函數,從隊列裏取消息
queue='hello', # 指定取消息的隊列名
no_ack=True) # 取完一條消息後,不給生產者發送確認消息,默認是False的,即 默認給rabbitmq發送一個收到消息的確認,一般默認即可
print('[消費者] waiting for msg .')
# 開始循環取消息
chan.start_consuming()
執行代碼:
python ./RabbitMQ/receive.py
打印消息:
[消費者] waiting for msg .
[消費者] recv b'hello Arvin'
[消費者] recv b'hello Ane'
Ubuntu服務器查看消息
$ rabbitmqctl list_queues
Listing queues ...
hello 0