先讲下为什么要使用swoole异步任务,在项目中我们经常会遇到执行时间比较久的请求(上传,爬取等),让用户一直等待不是好的体验,所以我们使用swoole异步请求,先返回‘执行中’,等异步任务执行完毕再修改状态。
接下来我们来实现swoole在thinkphp 里的集成:
1.安装swoole
推荐使用官网提供的安装方式 安装swoole扩展
2.安装QueryList
composer require jaeger/querylist
文档地址 querylist
3.在Tp5里自定义一个命令行类
在application下建立一个console文件夹用来存放自定义命令文件,然后在该文件夹下新建Crawler.php文件,编辑application目录下的command.php文件
添加如下代码
return [
'app\console\Crawler',
];
编写 Crawler.php
<?php
namespace app\Console;
use QL\QueryList;
use think\console\Command;
use think\console\Input;
use think\console\Output;
class Ceshi extends Command{
protected $server;
protected function configure()
{
//参考tp5自定义命令行手册
$this->setName('crawler:start')->setDescription('Start Crawler Server!');
}
protected function execute(Input $input, Output $output)
{
$serv = new \swoole_server('0.0.0.0',9502);//9502为swoole监听端口,可以自行设置
$serv->set(array('task_worker_num' =>