生产者
import pika
import sys
username = 'guest'
pwd = 'guest'
user_pwd = pika.PlainCredentials(username, pwd)
s_conn = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
chan = s_conn.channel()
chan.queue_declare(queue='hello')
chan.basic_publish(exchange='', routing_key='hello', body='你好啊,兄弟!')
print('生产者 send 你好, 兄弟!')
s_conn.close()
消费者
# coding: utf-8
import time
import pika
username = 'guest'
pwd = 'guest'
user_pwd = pika.PlainCredentials(username, pwd)
s_conn = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
chan = s_conn.channel()
chan.queue_declare(queue='hello')
def callback(ch, method, properties, body):
print("[消费者] recv %s" % str(body, encoding='UTF-8'))
time.sleep(20)
print("[x] Done")
print("method.delivery_tag",method.delivery_tag)
ch.basic_ack(delivery_tag=method.delivery_tag) # 告诉服务器消息已经消化掉了 更改这里
chan.basic_consume(queue='hello', on_message_callback=callback, auto_ack=False) #更改这里
print('[消费者] waiting for msg .')
chan.start_consuming()#开始循环取消息
网友评论