Jerry's WIKIJerry's WIKI
概述
  • 🐞 web使用
  • 📐 常用组件
  • 💡 使用技巧
  • 🎱 规范相关
  • 🖥 工作流
  • 🛠 常用工具
  • 🌐️ 服务器
  • 📦 容器相关
  • ♨️ 编程语言
咖啡屋
  • 简体中文
  • English
GitHub
概述
  • 🐞 web使用
  • 📐 常用组件
  • 💡 使用技巧
  • 🎱 规范相关
  • 🖥 工作流
  • 🛠 常用工具
  • 🌐️ 服务器
  • 📦 容器相关
  • ♨️ 编程语言
咖啡屋
  • 简体中文
  • English
GitHub
  • 📞 事件机制

    • 事件角色和注意事项
    • 代码示例
  • ⏰ 定时任务
  • ⛓ 自定义进程
  • 📝 文件系统
  • 🕓 缓存系统
  • 📩 异步队列

    • 队列使用
    • 注意事项
  • 🚦 信号处理器
  • 📤 GuzzleHttp
  • 📉 限流器
  • ❌ 异常处理器
  • 🖨 日志
  • 📡 命令行
  • 🔁 WebSocket

信号处理器

目录

  • 安装依赖
  • 发布配置
  • 注册信号处理器
    • 自定义进程信号处理器
    • 自定义work进程信号处理器

安装依赖

标准库地址

composer require hyperf/signal

发布配置

config/autoload/signal.php

<?php

declare(strict_types=1);
return [
    'handlers' => [
        // 这里我们自己实现, 所以注释
        // Hyperf\Signal\Handler\WorkerStopHandler::class => PHP_INT_MIN,
    ],
    // 收到信号后等待时间
    'timeout' => 5.0,
];

注册信号处理器

自定义进程信号处理器

<?php

declare(strict_types=1);
namespace App\Signal;

use Hyperf\Process\ProcessManager;
use Hyperf\Signal\Annotation\Signal;
use Hyperf\Signal\SignalHandlerInterface;

#[Signal]
class ProcessStopHandler implements SignalHandlerInterface
{
    public function listen(): array
    {
        return [
            [self::PROCESS, SIGTERM],
        ];
    }

    public function handle(int $signal): void
    {
        ProcessManager::setRunning(false);
    }
}

自定义work进程信号处理器

<?php

declare(strict_types=1);
namespace App\Signal;

use Hyperf\Contract\ConfigInterface;
use Hyperf\Coroutine\Coroutine;
use Hyperf\Signal\Annotation\Signal;
use Hyperf\Signal\SignalHandlerInterface;
use Psr\Container\ContainerInterface;
use Swoole\Server;

#[Signal]
class WorkerStopHandler implements SignalHandlerInterface
{
    protected ConfigInterface $config;

    public function __construct(protected ContainerInterface $container)
    {
        $this->config = $container->get(ConfigInterface::class);
    }

    public function listen(): array
    {
        return [
            [self::WORKER, SIGTERM],
            [self::WORKER, SIGINT],
        ];
    }

    public function handle(int $signal): void
    {
        if ($signal !== SIGINT) {
            $time = $this->config->get('server.settings.max_wait_time', 3);
            Coroutine::sleep($time);
        }

        // shutdown => https://wiki.swoole.com/#/server/methods?id=shutdown 直接kill -15 不触发后续动作
        // stop => https://wiki.swoole.com/#/server/methods?id=stop 使当前 Worker 进程停止运行,并立即触发 onWorkerStop 回调函数。

        //  $this->container->get(Server::class)->shutdown();
        $this->container->get(Server::class)->stop(-1, false);
    }
}

编辑此页面
更新时间:
贡献者: 田朝帆
Prev
队列注意事项
Next
GuzzleHttp