php - 我想在 laravel 中运行一个异步调用,然后返回 true。RETURN TRUE 不必等待异步调用完成
问题描述
实际上,我已经创建了一个 shopify 应用程序,并使用它来卸载 webhook。在卸载应用程序时,shopify 会通知我有关应用程序的卸载,以便我可以执行一些相关过程。如果 shopify 在 5 秒内没有得到响应,那么它会向我发送其他通知,导致两个电话。
在我的 webhook 功能中,我只是从我的数据库中删除了商店,这有时需要一些时间。我可以在 laravel 中做些什么,以便我的删除过程异步运行。在调用将是异步的删除过程之后,我的下一行代码就可以了return "true"
。我的卸载功能在下面给定代码中的 InstallController.php 中。
在应用\工作。我创建了 BackgroundJobs.php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\DB;
class BackgroundJobs implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $shopId;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($shopId)
{
$this->shopId = $shopId;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
DB::table("shops")
->where("id", $this->shopId)
->delete();
return true;
}
}
这是一个Controller InstallController.php,其中“uninstall()”函数调度队列。
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class InstallController extends Controller
{
public function index()
{
return view("install");
}
public function uninstall(Request $request)
{
$shop_id = $request->get('shopId');
// dispatching job
dispatch(new \App\Jobs\BackgroundJobs($shop_id));
return "true";
}
}
那么我怎样才能return "true"
并且不需要等待队列完成呢?
解决方案
您可以在完成工作之后或之前使用作业事件来执行代码
所以你在 AppServiceProvider 中定义启动方法
public function boot()
{
Queue::before(function (BackgroundJobs $event) {
// $event->connectionName
// $event->job
// $event->job->payload()
});
Queue::after(function (BackgroundJobs $event) {
// $event->connectionName
// $event->job
// $event->job->payload()
});
}
更多详情请查看官方文档
推荐阅读
- python - 获取查询返回的文档数
- oracle - 使用 SQL Developer 并收到以下错误:尝试将有效属性分配给代理
- python - 如何将字符串作为关键字参数传递给方法
- r - 随机化检查
- r - 随机分配任务到组
- java - 如何在 GraphqlJava 查询中支持排序
- c# - 具有身份角色授权的 Active Directory 身份验证
- ios - 提交 Crashlytics:无法上传二进制文件 - 但它实际上成功了
- macos - 如果脚本包含 import scipy.stats,则 OSX 10.14 脚本使用 pyinstall 编译为独立可执行文件
- python - Pytorch argsort 有序,张量中有重复元素