RBMQ中python案例一:簡單模式

一、生產者與消費者模式之 簡單模式,原理圖

 

 

 

二、生產者產生消息

import json
import pika
import datetime

# 生產者 producer.py
def get_message():
    # 產生消息入口處
    for i in range(100):  # 生成10條消息
        message = json.dumps({'id': "10000%s" % i, "amount": 100 * i, "name": "melon", "createtime": str(datetime.datetime.now())})
        producer(message)
        print('i',i)

def producer(message):
    # 獲取與rabbitmq 服務的連接,虛擬隊列需要指定參數 virtual_host,如果是默認的可以不填(默認爲/),也可以自己創建一個
    # 報錯StreamLostError: ('Transport indicated EOF',) 是因爲將端口 5672 寫成 15672
    connection = pika.BlockingConnection(pika.ConnectionParameters(virtual_host='/melon_demo',host='82.156.19.94', port=5672, credentials=pika.PlainCredentials('guest', 'guest')))
    # 創建一個 AMQP 信道(Channel),建造一個大郵箱,隸屬於這家郵局的郵箱
    channel = connection.channel()
    # 聲明消息隊列melon.msg.demo.queue ,消息將在這個隊列傳遞,如不存在,則創建
    channel.queue_declare(queue='melon.msg.demo.queue')
    # 向隊列插入數值 routing_key的隊列名爲melon.msg.demo.queue,body 就是放入的消息內容,exchange指定消息在哪個隊列傳遞,
    # 這裏是空的exchange但仍然能夠發送消息到隊列中,因爲我們使用的是我們定義的空字符串exchange(默認的exchange)
    # exchange指定四種模式:direct(默認),fanout, topic, 和headers
    channel.basic_publish(exchange='', routing_key='melon.msg.demo.queue', body=message)
    # 關閉連接
    connection.close()


if __name__ == "__main__":
   get_message()  # 程序執行入口

 

三、消費者消費消息

 

 

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# 消費者 receive.py
import time
import pika
# 建立與rabbitmq的連接
credentials = pika.PlainCredentials("guest","guest")
connection = pika.BlockingConnection(pika.ConnectionParameters(virtual_host='/melon_demo',host='82.156.19.94', port=5672,credentials=credentials))
channel = connection.channel()
channel.queue_declare(queue="melon.msg.demo.queue")

def callback(ch,method,properties,body):
    print('body',body)
    time.sleep(100)
    print("消費者接收到了任務:%r"%body.decode("utf8"))
    # 有消息來臨,立即執行callback,沒有消息則夯住,等待消息
    # 老百姓開始去郵箱取郵件啦,隊列名字是水許傳
# def basic_consume(self,
#                       queue,
#                       on_message_callback,
#                       auto_ack=False,
#                       exclusive=False,
#                       consumer_tag=None,
#                       arguments=None):
# 這個參數的調用有所改動
# 第一個參數是隊列
# 第二個是回調函數
# 第三個這是auto_ack=True 使用自動確認模式
channel.basic_consume("melon.msg.demo.queue",callback,True)
# 開始消費,接收消息
channel.start_consuming()

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章