TP5.1与swoole合并——php think swoole -d

TP5.1与swoole合并——php think swoole -d

第一步:下载tp swoole插件

composer require topthink/think-swoole=2.0.*


第二步:修改 config/swoole.php

// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2018 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------

use think\facade\Env;

// +----------------------------------------------------------------------
// | Swoole设置 php think swoole命令行下有效
// +----------------------------------------------------------------------
return [
    // 扩展自身配置
    'host'                  => 'swool.com', // 监听地址
    'port'                  => 80, // 监听端口
    'mode'                  => '', // 运行模式 默认为SWOOLE_PROCESS
    'sock_type'             => '', // sock type 默认为SWOOLE_SOCK_TCP
    'server_type'           => 'http', // 服务类型 支持 http websocket
    'app_path'              => __DIR__ . DIRECTORY_SEPARATOR . '../application', // 应用地址 如果开启了 'daemonize'=>true 必须设置(使用绝对路径)
    'file_monitor'          => false, // 是否开启PHP文件更改监控(调试模式下自动开启)
    'file_monitor_interval' => 2, // 文件变化监控检测时间间隔(秒)
    'file_monitor_path'     => [], // 文件监控目录 默认监控application和config目录

    // 可以支持swoole的所有配置参数
    'pid_file'              => Env::get('runtime_path') . 'swoole.pid',
    'log_file'              => Env::get('runtime_path') . 'swoole.log',
    'document_root'         => Env::get('root_path') . 'public',
    'enable_static_handler' => true,
    'timer'                 => true,//是否开启系统定时器
    'interval'              => 500,//系统定时器 时间间隔
    'task_worker_num'       => 20,//swoole 任务工作进程数量
];

image.png第三步:服务器执行 

php think swoole -d

第四步:写一段与 swoole 相关的代码

namespace app\index\controller;

use Swoole\Event;
use Swoole\Runtime;
use think\Controller;
use think\facade\App;

class Index extends Controller
{

    public function index()
    {
        Runtime::enableCoroutine();
        go(function () {
            sleep(2);
            file_put_contents(App::getRootPath() . '/1.txt', '123');
        });
        go(function () {
            sleep(1);
            file_put_contents(App::getRootPath() . '/1.txt', '46');
        });

        $this->assign('path', App::getRootPath() . '/1.txt');
//        Event::wait();
        return $this->view->fetch();
    }
}

第五步:访问URL查看结果

最后编辑于:2021/12/06作者: 牛逼PHP

发表评论