文章目录
生产者和消费者分开
生产者
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
import time import threading import random import redis import json # 导入脚本中用到的包 class Producter(threading.Thread): def __init__(self): super().__init__() self.queue = redis.Redis() def run(self) -> None: while True: a = random.randint(1, 100) b = random.randint(1, 100) print(f"生产者产生了两个数字 {a},{b}") self.queue.rpush('producter',json.dumps((a, b))) # 把(a,b)放入队列 time.sleep(2) if __name__ == '__main__': producter = Producter() producter.start() |
运行后生产者想redis list 中填充元素
在redis 客户端 查看队列中的元素
消费者:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
import time import threading import random import redis import json class Consumer(threading.Thread): def __init__(self): super().__init__() self.queue = redis.Redis() def run(self) -> None: while True: num_tuple = self.queue.blpop("producter") """ 返回并删除名称为在keys中的list中的首元素,如果list为空,则会一直阻塞等待 keys: key列表 timeout: 超时等待时间,0为一直等待 redis.blpop('list') """ a,b = json.loads(num_tuple[1].decode('utf-8')) print(f"消费一组{num_tuple}") time.sleep(random.randint(0,10)) if __name__ == '__main__': threads = [] for t in range(10): c = Consumer() threads.append(c) for c in threads: c.start() for i in threads: i.join() |