rabbitMQ 的简单模式

筅森魡賤 提交于 2019-12-06 23:33:27

生产者:

# !/usr/bin/env python
# -*- coding: utf-8 -*-

import pika

# 创建连接对象
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
# 获取频道对象
channel = connection.channel()

# 创建队列
channel.queue_declare(queue='hello')

# 向队列插入数据
channel.basic_publish(exchange='',
                      routing_key='hello',
                      body='Hello 12334!')

print("[x] Sent '生产者发送消息'")
connection.close()

  

消费者:

# !/usr/bin/env python
# -*- coding: utf-8 -*-

import pika

connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()

# 声明队列
channel.queue_declare(queue='hello')

def callback(ch, method, properties, body):

    print(" [x] Received %s" % body)
    ch.basic_ack(delivery_tag=method.delivery_tag)   # 应答信号

channel.basic_consume(queue='hello',
                      on_message_callback=callback,
                      # auto_ack=True)       # 无应答模式
                      auto_ack=False)     # 应答模式

print(' [x] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()

  

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!