# -*- 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()
来源:https://blog.csdn.net/qq_35899407/article/details/100669262