0

0

浅析thinkphp6中怎么使用workerman【教程分享】

青灯夜游

青灯夜游

发布时间:2022-12-08 20:30:21

|

3546人浏览过

|

来源于csdn

转载

thinkphp6中怎么使用workerman?下面本篇文章给大家介绍一下thinkphp6整合workerman的教程,希望对大家有所帮助。

浅析thinkphp6中怎么使用workerman【教程分享】

thinkphp6整合workerman教程

thinkphp6安装workerman命令:

composer require topthink/think-worker

第一步,创建一个自定义命令类文件,运行指令。【相关推荐:《workerman教程》】

立即学习PHP免费学习笔记(深入)”;

php think make:command Spider spider

会生成一个app\command\Spider命令行指令类,我们修改内容如下:

setName('spider')
            ->addArgument('status', Argument::OPTIONAL, "status")
            ->addArgument('controller_name', Argument::OPTIONAL, "controller_name/controller_name")
            ->addArgument('mode', Argument::OPTIONAL, "d")
            ->setDescription('spider control');
 
        /**
         * 以上设置命令格式为:php think spider [status] [controller_name/controller_name] [d]
         * think        为thinkphp框架入口文件
         * spider       为在框架中注册的命令,上面setName设置的
         * staus        为workerman框架接受的命令
         * controller_name/controller_name      为控制器名称,以正斜线分割,执行制定控制器,为空或缺省则启动所有控制器,控制器列表在controller_name属性中注册
         * d            最后一个参数为wokerman支持的-d-g参数,但是不用加-,直接使用d或者g
         * php think spider start collect/SendMsg
         */
    }
 
 
    /**
     * execute
     * tp框架自定义指令特性
     * 执行命令后的逻辑
     * @param mixed $input
     * @param mixed $output
     * @return mixed
     */
    protected function execute(Input $input, Output $output)
    {
 
        //获得status参数,即think自定义指令中的第一个参数,缺省报错
        $status  = $input->getArgument('status');
        if(!$status){
            $output->writeln('pelase input control command , like start');
            exit;
        }
 
 
        //获得控制器名称
        $controller_str =  $input->getArgument('controller_name');
 
        //获得模式,d为wokerman的后台模式(生产环境)
        $mode = $input->getArgument('mode');
 
        //分析控制器参数,如果缺省或为all,那么运行所有注册的控制器
        $controller_list = $this->controller_names;
 
        if($controller_str != '' && $controller_str != 'all' )
        {
            $controller_list = explode('/',$controller_str);
        }
 
        //重写mode参数,改为wokerman接受的参数
        if($mode == 'd'){
            $mode = '-d';
        }
 
        if($mode == 'g'){
            $mode = '-g';
        }
 
        //将wokerman需要的参数传入到其parseCommand方法中,此方法在start类中重写
        Start::$argvs = [
            'think',
            $status,
            $mode
        ];
 
        $output->writeln('start running spider');
 
        $programs_ob_list = [];
 
 
        //实例化需要运行的控制器
        foreach ($controller_list as $c_key => $controller_name) {
            $class_name = 'app\\'.$this->model_name.'\controller\\'.$controller_name;
            $programs_ob_list[] = new $class_name();
        }
 
 
 
        //将控制器的相关回调参数传到workerman中
        foreach (['onWorkerStart', 'onConnect', 'onMessage', 'onClose', 'onError', 'onBufferFull', 'onBufferDrain', 'onWorkerStop', 'onWorkerReload'] as $event) {
            foreach ($programs_ob_list as $p_key => $program_ob) {
                if (method_exists($program_ob, $event)) {
                    $programs_ob_list[$p_key]->$event = [$program_ob,$event];
                }
            }
        }
 
        Start::runAll();
    }
}

例如我们创建一个定时器的命令app\server\controller创建WebhookTimer.php

执行start命令行

php think spider start

执行stop命令

酷兔AI论文
酷兔AI论文

专业原创高质量、低查重,免费论文大纲,在线AI生成原创论文,AI辅助生成论文的神器!

下载
php think spider stop

执行全部进程命令

php think spider start all d

app\command\Spider.php文件

public $controller_names = ['WebhookTimer','其他方法','其他方法'];

其他方法 就是app\server\controller下创建的其他类文件方法

完结

Start.php文件

socket ?: $this->protocol . '://' . $this->host . ':' . $this->port, $this->context);
    }
 
    /**
     * parseCommand
     * 重写wokerman的解析命令方法
     * @return mixed
     */
    public static function parseCommand()
    {
        if (static::$_OS !== OS_TYPE_LINUX) {
            return;
        }
        // static::$argvs;
        // Check static::$argvs;
        $start_file = static::$argvs[0];
        $available_commands = array(
            'start',
            'stop',
            'restart',
            'reload',
            'status',
            'connections',
        );
        $usage = "Usage: php yourfile  [mode]\nCommands: \nstart\t\tStart worker in DEBUG mode.\n\t\tUse mode -d to start in DAEMON mode.\nstop\t\tStop worker.\n\t\tUse mode -g to stop gracefully.\nrestart\t\tRestart workers.\n\t\tUse mode -d to start in DAEMON mode.\n\t\tUse mode -g to stop gracefully.\nreload\t\tReload codes.\n\t\tUse mode -g to reload gracefully.\nstatus\t\tGet worker status.\n\t\tUse mode -d to show live status.\nconnections\tGet worker connections.\n";
        if (!isset(static::$argvs[1]) || !in_array(static::$argvs[1], $available_commands)) {
            if (isset(static::$argvs[1])) {
                static::safeEcho('Unknown command: ' . static::$argvs[1] . "\n");
            }
            exit($usage);
        }
 
        // Get command.
        $command  = trim(static::$argvs[1]);
        $command2 = isset(static::$argvs[2]) ? static::$argvs[2] : '';
 
        // Start command.
        $mode = '';
        if ($command === 'start') {
            if ($command2 === '-d' || static::$daemonize) {
                $mode = 'in DAEMON mode';
            } else {
                $mode = 'in DEBUG mode';
            }
        }
        static::log("Workerman[$start_file] $command $mode");
 
        // Get master process PID.
        $master_pid      = is_file(static::$pidFile) ? file_get_contents(static::$pidFile) : 0;
        $master_is_alive = $master_pid && posix_kill($master_pid, 0) && posix_getpid() != $master_pid;
        // Master is still alive?
        if ($master_is_alive) {
            if ($command === 'start') {
                static::log("Workerman[$start_file] already running");
                exit;
            }
        } elseif ($command !== 'start' && $command !== 'restart') {
            static::log("Workerman[$start_file] not run");
            exit;
        }
 
        // execute command.
        switch ($command) {
            case 'start':
                if ($command2 === '-d') {
                    static::$daemonize = true;
                }
                break;
            case 'status':
                while (1) {
                    if (is_file(static::$_statisticsFile)) {
                        @unlink(static::$_statisticsFile);
                    }
                    // Master process will send SIGUSR2 signal to all child processes.
                    posix_kill($master_pid, SIGUSR2);
                    // Sleep 1 second.
                    sleep(1);
                    // Clear terminal.
                    if ($command2 === '-d') {
                        static::safeEcho("\33[H\33[2J\33(B\33[m", true);
                    }
                    // Echo status data.
                    static::safeEcho(static::formatStatusData());
                    if ($command2 !== '-d') {
                        exit(0);
                    }
                    static::safeEcho("\nPress Ctrl+C to quit.\n\n");
                }
                exit(0);
            case 'connections':
                if (is_file(static::$_statisticsFile) && is_writable(static::$_statisticsFile)) {
                    unlink(static::$_statisticsFile);
                }
                // Master process will send SIGIO signal to all child processes.
                posix_kill($master_pid, SIGIO);
                // Waiting amoment.
                usleep(500000);
                // Display statisitcs data from a disk file.
                if(is_readable(static::$_statisticsFile)) {
                    readfile(static::$_statisticsFile);
                }
                exit(0);
            case 'restart':
            case 'stop':
                if ($command2 === '-g') {
                    static::$_gracefulStop = true;
                    $sig = SIGTERM;
                    static::log("Workerman[$start_file] is gracefully stopping ...");
                } else {
                    static::$_gracefulStop = false;
                    $sig = SIGINT;
                    static::log("Workerman[$start_file] is stopping ...");
                }
                // Send stop signal to master process.
                $master_pid && posix_kill($master_pid, $sig);
                // Timeout.
                $timeout    = 5;
                $start_time = time();
                // Check master process is still alive?
                while (1) {
                    $master_is_alive = $master_pid && posix_kill($master_pid, 0);
                    if ($master_is_alive) {
                        // Timeout?
                        if (!static::$_gracefulStop && time() - $start_time >= $timeout) {
                            static::log("Workerman[$start_file] stop fail");
                            exit;
                        }
                        // Waiting amoment.
                        usleep(10000);
                        continue;
                    }
                    // Stop success.
                    static::log("Workerman[$start_file] stop success");
                    if ($command === 'stop') {
                        exit(0);
                    }
                    if ($command2 === '-d') {
                        static::$daemonize = true;
                    }
                    break;
                }
                break;
            case 'reload':
                if($command2 === '-g'){
                    $sig = SIGQUIT;
                }else{
                    $sig = SIGUSR1;
                }
                posix_kill($master_pid, $sig);
                exit;
            default :
                if (isset($command)) {
                    static::safeEcho('Unknown command: ' . $command . "\n");
                }
                exit($usage);
        }
    }
 
}

更多编程相关知识,请访问:编程教学!!

相关文章

PHP速学教程(入门到精通)
PHP速学教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载

相关标签:

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

相关专题

更多
Java编译相关教程合集
Java编译相关教程合集

本专题整合了Java编译相关教程,阅读专题下面的文章了解更多详细内容。

5

2026.01.21

C++多线程相关合集
C++多线程相关合集

本专题整合了C++多线程相关教程,阅读专题下面的的文章了解更多详细内容。

0

2026.01.21

无人机驾驶证报考 uom民用无人机综合管理平台官网
无人机驾驶证报考 uom民用无人机综合管理平台官网

无人机驾驶证(CAAC执照)报考需年满16周岁,初中以上学历,身体健康(矫正视力1.0以上,无严重疾病),且无犯罪记录。个人需通过民航局授权的训练机构报名,经理论(法规、原理)、模拟飞行、实操(GPS/姿态模式)及地面站训练后考试合格,通常15-25天拿证。

7

2026.01.21

Python多线程合集
Python多线程合集

本专题整合了Python多线程相关教程,阅读专题下面的文章了解更多详细内容。

1

2026.01.21

java多线程相关教程合集
java多线程相关教程合集

本专题整合了java多线程相关教程,阅读专题下面的文章了解更多详细内容。

2

2026.01.21

windows激活码分享 windows一键激活教程指南
windows激活码分享 windows一键激活教程指南

Windows 10/11一键激活可以通过PowerShell脚本或KMS工具实现永久或长期激活。最推荐的简便方法是打开PowerShell(管理员),运行 irm https://get.activated.win | iex 脚本,按提示选择数字激活(选项1)。其他方法包括使用HEU KMS Activator工具进行智能激活。

2

2026.01.21

excel表格操作技巧大全 表格制作excel教程
excel表格操作技巧大全 表格制作excel教程

Excel表格操作的核心技巧在于 熟练使用快捷键、数据处理函数及视图工具,如Ctrl+C/V(复制粘贴)、Alt+=(自动求和)、条件格式、数据验证及数据透视表。掌握这些可大幅提升数据分析与办公效率,实现快速录入、查找、筛选和汇总。

6

2026.01.21

毒蘑菇显卡测试网站入口 毒蘑菇测试官网volumeshader_bm
毒蘑菇显卡测试网站入口 毒蘑菇测试官网volumeshader_bm

毒蘑菇VOLUMESHADER_BM测试网站网址为https://toolwa.com/vsbm/,该平台基于WebGL技术通过渲染高复杂度三维分形图形评估设备图形处理能力,用户可通过拖动彩色物体观察画面流畅度判断GPU与CPU协同性能;测试兼容多种设备,但中低端手机易卡顿或崩溃,高端机型可能因发热降频影响表现,桌面端需启用独立显卡并使用支持WebGL的主流浏览器以确保准确结果

9

2026.01.21

github中文官网入口 github中文版官网网页进入
github中文官网入口 github中文版官网网页进入

github中文官网入口https://docs.github.com/zh/get-started,GitHub 是一种基于云的平台,可在其中存储、共享并与他人一起编写代码。 通过将代码存储在GitHub 上的“存储库”中,你可以: “展示或共享”你的工作。 持续“跟踪和管理”对代码的更改。

7

2026.01.21

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
ThinkPHP6.x 微实战--十天技能课堂
ThinkPHP6.x 微实战--十天技能课堂

共26课时 | 1.7万人学习

ThinkPHP6.x API接口--十天技能课堂
ThinkPHP6.x API接口--十天技能课堂

共14课时 | 1.1万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号