這篇文章主要介紹Thinkphp5.1里怎么使用workerman,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
Workerman是一款純PHP開發的開源高性能的異步PHP socket框架。ThinkPHP是一個快速、兼容而且簡單的輕量級國產PHP開發框架。
之前一直用swoole,最近研究workerman,于是composer安裝
composer require workerman/workerman
在Thinkphp控制器里面寫一段測試代碼
<?php
namespace app\workerman\controller;
use think\Controller;
use Workerman\Worker;
class Index extends Controller
{
public function index()
{
// 創建一個Worker監聽2345端口,使用http協議通訊
$http_worker = new Worker("http://0.0.0.0:2345");
// 啟動4個進程對外提供服務
$http_worker->count = 4;
// 接收到瀏覽器發送的數據時回復hello world給瀏覽器
$http_worker->onMessage = function($connection, $data)
{
// 向瀏覽器發送hello world
$connection->send('hello world');
};
// 運行worker
Worker::runAll();
}
}命令行執行:php index.php workerman/index。以為大功告成,但是卻報下面的提示:

很明顯,workerman不能直接運行文件,看官方文檔是使用
php index.php start
php index.php stop
php index.php restart
這樣的格式執行。于是修改index.php文件綁定路由
// [ 應用入口文件 ]
namespace think;
// 加載基礎文件
require __DIR__ . '/../thinkphp/base.php';
// 支持事先使用靜態方法設置Request對象和Config對象
// 執行應用并響應
Container::get('app')->bind("workerman/index")->run()->send();直接運行php index.php start,汗,居然提示說找不到start該模型。特么tp5把start作為路由解析了。那怎么辦,workerman的需要使用start的方式執行,tp5卻要把該參數解析成模型啊。
后查閱資料發現,Thinkphp5.1本身就整合了workerman了??梢允褂胻hinkphp5的方式安裝workerman,那樣就可以使用thinkphp的運行方式運行了。
執行命令改成:
php think worker
后續發現Thinkphp5.1整合的workerman封裝的有點麻煩,不好用,而且如果你想用PHPSocketIO之類的workerman服務用整合的方式很麻煩。
workerman把第一個參數作為操作服務的命令,那我把它改成用第二個參數作為操作命令行不行?
果然就是這么做的。查找workerman插件里面的parseCommand()函數。這個鬼函數就是獲取那個操作命令的,把:
argv[1]改成argv[2],argv[2]改成argv[2]改成argv[2]改成argv[3]
protected static function parseCommand()
{
if (static::$_OS !== OS_TYPE_LINUX) {
return;
}
global $argv;
// Check argv;
$start_file = $argv[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($argv[2]) || !in_array($argv[2], $available_commands)) {
if (isset($argv[2])) {
static::safeEcho('Unknown command: ' . $argv[2] . "\n");
}
exit($usage);
}
// Get command.
$command = trim($argv[2]);
$command2 = isset($argv[3]) ? $argv[3] : '';執行命令改成
php server.php index start
(第一個參數用于Thinkphp解析路由,第二個參數用于workerman解析操作服務命令)
以上是“Thinkphp5.1里怎么使用workerman”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。