前景需求:在我们用队列的时候发现maxtries的个数时255次,这个太影响其他队列任务
我目前使用的thinkphp版本是6.1
第一部定义一个新的类
CustomDataBase(我用的mysql数据库存放的队列)
重写__make 和createPlainPayload方法或者getNextAvailableJob,两个方法有区别
createPlainPayload:当attempts超过maxTries就会走job的failed,且会将当前数据库中的job数据删掉
getNextAvailableJob:attempts超过10次的就不会再处理,也不会删掉此数据
<?php
namespace app;
use Carbon\Carbon;
use think\Db;
use think\db\Query;
use think\queue\connector\Database;
class CustomDataBase extends Database
{
public static function __make(Db $db, $config)
{
$connection = $db->connect($config['connection'] ?? null);
return new self($connection, $config['table'], $config['queue'], $config['retry_after'] ?? 60);
}
// 当attempts超过maxTries就会走job的failed,且会将当前数据库中的job数据删掉
protected function createPlainPayload($job, $data)
{
return [
'job' => $job,
'maxTries' => 22,
'timeout' => null,
'data' => $data,
];
}
// attempts超过10次的就不会再处理,也不会删掉此数据
protected function getNextAvailableJob($queue)
{
$job = $this->db
->name($this->table)
->lock(true)
->where('queue', $this->getQueue($queue))
->where('attempts', '<=',10)
->where(function (Query $query) {
$query->where(function (Query $query) {
$query->whereNull('reserve_time')
->where('available_time', '<=', $this->currentTime());
});
//超时任务重试
$expiration = Carbon::now()->subSeconds($this->retryAfter)->getTimestamp();
$query->whereOr(function (Query $query) use ($expiration) {
$query->where('reserve_time', '<=', $expiration);
});
})
->order('id', 'asc')
->find();
return $job ? (object) $job : null;
}
}
第二步修改queue.php文件的配置
为什么要重写类,自己要点Queue::push(),查看源码,因为我的项目通篇用的都是用的类名,最简单的是重写,当然你也可以自己在push的时候写对象,对象里面定义属性$tries=10;
Queue::push(EmailJob::class, $email->id);