基于消息队列的订水系统如何实现代码
以下是一个基于消息队列的订水系统的Python代码示例:
import time
import random
import threading
import queue
# 消息队列
msg_queue = queue.Queue()
# 生产者线程
class ProducerThread(threading.Thread):
def run(self):
while True:
# 随机生成订单
order_id = random.randint(1, 100)
print(f"订单 {order_id} 已生成")
# 将订单放入消息队列
msg_queue.put(order_id)
# 随机等待1-5秒
time.sleep(random.randint(1, 5))
# 消费者线程
class ConsumerThread(threading.Thread):
def run(self):
while True:
# 从消息队列中获取订单
order_id = msg_queue.get()
print(f"订单 {order_id} 正在处理中...")
# 模拟处理订单
time.sleep(random.randint(1, 3))
print(f"订单 {order_id} 处理完成")
# 创建生产者和消费者线程并启动
producer_thread = ProducerThread()
consumer_thread = ConsumerThread()
producer_thread.start()
consumer_thread.start()
这个订水系统的实现中,生产者线程随机生成订单并将其放入消息队列中,消费者线程从消息队列中获取订单并模拟处理。可以根据实际需求进行修改和扩展。
原文地址: https://www.cveoy.top/t/topic/bIiG 著作权归作者所有。请勿转载和采集!