总结
豆包 AI 助手文章总结
首页 > php框架 > Workerman > 正文

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

青灯夜游
发布: 2022-12-08 20:30:21
转载
3386人浏览过

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

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

thinkphp6整合workerman教程

thinkphp6安装workerman命令:

composer require topthink/think-worker
登录后复制

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

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

php think make:command Spider spider
登录后复制

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

<?php
namespace appcommand;
 
// tp指令特性使用的功能
use thinkconsoleCommand;
use thinkconsoleInput;
use thinkconsoleinputArgument;
use thinkconsoleOutput;
 
// 引用项目的基类,该类继承自worker
use appservercontrollerStart;
 
/**
 * 指令类
 * 在此定义指令
 * 再次启动多个控制器
 * @var mixed
 */
class Spider extends Command
{
 
    /**
     * 注册模块名称
     * 使用命令会启动该模块控制器
     * @var mixed
     */
    public $model_name = 'server';
 
    /**
     * 注册控制器名称
     * 使用命令启动相关控制器
     * @var mixed
     */
    public $controller_names = ['WebhookTimer'];
 
    /**
     * configure
     * tp框架自定义指令特性
     * 注册命令参数
     * @return mixed
     */
    protected function configure()
    {
        $this->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();
    }
}
登录后复制

例如我们创建一个定时器的命令appservercontroller创建WebhookTimer.php

<?php
namespace appservercontroller;
use WorkermanWorker; 
use WorkermanLibTimer;
use thinkacadeCache;
use thinkacadeDb;
use thinkRequest;
 
class WebhookTimer extends Start
{
    public $host     = '0.0.0.0';
    public $port     = '9527';
    public $name     = 'webhook';
    public $count    = 1;
    public function onWorkerStart($worker)
    {
      
        
            Timer::add(2, array($this, 'webhooks'), array(), true);
        
     
    }
    public function onConnect()
    {
 
    }
 
    public function onMessage($ws_connection, $message)
    {
       
    }
 
    public function onClose()
    {
 
    }
    
    public function webhooks()
    {
 
       echo 11;
    }
    
    
}
登录后复制

执行start命令行

php think spider start
登录后复制

执行stop命令

php think spider stop
登录后复制

执行全部进程命令

php think spider start all d
登录后复制

在appcommandSpider.php文件

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

其他方法 就是appservercontroller下创建的其他类文件方法

完结

Start.php文件

<?php
namespace appservercontroller;
 
use WorkermanWorker;
 
class Start extends Worker
{
    public static $argvs = [];
    public static $workerHost;
    public $socket   = '';
    public $protocol = 'http';
    public $host     = '0.0.0.0';
    public $port     = '2346';
    public $context  = [];
 
    public function __construct()
    {
        self::$workerHost = parent::__construct($this->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 <command> [mode]
Commands: 
start		Start worker in DEBUG mode.
		Use mode -d to start in DAEMON mode.
stop		Stop worker.
		Use mode -g to stop gracefully.
restart		Restart workers.
		Use mode -d to start in DAEMON mode.
		Use mode -g to stop gracefully.
reload		Reload codes.
		Use mode -g to reload gracefully.
status		Get worker status.
		Use mode -d to show live status.
connections	Get worker connections.
";
        if (!isset(static::$argvs[1]) || !in_array(static::$argvs[1], $available_commands)) {
            if (isset(static::$argvs[1])) {
                static::safeEcho('Unknown command: ' . static::$argvs[1] . "
");
            }
            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("(B", true);
                    }
                    // Echo status data.
                    static::safeEcho(static::formatStatusData());
                    if ($command2 !== '-d') {
                        exit(0);
                    }
                    static::safeEcho("
Press Ctrl+C to quit.

");
                }
                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 . "
");
                }
                exit($usage);
        }
    }
 
}
登录后复制

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

以上就是浅析thinkphp6中怎么使用workerman【教程分享】的详细内容,更多请关注php中文网其它相关文章!

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

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

下载
相关标签:
来源:csdn网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
豆包 AI 助手文章总结
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

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