【Python】Redis 实现队列

Python语言 小铁匠 2019-08-01

Redis 实现队列

命令说明

rpush : 往列表右侧推入数据
blpop : 客户端阻塞直到队列有值输出

简单队列实现
client.php
import time
import redis
import random
from apscheduler.schedulers.blocking import BlockingScheduler

pool = redis.ConnectionPool(host="127.0.0.1", port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)

def job_task():
    r.rpush("task:test1", random.randint(1000, 9999))
    time.sleep(1)
    r.rpush("task:test2", random.randint(1000, 9999))


if __name__ == "__main__":
    sched = BlockingScheduler()
    sched.add_job(job_task, "interval", max_instances = 10, seconds = 5)
    sched.start()

启用一个定时任务,每5秒钟往task:test1task:test2队列中推送一条数据

server.php
import redis
import time

pool = redis.ConnectionPool(host="127.0.0.1", port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)

while True:
    test = r.blpop({"task:test1", "task:test2"}, timeout=3)
    if test == None:
        print("nothing.")
        time.sleep(2)
    else: 
        print("任务名:%s" % test[0])
        print("任务值:%s" % test[1])
        print("当前时间:%s" % time.strftime("%H:%M:%S"))

设置blpop阻塞时间为3秒,当有数据出队时打印数据信息,当队列没有数据时,程序睡眠2秒重新检查队列是否有数据出队

执行
python server.py
python client.py

server 执行结果

任务名:task:test2
任务值:1458
当前时间:11:16:22
nothing.
任务名:task:test1
任务值:5949
当前时间:11:16:27
任务名:task:test2
任务值:8807
当前时间:11:16:27
......
------ 本文结束 感谢阅读 ------