编辑 config/database.php
,redis数组新增如下键值:
'queue' => [
'url' => env('REDIS_URL'),
'host' => env('REDIS_HOST', '127.0.0.1'),
'username' => env('REDIS_USERNAME'),
'password' => env('REDIS_PASSWORD'),
'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_QUEUE_DB', '2'),
],
.env
文件添加变量
# 指定redis队列库为db2
REDIS_QUEUE_DB=2
QUEUE_CONNECTION=redis
编辑 config/queue.php
'redis' => [
'driver' => 'redis',
'connection' => 'queue',// 将默认连接修改为上面新增的queue
'queue' => env('REDIS_QUEUE', 'default'),
'retry_after' => 90,
'block_for' => null,
'after_commit' => false,
],
创建 Job
类
php artisan make:job ProcessEmail
编辑 app/Jobs/ProcessEmail.php
class ProcessEmail implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* Create a new job instance.
* 注入Order模型
* @return void
*/
public function __construct(private readonly Order $order)
{
// 修改队列连接库
$this->onConnection('redis');
}
/**
* Execute the job.
*
* @return void
*/
public function handle(): void
{
// 调用mail发送邮件
Mail::to($this->order->user)->queue(new OrderPost($this->order));
}
}
调用
public function store(Request $req)
{
// 获取数据
$data = $req->all();
//创建新订单逻辑
$order = Order::create($data);
// 调用任务类
ProcessEmail::dispatch($order);
return $this->json();
}
启动任务进程
php artisan queue:work --tries=3 // 最大尝试数