lanlin/codeigniter-swoole

Codeigniter 3.0+ 的 swoole 适配器

2.0.4 2019-07-26 09:01 UTC

This package is auto-updated.

Last update: 2024-09-21 08:24:29 UTC


README

你需要长期任务?计时器?FPM 到 CLI?在 FPM 和 CLI 模式下复用代码?

"这太简单了!"

这个适配器可以让您在 Codeigniter 框架中轻松使用 swoole。

使用此适配器,您可以从代码中的任何位置(FPM)启动任务(CLI)。

这意味着您可以从 FPM 进程启动 CLI 任务。

安装

composer require lanlin/codeigniter-swoole

如何使用

  1. 首先,当然您必须将 codeigniter-swoole 安装到您的 Codeigniter 项目中。
  2. (此步骤为可选)从 src/Helper 复制这两个配置文件 swoole.phptimers.php 到您的 application/config 文件夹。
  3. 启动 swoole 服务器 php index.php swoole/server/start
  4. 现在您可以使用 \CiSwoole\Core\Client::send($data) 启动任务!
  5. 没有第五步。

什么是任务?

任务只是您的 Codeigniter 控制器的一种方法,因此几乎任何控制器方法都可以用作任务。

让我们看看代码

\CiSwoole\Core\Client::send(
[
    'route'  => 'your/route/uri/to/a/method'
    'params' => ['test' => 666]
]);

route 用于查找要调用的方法作为任务,而 params 是您可能想要传递给任务的参数数组。

所以,这就全部了!

服务器 CLI 命令

// start the swoole server
php index.php swoole/server/start

// stop the swoole server
php index.php swoole/server/stop

// reload all wokers of swoole server
php index.php swoole/server/reload

更多内容

第二步中复制的文件是该适配器的配置文件。

swoole.php 文件可以设置主机、端口、日志文件等。

timers.php 文件可以设置一些计时器方法供 swoole 服务器使用,这些计时器将在服务器初始化时启动。

您可以将 tests/application 复制到您的 application 文件夹以进行测试。示例与以下相同。

class Test extends CI_Controller
{

    // ------------------------------------------------------------------------------

    /**
     * here's the task 'tests/test/task'
     */
    public function task()
    {
        $data = $this->input->post();     // as you see, params worked like normally post data

        log_message('info', var_export($data, true));
    }

    // ------------------------------------------------------------------------------

    /**
     * here's the timer method
     *
     * you should copay timers.php to your config folder,
     * then add $timers['tests/test/task_timer'] = 10000; and start the swoole server.
     *
     * this method would be called every 10 seconds per time.
     */
    public function task_timer()
    {
        log_message('info', 'timer works!');
    }

    // ------------------------------------------------------------------------------

    /**
     * send data to task
     */
    public function send()
    {
        try
        {
            \CiSwoole\Core\Client::send(
            [
                'route'  => 'tests/test/task',
                'params' => ['hope' => 'it works!'],
            ]);
        }
        catch (\Exception $e)
        {
            log_message('error', $e->getMessage());
            log_message('error', $e->getTraceAsString());
        }
    }

    // ------------------------------------------------------------------------------

}

许可证

该项目受 MIT 许可证的许可。

补充说明

codeigniter-swoole 的主要应用场景