首页 > 其他 > 详细

laraval 实现消息队列

时间:2015-11-30 19:48:19      阅读:241      评论:0      收藏:0      [点我收藏+]

以 发送邮件,借助redis 做队列为例

 

1、app/Commands 文件夹建立 EmailQunene.php

namespace App\Commands;

use App\Commands\Command;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Contracts\Queue\ShouldQueue;

class EmailQuneue implements SelfHandling, ShouldQueue
{
    use InteractsWithQueue, SerializesModels;
    public $from;  //用成员属性接收需要参数
    public $to;
    public $message;
    public function __construct($arr)
    {
        $this->from = $arr[‘from‘];
        $this->to = $arr[‘to‘];
        $this->message = $arr[‘message‘];
    }
    public function handle()
    {
        echo "\n".$this->from.‘ send email to ‘.$this->to.‘ message:‘.$this->message;
    }
}

  

 

2、controller中实例化 队列类

//引入Queue 和消费类
use Queue;
use App\Commands\EmailQuneue;

//代码片段

$arr[‘from‘] = ‘a@qq.com’;
$arr[‘to‘] = ‘b@qq.com‘;
$arr[‘message‘] = ‘hello‘;
$messages = new EmailQuneue($arr);
Queue::pushOn(‘emailqueue‘,$messages); //消息push 进队列

  

3、监听队列,调用消费端

php artisan queue:listen --queue=emailqueue —tries=1

php artisan queue:work --queue=emailqueue  --daemon --sleep=1 --tries=1 守护进程模式,出错不会重试,存入数据库

listen 监听消费类动态加载,文件改变随时更新

work 开启守护进程加载消费类,文件修改,需要kill 掉进程重新开启

work 相对 listen 更节省cpu

 

4、push  queue 方法

pushOn($queue, $job, $data = ‘‘)  push进指定队列

laterOn($queue, $delay, $job, $data = ‘‘)  指定delay 时间后消费

laraval 实现消息队列

原文:http://www.cnblogs.com/loyal1986/p/5007784.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!