laravel - 在运行事件 Laravel 之前向客户端返回响应
问题描述
有没有更丑陋的方法来做到这一点:
ignore_user_abort(true);
set_time_limit(0);
ob_start();
echo $response; // send the response
header('Connection: close');
header('Content-Length: '.ob_get_length());
ob_end_flush();
ob_flush();
flush();
在 Laravel 中?基本上我需要服务器在运行事件之前向用户返回响应,我不能使用队列来执行此操作,因为要完成很多事情,并且很多客户端同时执行此操作,而这些事情需要完成瞬间,所以不能一一执行。这些事件包括发送邮件、警报、更新网站表格上的数据等。
解决方案
我在创建跟踪像素的项目中也有类似的需求。我想立即回复他们,然后 Laravel 继续运行。我把它作为第一件事index.php
:
if($_SERVER['REQUEST_URI'] == '/pixel'){
require "pixel.php";
}
然后在该文件中(其中一些可能与您无关,我需要确保他们没有缓存它,以便继续加载像素:
ignore_user_abort(true);
// turn off gzip compression
if ( function_exists( 'apache_setenv' ) ) {
apache_setenv( 'no-gzip', 1 );
}
ini_set('zlib.output_compression', 0);
// turn on output buffering if necessary
if (ob_get_level() == 0) {
ob_start();
}
// removing any content encoding like gzip etc.
header('Content-encoding: none', true);
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
echo ' ';
} else {
header("Content-type: image/gif");
header("Content-Length: 42");
header("Cache-Control: private, no-cache, no-cache=Set-Cookie, proxy-revalidate");
header("Expires: Wed, 11 Jan 2000 12:59:00 GMT");
header("Last-Modified: Wed, 11 Jan 2006 12:59:00 GMT");
header("Pragma: no-cache");
echo sprintf('%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%',71,73,70,56,57,97,1,0,1,0,128,255,0,192,192,192,0,0,0,33,249,4,1,0,0,0,0,44,0,0,0,0,1,0,1,0,0,2,2,68,1,0,59);
}
// flush all output buffers. No reason to make the user wait for OWA.
ob_flush();
flush();
ob_end_flush();
而已。现在,Laravel 继续运行,但是用户的浏览器已经结束了它的请求。因此,我添加了一条正常的路线,/pixel
并完成了我需要做的所有事情(添加到数据库、触发事件等)。
推荐阅读
- javascript - 以编程方式输入密码并按下按钮
- r - RenderUI 的闪亮书签问题
- graphql -
不使用我的自定义数据提供程序(棱镜) - python - 从查询列中分割字符串并将结果插入同一个表中
- ui-automation - Katalon Studio 是否支持混合应用自动化和新的浏览器版本发布?
- ios - 不遵守 Admob 上限
- java - 为什么通过Interface.super调用一个超接口的方法?
- java - PayPal API - 在捕获时更新付款详细信息
- c# - 查询或合并一对多关系而不复制结果条目
- c# - ASP.NET Core 2.1 - 选项模式 - 访问选项不返回绑定类的实例