惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

J
Java Code Geeks
Martin Fowler
Martin Fowler
MongoDB | Blog
MongoDB | Blog
博客园 - Franky
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Microsoft Security Blog
Microsoft Security Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
博客园_首页
腾讯CDC
D
Docker
The Cloudflare Blog
量子位
爱范儿
爱范儿
L
LangChain Blog
博客园 - 三生石上(FineUI控件)
博客园 - 司徒正美
aimingoo的专栏
aimingoo的专栏
Blog — PlanetScale
Blog — PlanetScale
Jina AI
Jina AI
Apple Machine Learning Research
Apple Machine Learning Research
Hugging Face - Blog
Hugging Face - Blog
博客园 - 聂微东
Vercel News
Vercel News
MyScale Blog
MyScale Blog

Jiajun的技术笔记

你好,2026! TiDB 源码阅读(六):TiDB Coprocessor 源码解析 性能优化的核心思想 TiDB 源码阅读(五):索引 TiDB 源码阅读(四):AST、逻辑计划、物理计划 CockroachDB Serverless Architecture podman 无故退出 Cursor Control-L (CTRL-L) Keyboard Shortcuts in Terminal Replace docker with podman Using xmonad with xfce4 A RC script for freebsd frpc 自己动手写一个k8s controller AI 会取代你的(编程)岗位吗? 自建DERP服务器提升Tailscale连接速度(使用Nginx转发) 自动升级Docker容器 再读《程序员修炼之道-从小工到专家》 让浏览器下载文件 再读《软件随想录》/《黑客与画家》/《软技能》 HTTP 压力测试中的 Coordinated Omission 2的补码 编程语言中的 context 是什么? flutter macOS 构建出错 Flatpak 使用小记 Golang CAS 操作是怎么实现的 PostgreSQL 当MQ来使用 Clash 结合 工作VPN 的网络设计 使用 PostgreSQL 搭建 JuiceFS PostgreSQL 配置优化和日志分析 有GitHub Copilot?那就可以搭建你的ChatGPT4服务 窗口函数的使用(以PG为例)
Python RQ(Redis Queue)添加gevent支持
Jiajun Huang · 2019-04-18 · via Jiajun的技术笔记

python-rq简单好用,但缺点是,默认的实现是使用fork的模式,关于这点可以看 python-rq源码阅读与分析

所以我们要对他进行改造,每次执行任务,我们就使用一个coroutine。gevent的文档中这样写道:

Patching should be done as early as possible in the lifecycle of the program.

因此,我们在最上面就开始进行 monkey patch。此外,我把queue定义在了 jobs/queue.py 里。直接上代码:

# worker.py
import gevent.monkey
gevent.monkey.patch_all()  # noqa

import logging
from rq.worker import (
    Worker,
    WorkerStatus,
)
import redis

from config import config
from jobs import (
    money_q,
    message_q,
)


class GeventWorker(Worker):
    def execute_job(self, job, queue):
        self.set_state(WorkerStatus.BUSY)
        self.log.debug("gonna spawn a greenlet to execute job %s from queue", job, queue)
        gevent.spawn(self.perform_job, job, queue).join()
        self.log.debug("job %s from queue %s executed", job, queue)
        self.set_state(WorkerStatus.IDLE)


def gevent_worker(queues):
    worker = GeventWorker(
        queues=queues,
        connection=redis.StrictRedis.from_url(config.WORKER_BROKER)
    )
    worker.work()


if __name__ == "__main__":
    gevent_worker([money_q, message_q])
# queue.py
from rq import Queue
import redis

from config import config

__conn = redis.StrictRedis.from_url(config.WORKER_BROKER)

money_q = Queue("money", connection=__conn)
message_q = Queue("message", connection=__conn)

解释一下实现原理:

首先阅读 rq 默认的worker实现,就会发现,所有的worker都有 execute_job 这个方法,因此我们继承 Worker 并且 重写这个方法,在我们的实现里,新起一个coroutine来执行相关代码。



相关文章