天天看点

php消息队列发送邮件,Laravel消息队列异步执行-发送邮件

0x01 配置

1、修改.env,我这里是采用的数据库,一般是用的异步服务器或者redis。我这里只是用作测试QUEUE_DRIVER=database

2、添加数据库,执行php artisan queue:table

php artisan queue:failed-table

php artisan migrate

3、创建队列任务,我这里使用的是发送邮件的例子php artisan make:job SendReminderEmail

0x02 控制器use Mail;

use App\Jobs\SendReminderEmail;

public function email()

{

$datas = \DB::table('data_email')->get();

foreach($datas as $data){

dispatch(new SendReminderEmail($data->name,$data->email));

}

return redirect('/users');

}

0x03 队列文件

编辑队列文件SendReminderEmail.php<?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 Mail;

class SendReminderEmail implements ShouldQueue

{

use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

protected $name;

protected $email;

public function __construct($name, $email)

{

$this->name = $name;

$this->email = $email;

}

public function handle()

{

// 如果参试大于三次

if ($this->attempts() > 3) {

\Log::info($this->name.'邮件参试失败过多');

}else{

// 每次进来休息3秒钟

sleep(3);

$flag = Mail::send('emails.test',['name'=>$this->name],function($message){

$message ->to($this->email)->subject('邮件测试');

});

echo $this->name;

if($flag){

\Log::info($this->name.'邮件发送成功');

}else{

\Log::info($this->name.'邮件发送失败');

}

}

}

public function failed()

{

\Log::error($this->name.'队列任务执行失败'."\n".date('Y-m-d H:i:s'));

}

}

0x04 开始并查看记录

在网站根目录执行,开始监听:php artisan queue:listen

查看storage/logs/laravel.log[2017-05-14 02:06:25] local.INFO: 亲6邮件发送成功

[2017-05-14 02:06:30] local.INFO: 亲7邮件发送成功

[2017-05-14 02:06:35] local.INFO: 亲1邮件发送成功

[2017-05-14 02:06:40] local.INFO: 亲2邮件发送成功

[2017-05-14 02:06:45] local.INFO: 亲3邮件发送成功

[2017-05-14 02:06:50] local.INFO: 亲4邮件发送成功

[2017-05-14 02:06:55] local.INFO: 亲5邮件发送成功

测试成功。。。。