rabbitmq 生产者和消费者

# 消费者
import pika,time

consumer = pika.BlockingConnection\
    (pika.ConnectionParameters('localhost'))#创建socket连接
channel = consumer.channel()#创建管道
channel.queue_declare(queue='name',durable=True)# durable=True server挂掉之后队列还在,消息持久话还需要设置delivery_mode=2

def backcall(ch,method,properties,body):#参数body是发送过来的消息。
    print(ch,method,properties)
    time.sleep(15)
    print('[x] Received %r'%body)

channel.basic_consume(backcall,#回调函数。执行结束后立即执行另外一个函数返回给发送端是否执行完毕。
                      queue='name',
                      # no_ack=True # 不会告知服务端我是否收到消息。一般注释。
                      properties=pika.BasicProperties(
                      delivery_mode=2 # 消息持久化
                       )
                       )#如果注释掉,对方没有收到消息的话不会将消息丢失,始终在队列里等待下次发送。

print('waiting for message To exit   press CTRL+C')
channel.start_consuming()#启动后进入死循环。一直等待消息。



# 生产者
import pika
connection = pika.BlockingConnection(
    pika.ConnectionParameters('localhost'))#建立一个最基本的socket
chanel = connection.channel()#声明一个管道

chanel.queue_declare(queue='name')#给管道创建一个队列,参数是管道队列名。

chanel.basic_publish(exchange='',
                     routing_key='name',
                     body ='HELLO WORD!')#要发送的消息。
print( '发出一个消息')
connection.close()#关闭

猜你喜欢

转载自blog.csdn.net/wu0che28/article/details/82383543