Python消息队列之Huey

发布时间 2023-12-28 09:16:21作者: X-Wolf

缘起:

之前在Python中使用最多的就是Celery, 同样的在这次项目中使用了Celery+eventlet的方式,但是由于具体执行的逻辑是使用的异步编写的, 当时就出现了一个问题,当使用httpx的AsyncClient发送一个网络请求的时候, 发生了阻塞, 导致整个程序无法完整执行. 于是就找替代方案, 于是这次就尝试使用了huey,最终可以实现, 但是为何Celery中执行会发生阻塞,Google中也有大佬提到了

 

github: https://github.com/coleifer/huey

特点:

- 简单

- 轻量

- 执行多种类型: redis,sqlite,file,memory

 

安装:

pip install huey

 

使用:

task.py

from huey import RedisHuey
from redis import ConnectionPool

redis_pool = ConnectionPool(host='127.0.0.1', port=6379, db=10, password="密码")
huey = RedisHuey('app', connection_pool=redis_pool)


@huey.task()
def count_beans(num):
    for i in range(num):
        print(i)
        time.sleep(3)
    return 'count beans'

启动消费者:

huey_consumer task.huey -k process -w 4

# windows下
huey_consumer.exe task.huey -k process -w 4

# -k: 指定worker类型, thread(默认), greenlet, process(windows下不支持)
# -w: 指定worker的数量, 同时有多少个消费者同时工作

# 还有其他的一些参数, 可以使用--help查看
# -l: 指定日志文件

 

主业务,将任务投递到队列中main.py

from task import count_beans

if __name__ == '__main__':
    res = count_beans(10)
    print(res)

 

整体使用感受,轻量,快速,清爽,还会有终端的时候,优雅处理方式