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 = '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(); } }
例如我们创建一个定时器的命令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 = '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
在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 = ''; 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]\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); } } }
更多编程相关知识,请访问:编程教学!!
위 내용은 thinkphp6에서 Workerman을 사용하는 방법에 대한 간략한 분석 [튜토리얼 공유]의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











ThinkPHP 프로젝트를 실행하려면 다음이 필요합니다: Composer를 설치하고, 프로젝트 디렉터리를 입력하고 php bin/console을 실행하고, 시작 페이지를 보려면 http://localhost:8000을 방문하세요.

Workerman 문서에서 파일 업로드 및 다운로드를 구현하려면 특정 코드 예제가 필요합니다. 소개: Workerman은 간단하고 효율적이며 사용하기 쉬운 고성능 PHP 비동기 네트워크 통신 프레임워크입니다. 실제 개발에서 파일 업로드 및 다운로드는 일반적인 기능 요구 사항입니다. 이 기사에서는 Workerman 프레임워크를 사용하여 파일 업로드 및 다운로드를 구현하는 방법을 소개하고 구체적인 코드 예제를 제공합니다. 1. 파일 업로드: 파일 업로드란 로컬 컴퓨터에 있는 파일을 서버로 전송하는 작업을 말합니다. 다음이 사용됩니다

ThinkPHP에는 다양한 PHP 버전용으로 설계된 여러 버전이 있습니다. 메이저 버전에는 3.2, 5.0, 5.1, 6.0이 포함되며, 마이너 버전은 버그를 수정하고 새로운 기능을 제공하는 데 사용됩니다. 최신 안정 버전은 ThinkPHP 6.0.16입니다. 버전을 선택할 때 PHP 버전, 기능 요구 사항 및 커뮤니티 지원을 고려하십시오. 최상의 성능과 지원을 위해서는 최신 안정 버전을 사용하는 것이 좋습니다.

ThinkPHP Framework를 로컬에서 실행하는 단계: ThinkPHP Framework를 로컬 디렉터리에 다운로드하고 압축을 풉니다. ThinkPHP 루트 디렉터리를 가리키는 가상 호스트(선택 사항)를 만듭니다. 데이터베이스 연결 매개변수를 구성합니다. 웹 서버를 시작합니다. ThinkPHP 애플리케이션을 초기화합니다. ThinkPHP 애플리케이션 URL에 접속하여 실행하세요.

"개발 제안: ThinkPHP 프레임워크를 사용하여 비동기 작업을 구현하는 방법" 인터넷 기술의 급속한 발전으로 인해 웹 응용 프로그램은 많은 수의 동시 요청과 복잡한 비즈니스 논리를 처리하기 위한 요구 사항이 점점 더 높아졌습니다. 시스템 성능과 사용자 경험을 향상시키기 위해 개발자는 이메일 보내기, 파일 업로드 처리, 보고서 생성 등과 같이 시간이 많이 걸리는 작업을 수행하기 위해 비동기 작업을 사용하는 것을 종종 고려합니다. PHP 분야에서 널리 사용되는 개발 프레임워크인 ThinkPHP 프레임워크는 비동기 작업을 구현하는 몇 가지 편리한 방법을 제공합니다.

Laravel과 ThinkPHP 프레임워크의 성능 비교: ThinkPHP는 일반적으로 최적화 및 캐싱에 중점을 두고 Laravel보다 성능이 좋습니다. Laravel은 잘 작동하지만 복잡한 애플리케이션의 경우 ThinkPHP가 더 적합할 수 있습니다.

Workerman 문서의 기본 사용법을 구현하는 방법 소개: Workerman은 개발자가 동시성이 높은 네트워크 애플리케이션을 쉽게 구축하는 데 도움이 되는 고성능 PHP 개발 프레임워크입니다. 이 기사에서는 설치 및 구성, 서비스 및 수신 포트 생성, 클라이언트 요청 처리 등 Workerman의 기본 사용법을 소개합니다. 그리고 해당 코드 예제를 제공하십시오. 1. Workerman을 설치하고 구성하려면 명령줄에 다음 명령을 입력합니다.

Swoole과 Workerman은 모두 고성능 PHP 서버 프레임워크입니다. 비동기 처리, 우수한 성능 및 확장성으로 잘 알려진 Swoole은 많은 수의 동시 요청과 높은 처리량을 처리해야 하는 프로젝트에 적합합니다. Workerman은 사용 편의성과 낮은 동시성 볼륨을 처리하는 프로젝트에 더 적합한 직관적인 API를 통해 비동기식 및 동기식 모드의 유연성을 제공합니다.
