laravel异步事件中`shouldQueue`存在的问题
测试异步队列事件shouldQueue
存在的问题,方法如下:
- 在
shouldQueue
添加判断条件,值小于5继续操作 - 在
handle
中阻塞操作,并添加条件
代码如下:
<?php
namespace App\Listeners\Test;
use App\Events\Test\RollEvent;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Redis;
class CapterBEventListener implements ShouldQueue
{
use InteractsWithQueue;
public function handle(RollEvent $event)
{
$redis = Redis::class;
$num = $redis::incr('capter_test');
echo '执行:',$num,PHP_EOL;
$redis::expire('capter_test', 3600);
sleep(10);
echo '结束',PHP_EOL;
}
public function shouldQueue(RollEvent $event)
{
$redis = Redis::class;
$num = $redis::exists('capter_test') ? (int)$redis::get('capter_test') : 0;
return $num < 5;
}
}
测试如下:
- 执行结果跑了10遍
- 预期应该是跑4遍后停止
$ php artisan tinker >>> for($i = 0; $i < 10; $i++) event(new App\Events\Test\RollEvent(5))
我想可能有人会说,那么你把判断条件放到handle
中不就好了吗?例如:
public function handle(RollEvent $event)
{
$redis = Redis::class;
$num = $redis::exists('capter_test') ? (int)$redis::get('capter_test') : 0;
if ($num < 5)
{
// doit...
}
}
那么不就回到主题了么,shouldQueue
方法不是很鸡肋么?还有存在的意义么?同步事件又不支持,异步事件又存在问题?
上面我用
redis
是为了便于举例,同理,比如操作mysql
数据库,或者发起异步请求,同样会出现类似的问题
推荐文章: