以 发送邮件,借助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 时间后消费