首頁 php框架 Workerman 淺析thinkphp6怎麼使用workerman【教學分享】

淺析thinkphp6怎麼使用workerman【教學分享】

Dec 08, 2022 pm 08:30 PM
thinkphp workerman thinkphp6

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

淺析thinkphp6怎麼使用workerman【教學分享】

thinkphp6整合workerman教程

thinkphp6安装workerman命令:

composer require topthink/think-worker
登入後複製

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

php think make:command Spider spider
登入後複製

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

<?php
namespace app\command;
 
// tp指令特性使用的功能
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;
 
// 引用项目的基类,该类继承自worker
use app\server\controller\Start;
 
/**
 * 指令类
 * 在此定义指令
 * 再次启动多个控制器
 * @var mixed
 */
class Spider extends Command
{
 
    /**
     * 注册模块名称
     * 使用命令会启动该模块控制器
     * @var mixed
     */
    public $model_name = &#39;server&#39;;
 
    /**
     * 注册控制器名称
     * 使用命令启动相关控制器
     * @var mixed
     */
    public $controller_names = [&#39;WebhookTimer&#39;];
 
    /**
     * configure
     * tp框架自定义指令特性
     * 注册命令参数
     * @return mixed
     */
    protected function configure()
    {
        $this->setName(&#39;spider&#39;)
            ->addArgument(&#39;status&#39;, Argument::OPTIONAL, "status")
            ->addArgument(&#39;controller_name&#39;, Argument::OPTIONAL, "controller_name/controller_name")
            ->addArgument(&#39;mode&#39;, Argument::OPTIONAL, "d")
            ->setDescription(&#39;spider control&#39;);
 
        /**
         * 以上设置命令格式为: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(&#39;status&#39;);
        if(!$status){
            $output->writeln(&#39;pelase input control command , like start&#39;);
            exit;
        }
 
 
        //获得控制器名称
        $controller_str =  $input->getArgument(&#39;controller_name&#39;);
 
        //获得模式,d为wokerman的后台模式(生产环境)
        $mode = $input->getArgument(&#39;mode&#39;);
 
        //分析控制器参数,如果缺省或为all,那么运行所有注册的控制器
        $controller_list = $this->controller_names;
 
        if($controller_str != &#39;&#39; && $controller_str != &#39;all&#39; )
        {
            $controller_list = explode(&#39;/&#39;,$controller_str);
        }
 
        //重写mode参数,改为wokerman接受的参数
        if($mode == &#39;d&#39;){
            $mode = &#39;-d&#39;;
        }
 
        if($mode == &#39;g&#39;){
            $mode = &#39;-g&#39;;
        }
 
        //将wokerman需要的参数传入到其parseCommand方法中,此方法在start类中重写
        Start::$argvs = [
            &#39;think&#39;,
            $status,
            $mode
        ];
 
        $output->writeln(&#39;start running spider&#39;);
 
        $programs_ob_list = [];
 
 
        //实例化需要运行的控制器
        foreach ($controller_list as $c_key => $controller_name) {
            $class_name = &#39;app\\&#39;.$this->model_name.&#39;\controller\\&#39;.$controller_name;
            $programs_ob_list[] = new $class_name();
        }
 
 
 
        //将控制器的相关回调参数传到workerman中
        foreach ([&#39;onWorkerStart&#39;, &#39;onConnect&#39;, &#39;onMessage&#39;, &#39;onClose&#39;, &#39;onError&#39;, &#39;onBufferFull&#39;, &#39;onBufferDrain&#39;, &#39;onWorkerStop&#39;, &#39;onWorkerReload&#39;] 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

<?php
namespace app\server\controller;
use Workerman\Worker; 
use \Workerman\Lib\Timer;
use think\facade\Cache;
use think\facade\Db;
use think\Request;
 
class WebhookTimer extends Start
{
    public $host     = &#39;0.0.0.0&#39;;
    public $port     = &#39;9527&#39;;
    public $name     = &#39;webhook&#39;;
    public $count    = 1;
    public function onWorkerStart($worker)
    {
      
        
            Timer::add(2, array($this, &#39;webhooks&#39;), 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
登入後複製

app\command\Spider.php文件

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

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

完结

Start.php文件

<?php
namespace app\server\controller;
 
use Workerman\Worker;
 
class Start extends Worker
{
    public static $argvs = [];
    public static $workerHost;
    public $socket   = &#39;&#39;;
    public $protocol = &#39;http&#39;;
    public $host     = &#39;0.0.0.0&#39;;
    public $port     = &#39;2346&#39;;
    public $context  = [];
 
    public function __construct()
    {
        self::$workerHost = parent::__construct($this->socket ?: $this->protocol . &#39;://&#39; . $this->host . &#39;:&#39; . $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(
            &#39;start&#39;,
            &#39;stop&#39;,
            &#39;restart&#39;,
            &#39;reload&#39;,
            &#39;status&#39;,
            &#39;connections&#39;,
        );
        $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";
        if (!isset(static::$argvs[1]) || !in_array(static::$argvs[1], $available_commands)) {
            if (isset(static::$argvs[1])) {
                static::safeEcho(&#39;Unknown command: &#39; . static::$argvs[1] . "\n");
            }
            exit($usage);
        }
 
        // Get command.
        $command  = trim(static::$argvs[1]);
        $command2 = isset(static::$argvs[2]) ? static::$argvs[2] : &#39;&#39;;
 
        // Start command.
        $mode = &#39;&#39;;
        if ($command === &#39;start&#39;) {
            if ($command2 === &#39;-d&#39; || static::$daemonize) {
                $mode = &#39;in DAEMON mode&#39;;
            } else {
                $mode = &#39;in DEBUG mode&#39;;
            }
        }
        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 === &#39;start&#39;) {
                static::log("Workerman[$start_file] already running");
                exit;
            }
        } elseif ($command !== &#39;start&#39; && $command !== &#39;restart&#39;) {
            static::log("Workerman[$start_file] not run");
            exit;
        }
 
        // execute command.
        switch ($command) {
            case &#39;start&#39;:
                if ($command2 === &#39;-d&#39;) {
                    static::$daemonize = true;
                }
                break;
            case &#39;status&#39;:
                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 === &#39;-d&#39;) {
                        static::safeEcho("\33[H\33[2J\33(B\33[m", true);
                    }
                    // Echo status data.
                    static::safeEcho(static::formatStatusData());
                    if ($command2 !== &#39;-d&#39;) {
                        exit(0);
                    }
                    static::safeEcho("\nPress Ctrl+C to quit.\n\n");
                }
                exit(0);
            case &#39;connections&#39;:
                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 &#39;restart&#39;:
            case &#39;stop&#39;:
                if ($command2 === &#39;-g&#39;) {
                    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 === &#39;stop&#39;) {
                        exit(0);
                    }
                    if ($command2 === &#39;-d&#39;) {
                        static::$daemonize = true;
                    }
                    break;
                }
                break;
            case &#39;reload&#39;:
                if($command2 === &#39;-g&#39;){
                    $sig = SIGQUIT;
                }else{
                    $sig = SIGUSR1;
                }
                posix_kill($master_pid, $sig);
                exit;
            default :
                if (isset($command)) {
                    static::safeEcho(&#39;Unknown command: &#39; . $command . "\n");
                }
                exit($usage);
        }
    }
 
}
登入後複製

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

以上是淺析thinkphp6怎麼使用workerman【教學分享】的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

<🎜>:泡泡膠模擬器無窮大 - 如何獲取和使用皇家鑰匙
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
北端:融合系統,解釋
4 週前 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora:巫婆樹的耳語 - 如何解鎖抓鉤
3 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Java教學
1670
14
CakePHP 教程
1428
52
Laravel 教程
1329
25
PHP教程
1273
29
C# 教程
1256
24
thinkphp專案怎麼運行 thinkphp專案怎麼運行 Apr 09, 2024 pm 05:33 PM

執行 ThinkPHP 專案需要:安裝 Composer;使用 Composer 建立專案;進入專案目錄,執行 php bin/console serve;造訪 http://localhost:8000 查看歡迎頁面。

thinkphp有幾個版本 thinkphp有幾個版本 Apr 09, 2024 pm 06:09 PM

ThinkPHP 擁有多個版本,針對不同 PHP 版本而設計。主要版本包括 3.2、5.0、5.1 和 6.0,而次要版本用於修復 bug 和提供新功能。目前最新穩定版本為 ThinkPHP 6.0.16。在選擇版本時,需考慮 PHP 版本、功能需求和社群支援。建議使用最新穩定版本以獲得最佳性能和支援。

實作Workerman文件中的文件上傳與下載 實作Workerman文件中的文件上傳與下載 Nov 08, 2023 pm 06:02 PM

實現Workerman文件中的文件上傳與下載,需要具體程式碼範例引言:Workerman是一款高效能的PHP非同步網路通訊框架,具備簡潔、高效、易用等特點。在實際開發中,文件上傳和下載是常見的功能需求,本文將介紹如何使用Workerman框架實現文件的上傳和下載,並給出具體的程式碼範例。一、檔案上傳:檔案上傳是指將本機上的檔案傳輸至伺服器端的操作。下面是使用

thinkphp怎麼運行 thinkphp怎麼運行 Apr 09, 2024 pm 05:39 PM

ThinkPHP Framework 的本機運作步驟:下載並解壓縮 ThinkPHP Framework 到本機目錄。建立虛擬主機(可選),指向 ThinkPHP 根目錄。配置資料庫連線參數。啟動 Web 伺服器。初始化 ThinkPHP 應用程式。存取 ThinkPHP 應用程式 URL 運行。

laravel和thinkphp哪個好 laravel和thinkphp哪個好 Apr 09, 2024 pm 03:18 PM

Laravel 和 ThinkPHP 框架的效能比較:ThinkPHP 效能通常優於 Laravel,專注於最佳化和快取。 Laravel 性能良好,但對於複雜應用程序,ThinkPHP 可能更適合。

swoole和workerman哪個好 swoole和workerman哪個好 Apr 09, 2024 pm 07:00 PM

Swoole 和 Workerman 都是高效能 PHP 伺服器框架。 Swoole 以其非同步處理、出色的效能和可擴展性而聞名,適用於需要處理大量並發請求和高吞吐量的專案。 Workerman 提供了非同步和同步模式的靈活性,具有直覺的 API,更適合易用性和處理較低並發量的專案。

如何實作Workerman文件的基本使用方法 如何實作Workerman文件的基本使用方法 Nov 08, 2023 am 11:46 AM

如何實現Workerman文件的基本使用方法簡介:Workerman是一個高效能的PHP開發框架,它可以幫助開發者輕鬆建立高並發的網路應用程式。本文將介紹Workerman的基本使用方法,包括安裝和設定、建立服務和監聽連接埠、處理客戶端請求等。並給出相應的程式碼範例。一、安裝並設定Workerman在命令列中輸入以下命令來安裝Workerman:c

thinkphp怎麼安裝 thinkphp怎麼安裝 Apr 09, 2024 pm 05:42 PM

ThinkPHP 安裝步驟:準備 PHP、Composer、MySQL 環境。使用 Composer 建立專案。安裝 ThinkPHP 框架及相依性。配置資料庫連線。產生應用程式碼。啟動應用程式並造訪 http://localhost:8000。

See all articles