一、基于Queue实现的生产者消费者模型
import Queue
import threading
message = Queue.Queue(10)
def producer(i):
while True:
message.put(i)
def consumer(i):
while True:
msg = message.get()
for i in range(12):
t = threading.Thread(target=producer, args=(i,))
t.start()
for i in range(10):
t = threading.Thread(target=consumer, args=(i,))
t.start()
二、Rabbitmq的生产者消费者模型基本使用
1、对于RabbitMQ来说,生产和消费不再针对内存里的一个Queue对象,而是某台服务器上的RabbitMQ Server实现的消息队列
2、生产者
import pika
# 无密码
# 创建连接
# connection = pika.BlockingConnection(pika.ConnectionParameters('127.0.0.1'))
# 有密码
# 用户登录
credentials = pika.PlainCredentials("admin","admin")
# 创建连接
connection = pika.BlockingConnection(pika.ConnectionParameters('101.133.225.166',credentials=credentials))
# 创建信道
channel = connection.channel()
# 创建队列,或声明已有队列
channel.queue_declare(queue='myqueue')
# 发布消息
channel.basic_publish(exchange='', routing_key='myqueue', body='hello world')
# 断开连接
connection.close()
3、消费者
import pika
credentials = pika.PlainCredentials("admin","admin")
connection = pika.BlockingConnection(pika.ConnectionParameters('101.133.225.166',credentials=credentials))
channel = connection.channel()
channel.queue_declare(queue='myqueue')
def callback(ch, method, properties, body):
print("消费者接受到了任务: %r" % body)
channel.basic_consume(queue='myqueue', on_message_callback=callback, auto_ack=True)
channel.start_consuming()