Laravel简单粗暴的队列

场景

抓取一批域名的whois信息

路由

Route::controller('whois', 'WhoisController');

传统操作控制器

class WhoisController extends Controller
{
 /**
 * 开始执行任务
 */
 function getStart() {
 $domains = ['baidu.com', 'zhujunwu.cn', 'laravel.com'];
 foreach($domains as $domain) {
 $this->query_whois($domain);
 echo $domain . ' has done at ' . date('Y-m-d H:i:s') . '<br/>';
 }
 }
/**
 * 模拟耗时过程
 * @param $domain
 * @return string
 */
 function query_whois($domain) {
 sleep(rand(1, 5));
 return $domain;
 }
}

输出

当浏览器访问”http://localhost:8000/whois/start”,调用爬行脚本即query_whois方法,当浏览器的菊花停止转动,输出以下结果:

baidu.com has done at 2015-11-05 06:49:27
zhujunwu.cn has done at 2015-11-05 06:49:28
laravel.com has done at 2015-11-05 06:49:31

可以看得出整个程序阻塞了。

队列操作

配置

请参考官方配置,别如这里使用redis,则只需要配置环境即可:

QUEUE_DRIVER=redis

创建队列

php artisan make:job GetWhois --queued
use App\Http\Controllers\WhoisController;
class GetWhois extends Job implements SelfHandling, ShouldQueue
{
 use InteractsWithQueue, SerializesModels;
 
 protected $domain;
/**
 * Create a new job instance.
 *
 * @return void
 */
 public function __construct($domain)
 {
 $this->domain = $domain;
 }
/**
 * Execute the job.
 *
 * @return void
 */
 public function handle(WhoisController $whoisController)
 {
 $whoisController->query_whois($this->domain);
 }
}

控制器

引入GetWhois类’use App\Jobs\GetWhois;’,修改getStart()方法:

 function getStart() {
 $domains = ['baidu.com', 'zhujunwu.cn', 'laravel.com'];
 foreach($domains as $domain) {
// $this->query_whois($domain);
 $this->dispatch(new GetWhois($domain));
 echo $domain . ' has done at ' . date('Y-m-d H:i:s') . '<br/>';
 }
 }

输出

再次访问start,输出:

baidu.com has done at 2015-11-05 06:50:53
zhujunwu.cn has done at 2015-11-05 06:50:53
laravel.com has done at 2015-11-05 06:50:53

任务列表

使用redis客户端查看任务列表

laravel-redis

监听

事实上目前为止并未执行query_whois方法,我们需要使用命令来监听队列:

php artisan queue:listen

部署到服务器时,推荐使用supervisor。