ThinkPHP8 自建常驻队列消费者:信号处理、内存防泄漏与连接重连

2026-11-22 0 586

项目里有个对账任务,每天凌晨跑一次,原来是用 crontab 每五分钟拉起一次 php think reconcile。订单量在三万左右时还没事,一次跑一两分钟就退出来了。后来单量翻了一倍,有几天一次跑不完五分钟,crontab 又开始拉第二个进程。两拨进程同时挟持同一批订单,对出来的账金额翻倍,财务那边直接打电话过来问是不是系统出问题了。

那次之后把整个逻辑改成了常驻进程。这篇把踩过的坑整理一下——常驻进程不是”写个 while(true) 就完事”,真正花时间的是信号、内存、连接这几个地方。

先回答一个问题:为什么不用现成的 queue:work

装了 topthink/think-queue 之后直接 php think queue:work 就能消费,本身也是常驻的,而且已经带了 --memory 参数来限制内存。绝大多数场景用它就够了,没必要重复造轮子。

自建的动机通常来自业务侧:消费完成后要把消费耗时、失败次数上报到监控系统;需要按队列名动态切换不同的问题处理器;需要消费失败后落到一个专门的死信队列做人工干预;或者消费过程要复用某个初始化成本很高的资源(比如一个 ES 客户端、一组预热的字典数据)。这些东西插进 think-queue 的 worker 里比较别扭,自己控制循环反而更清楚。

所以本文的代码不是要替代 think-queue,而是把常驻进程本身要处理的几个问题讲清楚。看懂之后,无论是改 think-queue 的源码还是自己写,都知道该盯哪些点。

最小骨架

ThinkPHP 8 的自定义命令放在 app/command 目录下,然后在 config/console.php 里注册:

<?php

return [
    'commands' => [
        'queue:daemon' => appcommandQueueDaemon::class,
    ],
];

命令类继承 thinkconsoleCommand,重写 configure 和 execute。骨架先写出来:

<?php
declare(strict_types=1);

namespace appcommand;

use thinkconsoleCommand;
use thinkconsoleInput;
use thinkconsoleinputOption;
use thinkconsoleOutput;
use thinkfacadeLog;

class QueueDaemon extends Command
{
    protected Redis $redis;
    protected bool $running = true;
    protected int $memoryLimit = 134217728;   // 128MB
    protected string $queueName = 'default';
    protected int $sleepSeconds = 1;

    protected function configure()
    {
        $this->setName('queue:daemon')
            ->addOption('queue', null, Option::VALUE_OPTIONAL, '队列名', 'default')
            ->addOption('memory', null, Option::VALUE_OPTIONAL, '内存上限(MB)', 128)
            ->addOption('sleep', null, Option::VALUE_OPTIONAL, '空闲休眠秒数', 1)
            ->setDescription('常驻队列消费者');
    }

    protected function execute(Input $input, Output $output)
    {
        $this->queueName    = (string) $input->getOption('queue');
        $this->memoryLimit  = (int) $input->getOption('memory') * 1024 * 1024;
        $this->sleepSeconds = max(1, (int) $input->getOption('sleep'));

        $this->registerSignals();
        $this->connectRedis();

        while ($this->running) {
            $this->dispatchOnce($output);
            $this->checkMemory($output);
        }

        $this->redis->close();
        $output->writeln('daemon stopped');
        return 0;
    }
}

下面把 registerSignals、connectRedis、dispatchOnce、checkMemory 四个方法逐一写出来,每个方法对应一类问题。

信号:让进程能”好好下线”

最直接的想法是用 kill 或者 Ctrl+C 停掉进程。但默认行为是直接终止,正在处理的这条任务会被拦腰斩断——数据库写了一半、文件传到一半、Redis 里删了但数据库还没改。每次发版都来一次,迟早出事。

正确做法是注册信号处理,收到 SIGTERM 时只把 running 置成 false,主循环跑完当前任务后自然退出:

protected function registerSignals(): void
{
    // 开启异步信号,handler 立即执行,不用手动 dispatch
    pcntl_async_signals(true);

    $stop = function (int $signo) {
        // 不要在信号处理函数里做业务,这里只置标志
        $this->running = false;
    };

    pcntl_signal(SIGTERM, $stop);   // supervisor stop / kill 默认发这个
    pcntl_signal(SIGINT,  $stop);   // Ctrl+C
    pcntl_signal(SIGQUIT, $stop);   // kill -QUIT
}

两个必须注意的地方。

第一,信号处理函数里不要做业务。 处理函数运行在一个非常受限的上下文里,这时候打日志、写数据库、调 Redis 都可能和主流程产生竞争。只置标志,其余逻辑交回主循环判断,是最稳的写法。

第二,没开 pcntl_async_signals 的话,需要在循环里调 pcntl_signal_dispatch()。 不开异步信号,信号来了只是被挂起,得等到显式 dispatch 时才执行。而那段 sleep(1) 的空闲等待里,恰恰不会 dispatch,进程看起来”卡死”到下一次 pop 才响应。直接开异步,省掉这一层心智负担。

顺带说一下 sleep() 和信号的关系:PHP 的 sleep 在收到信号时会被中断并返回剩余秒数,所以即使休眠中收到 SIGTERM,最多也就等一秒就退出,不会出现”等十分钟才停”的尴尬。如果想要更灵敏,用 usleep(200000) 分小步睡,一次检查一次标志。

内存:进程为什么会越来越胖

常驻进程跑上一两天,top 里看到 RSS 从 40MB 涨到 200MB,然后被系统 OOM killer 干掉。原因无非几种:

  • 大数组没释放,留在某个全局变量或者单例里
  • 循环引用没被 GC 回收
  • 框架内部的日志缓冲、事件监听器越积越多
  • 数据库连接池里连接没关

彻底解决每一处泄漏很难,工程上更现实的做法是”给定阈值,到了就退出,靠守护进程重启”。这样内存最多撑到一个上限就重置,比花几周时间去追每一处引用实际得多。

protected function checkMemory(Output $output): void
{
    // true 表示包含分配器已申请但未返还给操作系统的页
    // 这个值更适合做阈值判断,不会因为一次大对象释放就立刻降下来
    $used = memory_get_usage(true);

    if ($used > $this->memoryLimit) {
        $output->writeln(sprintf(
            '[%s] memory reached %dMB, exit for supervisor restart',
            date('Y-m-d H:i:s'),
            (int) ($used / 1024 / 1024)
        ));
        $this->running = false;
        return;
    }

    // 每轮循环主动收一次循环引用,成本很低
    gc_collect_cycles();
}

关于 memory_get_usage 参数的选择:false 返回的是 PHP 层面脚本当前占用的字节数,true 返回的是内存分配器向操作系统申请的总量。前者容易因为一次释放骤降,后者更接近 top 里看到的数字。做阈值就用 true。

另外,ThinkPHP 8 的日志默认是请求结束时统一落盘的。常驻进程没有”请求结束”,日志会一直堆在内存里,直到某种条件触发才写出去。这个问题很典型,具体原因在踩坑那一节展开。

Redis 连接:默认会超时

自建 Redis 连接的时候有一行必须加,否则大概率会出现”消费一会儿就卡住”:

protected function connectRedis(): void
{
    $conf = config('cache.stores.redis');

    $this->redis = new Redis();
    $this->redis->connect(
        $conf['host'] ?? '127.0.0.1',
        (int) ($conf['port'] ?? 6379),
        2.5          // 连接超时,秒
    );

    if (!empty($conf['password'])) {
        $this->redis->auth($conf['password']);
    }
    if (!empty($conf['select'])) {
        $this->redis->select((int) $conf['select']);
    }

    // 关键:读超时设为 -1,阻塞时永不超时
    $this->redis->setOption(Redis::OPT_READ_TIMEOUT, -1);
}

phpredis 的默认读超时和连接超时是同一个值。如果用的是 brpop、blpop 这种阻塞读,连接超时 2.5 秒意味着一到时间就抛 RedisException: read error on connection。很多教程让你在 catch 里重连,但更好的做法是根本不让它超时,因为常驻消费者本来就应该长时间阻塞等消息。

不用 brpop 用普通 lpop + sleep 的组合则没有这个问题,只是空队列时会空转几十次。如果追求低延迟,用 brpop 加 OPT_READ_TIMEOUT = -1 是最省资源的方案。

重连也不能简单粗暴:

protected function reconnectRedis(): void
{
    try {
        $this->redis->close();
    } catch (Throwable $e) {
        // 连接已经断了,close 报错很正常,忽略
    }
    $this->connectRedis();
}

为什么不用 Cache::store('redis')->handler()?因为 think-cache 的 Redis 驱动是单例,内部连接挂了之后,再次拿到的还是同一个已断的对象。自己 new 一个 Redis 对象来管,重连的时候干净利落。

消费循环

把上面几块拼在一起,主循环大致是:

protected function dispatchOnce(Output $output): void
{
    try {
        $raw = $this->redis->lPop($this->queueName);
    } catch (Throwable $e) {
        Log::warning('[queue:daemon] lPop failed: ' . $e->getMessage());
        $this->reconnectRedis();
        usleep(500000);
        return;
    }

    if ($raw === false || $raw === null || $raw === '') {
        // 空队列,睡一会儿再拉
        sleep($this->sleepSeconds);
        return;
    }

    $task = json_decode($raw, true);
    if (!is_array($task) || empty($task['handler'])) {
        Log::error('[queue:daemon] malformed task: ' . $raw);
        return;
    }

    try {
        $handler = app()->make($task['handler']);
        $handler->handle($task['params'] ?? []);
        $output->writeln(sprintf('[%s] OK  %s', date('H:i:s'), $task['handler']));
    } catch (Throwable $e) {
        $this->handleFailed($task, $e);
    }
}

protected function handleFailed(array $task, Throwable $e): void
{
    Log::error(sprintf(
        '[queue:daemon] task failed: %s | %s',
        $task['handler'],
        $e->getMessage()
    ), [
        'trace' => $e->getTraceAsString(),
        'task'  => $task,
    ]);

    $attempts = (int) ($task['attempts'] ?? 0) + 1;
    $task['attempts'] = $attempts;

    try {
        if ($attempts < 3) {
            $this->redis->rPush($this->queueName, json_encode($task, JSON_UNESCAPED_UNICODE));
        } else {
            // 超过重试次数,落到死信队列
            $this->redis->rPush($this->queueName . ':dead', json_encode($task, JSON_UNESCAPED_UNICODE));
        }
    } catch (Throwable $pushErr) {
        Log::error('[queue:daemon] requeue failed: ' . $pushErr->getMessage());
        $this->reconnectRedis();
    }
}

几个细节值得说一下。

任务用 json_encode 存。 队列数据在 Redis 里是纯字符串,跨语言、跨版本都不会出问题。PHP 的 serialize 反序列化时依赖类定义,换了版本或改了类名就炸。

重试策略。 失败后 rPush 回原队列会立刻被下一轮重新取出——如果这条任务是因为数据问题失败,会瞬间重试三次然后进死信,几乎等于没重试。更合理的做法是 rPush 到 队列名:retry,由另一个慢速消费者按分钟级别重新投递。本文为了代码简单先直接放回原队列,知道这个局限就行。

app()->make() 而不是 new。 handler 的构造函数里可以声明依赖,比如构造函数里注入一个 Logger,容器自动解析。业务 handler 里也能直接调 $this->app。

MySQL 断线

Redis 会断,MySQL 一样的。默认 wait_timeout 是 8 小时,凌晨没有人操作,连接就被服务器单方面回收了。第二天早上第一条查询直接报 MySQL server has gone away。

不用在每个 handler 里写一堆 try/catch,在入口处做一次统一处理就行。最直接的方案是让 handler 里遇到 PDO 异常时自愈:

try {
    $order = Db::name('order')->where('id', $params['order_id'])->find();
    // 业务逻辑
} catch (thinkdbexceptionPDOException $e) {
    // 连接层面出错,关闭让 think-orm 下次查询重建连接
    Db::close();
    throw $e;   // 抛出去让外层的重试机制接
}

Db::close() 会把当前所有连接都关掉,下一次查询自动重连。这样单条任务会因为断线失败一次,但重试一次就成功了。

如果你的业务不能容忍”因断线而失败一次”,那就在循环顶部加一个心跳:

// 每 5 分钟 ping 一次数据库
private int $lastPing = 0;

protected function checkDbAlive(): void
{
    $now = time();
    if ($now - $this->lastPing < 300) {
        return;
    }
    $this->lastPing = $now;

    try {
        Db::query('SELECT 1');
    } catch (Throwable $e) {
        Log::warning('[queue:daemon] db ping failed, closing for reconnect');
        Db::close();
    }
}

在主循环里每轮调一下 checkDbAlive(),成本是一次最简单的查询,能避免大部分”睡了一夜起来断线”的情况。

日志为什么会撑爆内存

这是 ThinkPHP 8 常驻进程里经常被忽略的一个点。框架的日志写在请求结束时统一 flush,由 thinkLog 的事件监听触发。常驻进程没有请求结束事件,Log::info() 上百次之后内存里攒了一大堆日志对象。

解决方案有两种,任选其一:

在命令启动时,把日志配置里的 close 或 buffer_size 处理好:

// 强制每条日志立即落盘
$log = app('log');
$log->setConfig(['close' => true, 'type' => 'file']);

或者更直接,别让日志对象在内存里累积,每轮循环主动强制写一次:

protected function flushLog(): void
{
    // 触发 ThinkPHP 的日志保存逻辑
    app('log')->save();
}

在主循环的末尾调用 $this->flushLog()。这样每消费一条任务,日志就落到文件里一次,内存不会累积。

还有一个相关的问题是日志文件的体积。常驻进程的日志是按天滚动的,一天几十万行会撑出几百 MB 的单个文件,用 tail -f 都不好翻。可以在配置里同时限制单文件大小和保留份数:

// config/log.php
'file' => [
    'path'  => '',
    'single' => false,
    'apart_level' => ['error', 'sql'],
    'max_files' => 30,
    'file_size' => 10 * 1024 * 1024,   // 单文件 10MB 就切
],

file_size 这一项在 max_files 生效后会按大小切分,文件名里带序号,配合 logrotate 一起用体验最好。

完整命令

把前面的代码合到一起,整份命令类大致长这样:

<?php
declare(strict_types=1);

namespace appcommand;

use thinkconsoleCommand;
use thinkconsoleInput;
use thinkconsoleinputOption;
use thinkconsoleOutput;
use thinkfacadeDb;
use thinkfacadeLog;

class QueueDaemon extends Command
{
    protected Redis $redis;
    protected bool $running = true;
    protected int $memoryLimit = 134217728;
    protected string $queueName = 'default';
    protected int $sleepSeconds = 1;
    protected int $lastDbPing = 0;

    protected function configure()
    {
        $this->setName('queue:daemon')
            ->addOption('queue', null, Option::VALUE_OPTIONAL, '队列名', 'default')
            ->addOption('memory', null, Option::VALUE_OPTIONAL, '内存上限(MB)', 128)
            ->addOption('sleep', null, Option::VALUE_OPTIONAL, '空闲休眠秒数', 1)
            ->setDescription('常驻队列消费者');
    }

    protected function execute(Input $input, Output $output)
    {
        $this->queueName    = (string) $input->getOption('queue');
        $this->memoryLimit  = (int) $input->getOption('memory') * 1024 * 1024;
        $this->sleepSeconds = max(1, (int) $input->getOption('sleep'));

        $this->registerSignals();
        $this->connectRedis();

        $output->writeln(sprintf(
            '[%s] daemon started, queue=%s, pid=%d',
            date('Y-m-d H:i:s'),
            $this->queueName,
            getmypid()
        ));

        while ($this->running) {
            $this->checkDbAlive();
            $this->dispatchOnce($output);
            $this->flushLog();
            $this->checkMemory($output);
        }

        try {
            $this->redis->close();
        } catch (Throwable $e) {
            // ignore
        }

        $output->writeln(sprintf('[%s] daemon stopped', date('Y-m-d H:i:s')));
        return 0;
    }

    protected function registerSignals(): void
    {
        pcntl_async_signals(true);
        $stop = function (int $signo) {
            $this->running = false;
        };
        pcntl_signal(SIGTERM, $stop);
        pcntl_signal(SIGINT, $stop);
        pcntl_signal(SIGQUIT, $stop);
    }

    protected function connectRedis(): void
    {
        $conf = config('cache.stores.redis');
        $this->redis = new Redis();
        $this->redis->connect($conf['host'] ?? '127.0.0.1', (int) ($conf['port'] ?? 6379), 2.5);

        if (!empty($conf['password'])) {
            $this->redis->auth($conf['password']);
        }
        if (!empty($conf['select'])) {
            $this->redis->select((int) $conf['select']);
        }

        $this->redis->setOption(Redis::OPT_READ_TIMEOUT, -1);
    }

    protected function reconnectRedis(): void
    {
        try {
            $this->redis->close();
        } catch (Throwable $e) {
            // ignore
        }
        $this->connectRedis();
    }

    protected function dispatchOnce(Output $output): void
    {
        try {
            $raw = $this->redis->lPop($this->queueName);
        } catch (Throwable $e) {
            Log::warning('[queue:daemon] lPop failed: ' . $e->getMessage());
            $this->reconnectRedis();
            usleep(500000);
            return;
        }

        if ($raw === false || $raw === null || $raw === '') {
            sleep($this->sleepSeconds);
            return;
        }

        $task = json_decode($raw, true);
        if (!is_array($task) || empty($task['handler'])) {
            Log::error('[queue:daemon] malformed task: ' . $raw);
            return;
        }

        try {
            $handler = app()->make($task['handler']);
            $handler->handle($task['params'] ?? []);
            $output->writeln(sprintf('[%s] OK  %s', date('H:i:s'), $task['handler']));
        } catch (Throwable $e) {
            $this->handleFailed($task, $e);
        }
    }

    protected function handleFailed(array $task, Throwable $e): void
    {
        Log::error(sprintf(
            '[queue:daemon] task failed: %s | %s',
            $task['handler'],
            $e->getMessage()
        ), [
            'trace' => $e->getTraceAsString(),
            'task'  => $task,
        ]);

        $attempts = (int) ($task['attempts'] ?? 0) + 1;
        $task['attempts'] = $attempts;

        try {
            if ($attempts < 3) {
                $this->redis->rPush($this->queueName, json_encode($task, JSON_UNESCAPED_UNICODE));
            } else {
                $this->redis->rPush($this->queueName . ':dead', json_encode($task, JSON_UNESCAPED_UNICODE));
            }
        } catch (Throwable $pushErr) {
            Log::error('[queue:daemon] requeue failed: ' . $pushErr->getMessage());
            $this->reconnectRedis();
        }
    }

    protected function checkMemory(Output $output): void
    {
        $used = memory_get_usage(true);
        if ($used > $this->memoryLimit) {
            $output->writeln(sprintf(
                '[%s] memory reached %dMB, exit for supervisor restart',
                date('Y-m-d H:i:s'),
                (int) ($used / 1024 / 1024)
            ));
            $this->running = false;
            return;
        }
        gc_collect_cycles();
    }

    protected function checkDbAlive(): void
    {
        $now = time();
        if ($now - $this->lastDbPing < 300) {
            return;
        }
        $this->lastDbPing = $now;

        try {
            Db::query('SELECT 1');
        } catch (Throwable $e) {
            Log::warning('[queue:daemon] db ping failed, closing for reconnect');
            Db::close();
        }
    }

    protected function flushLog(): void
    {
        try {
            app('log')->save();
        } catch (Throwable $e) {
            // ignore
        }
    }
}

生产投递长什么样

生产端不负责消费,只要把 handler 类名和 params 塞进 Redis 的 list 就行。比如订单创建之后推送对账任务:

app(Redis::class)->rPush('default', json_encode([
    'handler' => appjobSyncOrder::class,
    'params'  => ['order_id' => $orderId],
]));

把 Redis 注册进容器,业务代码里就能直接注入,不用每次 new。handler 的写法:

<?php
declare(strict_types=1);

namespace appjob;

use thinkfacadeDb;

class SyncOrder
{
    public function handle(array $params): void
    {
        try {
            $order = Db::name('order')->where('id', $params['order_id'])->find();
            if (!$order) {
                return;
            }

            // 走对账逻辑
            Db::name('reconcile_log')->insert([
                'order_id'   => $order['id'],
                'amount'     => $order['amount'],
                'created_at' => date('Y-m-d H:i:s'),
            ]);
        } catch (thinkdbexceptionPDOException $e) {
            Db::close();
            throw $e;
        }
    }
}

用 supervisor 守护

常驻进程必须有人看着,进程挂了要能自动重启。生产上用 supervisor:

[program:queue-daemon]
command=php /var/www/html/think queue:daemon --queue=default --memory=128
directory=/var/www/html
user=www-data
autostart=true
autorestart=true
numprocs=2
process_name=%(program_name)s_%(process_num)02d
redirect_stderr=true
stdout_logfile=/var/log/queue-daemon.log
stdout_logfile_maxbytes=50MB
stdout_logfile_backups=5
stopsignal=TERM
stopwaitsecs=30
stopasgroup=true
killasgroup=true

逐项解释几个非默认值。

autorestart=true 是内存超限退出的配套。我们主动 exit,supervisor 自动拉起一个新的,内存清零。这就是前面说的”用重启代替修复泄漏”。

numprocs=2 至少开两个进程。一个在跑任务时,另一个还能继续消费,避免单进程串行导致的吞吐下降。

stopsignal=TERM 配合代码里的 SIGTERM 处理,进程会先把当前任务跑完再退出。supervisor 默认会等 10 秒,超过就 SIGKILL。改成 30 秒给大任务留足够时间。

stopasgroup / killasgroup 很重要。这两个不开,supervisor stop 时只把信号发给主进程,进程 fork 出来的子进程(比如你调用了 pcntl_fork 并行处理)会变成孤儿进程继续跑,下一次重启时又起来一批,进程越积越多。开了之后整个进程组一起收信号。

上线之前自检清单

日志配置。 用的是 file 还是 sql?后者在队列高吞吐下会把数据库写爆。如果是临时排障,记得改回来。

supervisor 用户权限。 user=www-data 跟 nginx / php-fpm 用同一个用户,生成的文件权限一致。用 root 跑常见于事故现场。

Redis 密码。 别把密码写死在代码里。从 config/cache.php 读,或者直接用环境变量。

死信队列的清理。 队列名:dead 会一直堆着,需要定时任务扫描,把内容打到告警群里。不然哪天凌晨突然死信爆了没人知道。

监控上报。 给消费速度、失败率、进程存活状态各配一个监控项。进程两天没动静,监控才会告诉你。

最后

常驻消费者本身不复杂,难的是运行一两个月不出事。信号、内存、连接这三件事,各自写个几十行就能兜住,但如果一开始不处理,后面就是无穷无尽的线上问题。

如果项目量级不大,直接用 think-queue 的 queue:work 就行,没必要重复实现。真正需要自建的场景,照着本文把信号、Redis 超时、Db::close、日志 flush 这四处对着改一遍,能省掉至少两次半夜被叫起来排查的失眠。

ThinkPHP8 自建常驻队列消费者:信号处理、内存防泄漏与连接重连
收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

版权声明:
本站资源有的来自互联网收集整理,本站纯免费分享提供学习使用,如果侵犯了您的合法权益,请发送邮件1506151422@qq.com联系,将会及时下架删除。
本站资源仅供研究、学习交流之用,免费开源项目不代表完全可商用,若商业用途请先咨询开发企业能否商用,否则产生的一切后果将由下载用户自行承担。
原创板块未经允许不得转载,否则将追究法律责任。

淘吗网 thinkphp ThinkPHP8 自建常驻队列消费者:信号处理、内存防泄漏与连接重连 https://www.taomawang.com/server/thinkphp/3037.html

常见问题

相关文章

猜你喜欢
发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务