如何在 Laravel 中响应 HTTP 请求后执行某些操作

问题描述 投票:0回答:2

我想知道 Laravel 5 是否可以在响应 HTTP 响应后执行某些操作。

例如,我想回复向我发出请求的服务器,然后开始发送一些电子邮件和通知。

这样服务器就不必等待我发送电子邮件和通知来得到答案。

谢谢你

php laravel laravel-5
2个回答
4
投票

这绝对是可能的!查看有关队列的文档:https://laravel.com/docs/5.2/queues

基本上,您可以创建一个实现

ShouldQueue
接口的作业,它将使用您在 .env 文件中指定的
QUEUE_DRIVER
并回退到“同步”,这意味着它将同步发生。


0
投票

对于 laravel 6+ 有dispatchAfterResponse

dispatch($job)->afterResponse();

来自文档:

您还可以分派一个闭包并链接 afterResponse 方法 到调度助手上以在 HTTP 响应后执行闭包 已发送至浏览器:

use App\Mail\WelcomeMessage;
use Illuminate\Support\Facades\Mail;
 
dispatch(function () {
    Mail::to('[email protected]')->send(new WelcomeMessage);
})->afterResponse();

https://laravel.com/docs/10.x/queues#dispatching-after-the-response-is-sent-to-browser

© www.soinside.com 2019 - 2024. All rights reserved.