pika 生产 消费 简单类

时光毁灭记忆、已成空白 提交于 2019-11-29 08:22:25
# -*- coding: utf-8 -*-
# by dl
import pika


class MessageQueue:
    def __init__(self,
                 host='localhost',
                 queueName='TestQueue',
                 exchange='',
                 body='Hello World',
                 consumer_tag=''):
        self.host = host
        self.queueName = queueName
        self.exchange = exchange
        self.body = body
        self.consumer_tag = consumer_tag

    def SPsend(self):
        connection = pika.BlockingConnection(pika.ConnectionParameters(self.host))
        channel = connection.channel()
        channel.queue_declare(queue=self.queueName)
        channel.basic_publish(exchange=self.exchange, routing_key=self.queueName, body=self.body)
        print("[x] Seng 'Hello World!;'")
        connection.close()
    
    # 这里的接收参数不能少
    def callback(self, ch, method, properties, body):
        print(body)

    def SPreceive(self):
        # 重新声明队列 以防先执行了接收函数
        connecton = pika.BlockingConnection(pika.ConnectionParameters(self.host))
        channel = connecton.channel()
        channel.queue_declare(self.queueName)
        channel.basic_consume(self.queueName,
                              self.callback,
                              self.consumer_tag)
        channel.start_consuming()


mq = MessageQueue()
mq.SPsend()
mq.SPreceive()

 

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