laravel 如何在laravel中异步执行事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39777828/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 14:32:17  来源:igfitidea点击:

how to execute events asynchronously in laravel

phplaravelasynchronous

提问by Mazino S Ukah

Pls I'm still new to laravel and I have used events in laravel a couple of times but I'm curious and would like to know if it's possible to execute an event in laravel asynchronously. Like for instance in the code below:

请我还是 laravel 的新手,我已经在 laravel 中使用过几次事件,但我很好奇,想知道是否可以在 laravel 中异步执行事件。例如在下面的代码中:

    <?php

    namespace mazee\Http\Controllers;

   class maincontroller extends Controller
   {
    public  function index(){
       Event::fire(new newaccountcreated($user)) ;
      //do something

    }

Is it possible for the block of code in the event listener of the "newaccountcreated" event to be executed asynchronously after the event is fired ?

“newaccountcreated”事件的事件侦听器中的代码块是否可以在事件触发后异步执行?

回答by Filip Koblański

Yes of course this is possible. You should read about Laravel Queues. Every driver (only not syncdriver) are async. The easiest to configure is the databasedriver, but you can also want to try RabbitMQserver , here is Laravel bundlefor it.

是的,这当然是可能的。你应该阅读Laravel 队列。每个驱动程序(只有非同步驱动程序)都是异步的。最容易配置的是database驱动程序,但您也可以尝试使用RabbitMQ服务器,这里是Laravel 的包

You can also add to your EventListener: newaccountcreatedtrait Illuminate\Queue\InteractsWithQueue(you can read about him here) which will helps you to connect it with Laravel Queue.

您还可以添加到您的 EventListener: newaccountcreatedtrait Illuminate\Queue\InteractsWithQueue(您可以在此处阅读有关他的信息),这将帮助您将其与 Laravel 队列连接起来。

回答by user3107673

Filip's answer covers it all. I will add a bit more to it. If you push an event it will goto the default queue. You can specify a queue name as well. Have the listener class implements ShouldQueue and just include the queue method in the listener class like below.

菲利普的回答涵盖了这一切。我会再补充一点。如果您推送一个事件,它将转到默认队列。您也可以指定队列名称。让监听器类实现 ShouldQueue 并在监听器类中包含队列方法,如下所示。

/**
 * Push a new job onto the queue.
**/
public function queue($queue, $job, $data)
{
    return $queue->pushOn('queue-name', $job, $data);
}