laravel 怎么异步执行 自定义Artisan Command

目前项目中遇到一些耗时比较长的第三方请求,所以想着写一个command来异步执行这些耗时的第三方请求。在用户请求相关接口时触发command,然后异步执行command。这时用户不需一直等待command的结果,可以继续浏览。
代码:

public function sync(){

        $enterId     = $this->request->input('enter_id');
        $warehouseId = $this->request->input('warehouse_id');
        $personId    = $this->request->attributes->get('person')->id;
        $warehouse   = Warehouse::getById($warehouseId, $enterId);
        $warehouse->syncValid(); //同步校验
        $commandKey = ['key' => 'SYNC_FBA','enterprise' => $enterId, 'warehouse'=>$warehouseId];
        $commandId  = CommandLog::getCommand($enterId,  $personId, $commandKey);
        Artisan::call('sync:fba',[
            'enterprise'=> $enterId,
            '--warehouse'=> $warehouseId,
            '--command'=> $commandId,
            '--help'=>true
        ]); //执行同步FBA

        return $this->response(['data'=>['command_id'=>$commandId]]);
    }

请问各位大佬,怎样可以可以异步执行sync:fba这个命令

阅读 5.3k
2 个回答

单纯的command想要异步是做不到的,你可以加一个队列,在队列里调用sync:fba,然后在逻辑里dispatch((new QueueJob($param)));往队列里push一个job,这样就能异步执行command了

新手上路,请多包涵
class YourCommand extends Command implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    ...
}

参照https://laravel-china.org/doc...
普通事件->队列事件,举一反三

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题