浅析thinkphp6中怎么使用workerman

 4530

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


浅析thinkphp6中怎么使用workerman


thinkphp6整合workerman教程

thinkphp6安装workerman命令:

  1. composer require topthink/think-worker

第一步,创建一个自定义命令类文件,运行指令。

  1. php think make:command Spider spider

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

  1. <?php
  2. namespace app\command;
  3.   
  4. // tp指令特性使用的功能
  5. use think\console\Command;
  6. use think\console\Input;
  7. use think\console\input\Argument;
  8. use think\console\Output;
  9.   
  10. // 引用项目的基类,该类继承自worker
  11. use app\server\controller\Start;
  12.   
  13. /**
  14.  * 指令类
  15.  * 在此定义指令
  16.  * 再次启动多个控制器
  17.  * @var mixed
  18.  */
  19. class Spider extends Command
  20. {
  21.   
  22.     /**
  23.      * 注册模块名称
  24.      * 使用命令会启动该模块控制器
  25.      * @var mixed
  26.      */
  27.     public $model_name = 'server';
  28.   
  29.     /**
  30.      * 注册控制器名称
  31.      * 使用命令启动相关控制器
  32.      * @var mixed
  33.      */
  34.     public $controller_names = ['WebhookTimer'];
  35.   
  36.     /**
  37.      * configure
  38.      * tp框架自定义指令特性
  39.      * 注册命令参数
  40.      * @return mixed
  41.      */
  42.     protected function configure()
  43.     {
  44.         $this->setName('spider')
  45.             ->addArgument('status', Argument::OPTIONAL, "status")
  46.             ->addArgument('controller_name', Argument::OPTIONAL, "controller_name/controller_name")
  47.             ->addArgument('mode', Argument::OPTIONAL, "d")
  48.             ->setDescription('spider control');
  49.   
  50.         /**
  51.          * 以上设置命令格式为:php think spider [status] [controller_name/controller_name] [d]
  52.          * think        为thinkphp框架入口文件
  53.          * spider       为在框架中注册的命令,上面setName设置的
  54.          * staus        为workerman框架接受的命令
  55.          * controller_name/controller_name      为控制器名称,以正斜线分割,执行制定控制器,为空或缺省则启动所有控制器,控制器列表在controller_name属性中注册
  56.          * d            最后一个参数为wokerman支持的-d-g参数,但是不用加-,直接使用d或者g
  57.          * php think spider start collect/SendMsg
  58.          */
  59.     }
  60.   
  61.   
  62.     /**
  63.      * execute
  64.      * tp框架自定义指令特性
  65.      * 执行命令后的逻辑
  66.      * @param mixed $input
  67.      * @param mixed $output
  68.      * @return mixed
  69.      */
  70.     protected function execute(Input $input, Output $output)
  71.     {
  72.   
  73.         //获得status参数,即think自定义指令中的第一个参数,缺省报错
  74.         $status  = $input->getArgument('status');
  75.         if(!$status){
  76.             $output->writeln('pelase input control command , like start');
  77.             exit;
  78.         }
  79.   
  80.   
  81.         //获得控制器名称
  82.         $controller_str =  $input->getArgument('controller_name');
  83.   
  84.         //获得模式,d为wokerman的后台模式(生产环境)
  85.         $mode = $input->getArgument('mode');
  86.   
  87.         //分析控制器参数,如果缺省或为all,那么运行所有注册的控制器
  88.         $controller_list = $this->controller_names;
  89.   
  90.         if($controller_str != '' && $controller_str != 'all' )
  91.         {
  92.             $controller_list = explode('/',$controller_str);
  93.         }
  94.   
  95.         //重写mode参数,改为wokerman接受的参数
  96.         if($mode == 'd'){
  97.             $mode = '-d';
  98.         }
  99.   
  100.         if($mode == 'g'){
  101.             $mode = '-g';
  102.         }
  103.   
  104.         //将wokerman需要的参数传入到其parseCommand方法中,此方法在start类中重写
  105.         Start::$argvs = [
  106.             'think',
  107.             $status,
  108.             $mode
  109.         ];
  110.   
  111.         $output->writeln('start running spider');
  112.   
  113.         $programs_ob_list = [];
  114.   
  115.   
  116.         //实例化需要运行的控制器
  117.         foreach ($controller_list as $c_key => $controller_name) {
  118.             $class_name = 'app\\'.$this->model_name.'\controller\\'.$controller_name;
  119.             $programs_ob_list[] = new $class_name();
  120.         }
  121.   
  122.   
  123.   
  124.         //将控制器的相关回调参数传到workerman中
  125.         foreach (['onWorkerStart', 'onConnect', 'onMessage', 'onClose', 'onError', 'onBufferFull', 'onBufferDrain', 'onWorkerStop', 'onWorkerReload'] as $event) {
  126.             foreach ($programs_ob_list as $p_key => $program_ob) {
  127.                 if (method_exists($program_ob, $event)) {
  128.                     $programs_ob_list[$p_key]->$event = [$program_ob,$event];
  129.                 }
  130.             }
  131.         }
  132.   
  133.         Start::runAll();
  134.     }
  135. }

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

  1. <?php
  2. namespace app\server\controller;
  3. use Workerman\Worker; 
  4. use \Workerman\Lib\Timer;
  5. use think\facade\Cache;
  6. use think\facade\Db;
  7. use think\Request;
  8.   
  9. class WebhookTimer extends Start
  10. {
  11.     public $host     = '0.0.0.0';
  12.     public $port     = '9527';
  13.     public $name     = 'webhook';
  14.     public $count    = 1;
  15.     public function onWorkerStart($worker)
  16.     {
  17.        
  18.          
  19.             Timer::add(2, array($this, 'webhooks'), array(), true);
  20.          
  21.       
  22.     }
  23.     public function onConnect()
  24.     {
  25.   
  26.     }
  27.   
  28.     public function onMessage($ws_connection, $message)
  29.     {
  30.         
  31.     }
  32.   
  33.     public function onClose()
  34.     {
  35.   
  36.     }
  37.      
  38.     public function webhooks()
  39.     {
  40.   
  41.        echo 11;
  42.     }
  43.      
  44.      
  45. }

执行start命令行

  1. php think spider start


浅析thinkphp6中怎么使用workerman


执行stop命令

  1. php think spider stop

执行全部进程命令

  1. php think spider start all d

app\command\Spider.php文件

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

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


完结

Start.php文件

  1. <?php
  2. namespace app\server\controller;
  3.   
  4. use Workerman\Worker;
  5.   
  6. class Start extends Worker
  7. {
  8.     public static $argvs = [];
  9.     public static $workerHost;
  10.     public $socket   = '';
  11.     public $protocol = 'http';
  12.     public $host     = '0.0.0.0';
  13.     public $port     = '2346';
  14.     public $context  = [];
  15.   
  16.     public function __construct()
  17.     {
  18.         self::$workerHost = parent::__construct($this->socket ?: $this->protocol . '://' . $this->host . ':' . $this->port, $this->context);
  19.     }
  20.   
  21.     /**
  22.      * parseCommand
  23.      * 重写wokerman的解析命令方法
  24.      * @return mixed
  25.      */
  26.     public static function parseCommand()
  27.     {
  28.         if (static::$_OS !== OS_TYPE_LINUX) {
  29.             return;
  30.         }
  31.         // static::$argvs;
  32.         // Check static::$argvs;
  33.         $start_file = static::$argvs[0];
  34.         $available_commands = array(
  35.             'start',
  36.             'stop',
  37.             'restart',
  38.             'reload',
  39.             'status',
  40.             'connections',
  41.         );
  42.         $usage = "Usage: php yourfile <command> [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";
  43.         if (!isset(static::$argvs[1]) || !in_array(static::$argvs[1], $available_commands)) {
  44.             if (isset(static::$argvs[1])) {
  45.                 static::safeEcho('Unknown command: ' . static::$argvs[1] . "\n");
  46.             }
  47.             exit($usage);
  48.         }
  49.   
  50.         // Get command.
  51.         $command  = trim(static::$argvs[1]);
  52.         $command2 = isset(static::$argvs[2]) ? static::$argvs[2] : '';
  53.   
  54.         // Start command.
  55.         $mode = '';
  56.         if ($command === 'start') {
  57.             if ($command2 === '-d' || static::$daemonize) {
  58.                 $mode = 'in DAEMON mode';
  59.             } else {
  60.                 $mode = 'in DEBUG mode';
  61.             }
  62.         }
  63.         static::log("Workerman[$start_file] $command $mode");
  64.   
  65.         // Get master process PID.
  66.         $master_pid      = is_file(static::$pidFile) ? file_get_contents(static::$pidFile) : 0;
  67.         $master_is_alive = $master_pid && posix_kill($master_pid, 0) && posix_getpid() != $master_pid;
  68.         // Master is still alive?
  69.         if ($master_is_alive) {
  70.             if ($command === 'start') {
  71.                 static::log("Workerman[$start_file] already running");
  72.                 exit;
  73.             }
  74.         } elseif ($command !== 'start' && $command !== 'restart') {
  75.             static::log("Workerman[$start_file] not run");
  76.             exit;
  77.         }
  78.   
  79.         // execute command.
  80.         switch ($command) {
  81.             case 'start':
  82.                 if ($command2 === '-d') {
  83.                     static::$daemonize = true;
  84.                 }
  85.                 break;
  86.             case 'status':
  87.                 while (1) {
  88.                     if (is_file(static::$_statisticsFile)) {
  89.                         @unlink(static::$_statisticsFile);
  90.                     }
  91.                     // Master process will send SIGUSR2 signal to all child processes.
  92.                     posix_kill($master_pid, SIGUSR2);
  93.                     // Sleep 1 second.
  94.                     sleep(1);
  95.                     // Clear terminal.
  96.                     if ($command2 === '-d') {
  97.                         static::safeEcho("\33[H\33[2J\33(B\33[m", true);
  98.                     }
  99.                     // Echo status data.
  100.                     static::safeEcho(static::formatStatusData());
  101.                     if ($command2 !== '-d') {
  102.                         exit(0);
  103.                     }
  104.                     static::safeEcho("\nPress Ctrl+C to quit.\n\n");
  105.                 }
  106.                 exit(0);
  107.             case 'connections':
  108.                 if (is_file(static::$_statisticsFile) && is_writable(static::$_statisticsFile)) {
  109.                     unlink(static::$_statisticsFile);
  110.                 }
  111.                 // Master process will send SIGIO signal to all child processes.
  112.                 posix_kill($master_pid, SIGIO);
  113.                 // Waiting amoment.
  114.                 usleep(500000);
  115.                 // Display statisitcs data from a disk file.
  116.                 if(is_readable(static::$_statisticsFile)) {
  117.                     readfile(static::$_statisticsFile);
  118.                 }
  119.                 exit(0);
  120.             case 'restart':
  121.             case 'stop':
  122.                 if ($command2 === '-g') {
  123.                     static::$_gracefulStop = true;
  124.                     $sig = SIGTERM;
  125.                     static::log("Workerman[$start_file] is gracefully stopping ...");
  126.                 } else {
  127.                     static::$_gracefulStop = false;
  128.                     $sig = SIGINT;
  129.                     static::log("Workerman[$start_file] is stopping ...");
  130.                 }
  131.                 // Send stop signal to master process.
  132.                 $master_pid && posix_kill($master_pid, $sig);
  133.                 // Timeout.
  134.                 $timeout    = 5;
  135.                 $start_time = time();
  136.                 // Check master process is still alive?
  137.                 while (1) {
  138.                     $master_is_alive = $master_pid && posix_kill($master_pid, 0);
  139.                     if ($master_is_alive) {
  140.                         // Timeout?
  141.                         if (!static::$_gracefulStop && time() - $start_time >= $timeout) {
  142.                             static::log("Workerman[$start_file] stop fail");
  143.                             exit;
  144.                         }
  145.                         // Waiting amoment.
  146.                         usleep(10000);
  147.                         continue;
  148.                     }
  149.                     // Stop success.
  150.                     static::log("Workerman[$start_file] stop success");
  151.                     if ($command === 'stop') {
  152.                         exit(0);
  153.                     }
  154.                     if ($command2 === '-d') {
  155.                         static::$daemonize = true;
  156.                     }
  157.                     break;
  158.                 }
  159.                 break;
  160.             case 'reload':
  161.                 if($command2 === '-g'){
  162.                     $sig = SIGQUIT;
  163.                 }else{
  164.                     $sig = SIGUSR1;
  165.                 }
  166.                 posix_kill($master_pid, $sig);
  167.                 exit;
  168.             default :
  169.                 if (isset($command)) {
  170.                     static::safeEcho('Unknown command: ' . $command . "\n");
  171.                 }
  172.                 exit($usage);
  173.         }
  174.     }
  175.   
  176. }


TAG标签:
本文网址:https://www.zztuku.com/index.php/detail-13530.html
站长图库 - 浅析thinkphp6中怎么使用workerman
申明:本文转载于《CSDN》,如有侵犯,请 联系我们 删除。

评论(0)条

您还没有登录,请 登录 后发表评论!

提示:请勿发布广告垃圾评论,否则封号处理!!

    编辑推荐