Thinkphp5.1里面如何使用workerman
2022-07-28 14:14:58
140
{{single.collect_count}}

之前一直用swoole,最近研究workerman,于是composer安装

composer require workerman/workerman

在Thinkphp控制器里面写一段测试代码

<?phpnamespace 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');};// 运行workerWorker::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了。可以使用thinkphp5的方式安装workerman,那样就可以使用thinkphp的运行方式运行了。
具体方式请查阅Thinkphp5.1官方文档。执行命令改成
php think worker
后续发现Thinkphp5.1整合的workerman封装的有点麻烦,不好用,而且如果你想用PHPSocketIO之类的workerman服务用整合的方式很麻烦。还是想自己写服务。
后来想了下,workerman把第一个参数作为操作服务的命令,那我把它改成用第二个参数作为操作命令行不行?果然就是这么做的。查找workerman插件里面的parseCommand()函数。这个鬼函数就是获取那个操作命令的,把argv[1]改成argv[1]改成 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解析操作服务命令)

OK,以上。

回帖
全部回帖({{commentCount}})
{{item.user.nickname}} {{item.user.group_title}} {{item.friend_time}}
{{item.content}}
{{item.comment_content_show ? '取消' : '回复'}} 删除
回帖
{{reply.user.nickname}} {{reply.user.group_title}} {{reply.friend_time}}
{{reply.content}}
{{reply.comment_content_show ? '取消' : '回复'}} 删除
回帖
收起
没有更多啦~
{{commentLoading ? '加载中...' : '查看更多评论'}}