在我的多服务器应用程序中,我使用laravel的Queuing系统来运行后台作业。有时,按照我的逻辑,我想让我的工作引发异常,以便我可以使用提供的laravel library通过岗亭记录该异常。
所以在我的工作中:
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use App\Model\Etable\User;
use App\Model\User;
class MyJob implements ShouldQueue
{
use Dispatchable;
use InteractsWithQueue;
use Queueable;
/**
* @var int
*/
private $user_id;
/**
* @param int $user The user that has opted or deopted for newsletter consent
*/
public function __construct(int $id)
{
$this->user_id = $user_id;
}
public function handle(): void
{
/**
* @var User
*/
$user=User::useWritePdo()->find($this->user_id);
if(empty($user)){
throw new \Exception("No such a user with user id: {$this->user_id}");
}
// Rest of logic here
}
}
一旦抛出异常,我将登录哨兵,但由于laravel的工作逻辑应该这样做,所以它将继续产生。
就我而言,在用户不存在的情况下,保持重生MyJob
浪费资源是没有资源的,因为在没有用户的情况下,逻辑本身无法执行,因此无法继续产生。另一方面,对于其他任何错误,我希望我的工作继续重试,直到能够再次成功运行。
因此,如何使我的工作不因特定的错误而重生?如果我可以使用默认的日志方法laravel ofers来更好地将错误通过哨兵专用通道记录到哨兵中,那就更好了。
请注意,除非您明确运行,否则失败的作业将不会重新运行
php artisan queue:failed
您可以引发异常并在AppServiceProvider的启动方法deleting the job中进行处理,以避免其再次尝试。有关如何操作,请参见documentation。
最好和更容易的方法是一旦代码无法检查已经执行了多少次:
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use App\Model\Etable\User;
use App\Model\User;
class MyJob implements ShouldQueue
{
use Dispatchable;
use InteractsWithQueue;
use Queueable;
/**
* @var int
*/
private $user_id;
/**
* @param int $user The user that has opted or deopted for newsletter consent
*/
public function __construct(int $id)
{
$this->user_id = $user_id;
}
public function handle(): void
{
/**
* @var User
*/
$user=User::useWritePdo()->find($this->user_id);
if(empty($user)){
if ($this->attempts() > 1) {
return;
}
throw new \Exception("No such a user with user id: {$this->user_id}");
}
// Rest of logic here
}
}
这是通过以下方式实现的:
if ($this->attempts() > 1) {
return;
}
因此,一旦抛出异常,该异常将被登录到哨兵中,然后在第二次执行该异常时,它将退出并且永远不会重生。