Mic*_*usa 5 queue jobs redis laravel-5
我几天前已经实现了一个工作队列,我遇到了重复问题,我目前正在使用Redis并遵循Laravel的官方教程.
在我的情况下,每当有人进入主页,作业被发送到队列,让我们举个例子:
HomeController的 index():
public function index()
{
if(/*condition*/){
//UpdateServer being the job
$this->dispatch(new UpdateServer());
}
}
Run Code Online (Sandbox Code Playgroud)
由于此任务大约需要10秒钟才能完成,如果在处理任务时对我的主页有n个请求,则队列中将会有更多相同的作业,从而导致我的数据库出现意外结果.
所以我的问题是,有没有办法知道某个工作是否已经在队列中?
小智 9
我知道这是一个老问题,但我发现自己一次又一次地从谷歌回来,所以我想给它一个答案.我想要一种简单的方法来在仪表板上查看Laravel应用程序内队列中的作业,并使用以下代码.
$thejobs = array();
// Get the number of jobs on the queue
$numJobs = Redis::connection()->llen('queues:default');
// Here we select details for up to 1000 jobs
$jobs = Redis::connection()->lrange('queues:default', 0, 1000);
// I wanted to clean up the data a bit
// you could use var_dump to see what it looks like before this
// var_dump($jobs);
foreach ($jobs as $job) {
// Each job here is in json format so decode to object form
$tmpdata = json_decode($job);
$data = $tmpdata->data;
// I wanted to just get the command so I stripped away App\Jobs at the start
$command = $this->get_string_between($data->command, '"App\Jobs\\', '"');
$id = $tmpdata->id;
// Could be good to see the number of attempts
$attempts = $tmpdata->attempts;
$thejobs[] = array($command, $id, $attempts);
}
// Now you can use the data and compare it or check if your job is already in queue
Run Code Online (Sandbox Code Playgroud)
我不建议这样做,特别是在页面加载,如op已完成的索引页面.如果您需要使用此代码来检查作业是否正在运行,则很可能需要重新考虑您的工作方式.
答案特定于运行Redis的队列.
我知道这是一个非常老的问题,但我正在为未来的谷歌用户回答它。
从Laravel 8开始,就有了“独特的工作”功能 - https://laravel.com/docs/8.x/queues#unique-jobs。