首页 > 解决方案 > 我想在 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"并且不需要等待队列完成呢?

标签: phplaravelwebhooksbackground-taskshopify-app

解决方案


您可以在完成工作之后或之前使用作业事件来执行代码

所以你在 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()
    });
}

更多详情请查看官方文档

https://laravel.com/docs/5.8/queues#job-events


推荐阅读