websightnl/gearman

用于分配、处理和管理 Gearman 工人的 PHP 库

v1.1.3 2021-06-16 18:59 UTC

This package is auto-updated.

Last update: 2024-09-17 02:13:44 UTC


README

Build Status Latest Stable Version Total Downloads License

用于分配、处理和管理 Gearman 工人的 PHP 库

待办事项:添加对任务的支持,目前只处理作业。
待办事项:测试正在运行,但可以覆盖更多内容。

目录

  1. 需求
  2. 安装
  3. 配置
  4. 引导
  5. 作业示例
  6. 分发器使用
  7. 启动工人守护进程
  8. 与 Supervisor 一起使用

需求

此库使用 PHP 5.4+,PECL GearmanGearman 1.0+

安装

建议通过 composer 安装 Gearman 库。为此,将以下行添加到您的 composer.json 文件中。

{
    "require": {
       "websightnl/gearman": "~1.0"
    }
}

配置

库使用 Config 类在类之间共享配置。

示例

use Sinergi\Gearman\Config;

$config = (new Config())
    ->addServer('127.0.0.1', 4730)
    ->setUser('apache');

使用数组示例

或者,您可以使用数组设置配置。

use Sinergi\Gearman\Config;

$config = new Config([
    'servers' => ['127.0.0.1:4730', '127.0.0.1:4731'],
    'user' => 'apache'
]);

参数

  • string server
    Gearman 服务器(例如:127.0.0.1:4730)。

  • array servers
    Gearman 服务器池。

  • string bootstrap
    引导文件的路径。

  • string class
    引导类的完全限定名,该类需要实现 Sinergi\Gearman\BootstrapInterface 接口。

  • array env_variables
    您想要发送到引导程序的环境变量。

  • string user
    Gearman 工人运行的账户(例如:apache)。

  • bool auto_update
    仅用于 开发,在执行作业或任务之前自动更新工人。

  • string pidFilename
    更改创建的 PID 文件名(默认为 gearmanhandler.pid)。文件始终在系统临时路径中创建。

  • string lockFilename
    更改创建的锁文件名(默认为 gearmanhandler.lock)。文件始终在系统临时路径中创建。

  • int loopTimeout
    更改ping Gearman 服务器之间的时间(以毫秒为单位)。默认为10毫秒的低值,出于历史原因。 如果您的 Gearman 服务器负载较高,请更改此值!

引导

文件 /path/to/your/bootstrap.php

use Sinergi\Gearman\BootstrapInterface;
use Sinergi\Gearman\Application;

class MyBootstrap implements BootstrapInterface
{
    public function run(Application $application)
    {
        $application->add(new JobExample());
    }
}

作业示例

use Sinergi\Gearman\JobInterface;
use GearmanJob;

class JobExample implements JobInterface
{
    public function getName()
    {
        return 'JobExample';
    }

    public function execute(GearmanJob $job)
    {
        // Do something
    }
}

分发器使用

要将任务和作业发送到工人,请使用分发器如下

use Sinergi\Gearman\Dispatcher;

$dispatcher = new Dispatcher($config);
$dispatcher->execute('JobExample', ['data' => 'value']);

启动工人守护进程

以守护进程方式启动工人。您可以使用类似 supervisor 的工具确保工人始终运行。您可以使用与 配置 中相同的参数。

单服务器

php vendor/bin/gearman start --bootstrap="/path/to/your/bootstrap.php" --class="MyBootstrap" --server="127.0.0.1:4730"

多服务器

php vendor/bin/gearman start --bootstrap="/path/to/your/bootstrap.php" --class="MyBootstrap" --servers="127.0.0.1:4730,127.0.0.1:4731"

命令列表

  • start
  • stop
  • restart

与 Supervisor 一起使用

这是 Supervisor 配置的示例。将其添加到您的 Supervisor 配置文件中(例如:/etc/supervisord.conf)。

[program:mygearman]
command=php /path/to/vendor/bin/gearman start --daemon=false
process_name=%(program_name)s-procnum-%(process_num)s
numprocs=12
autostart=true
autorestart=true