laravel5.6 基于redis,使用消息队列(邮件推送)


邮件发送如何配置参考:https://www.cnblogs.com/clubs/p/10640682.html

用到的用户表:

 1 CREATE TABLE `recruit_users` (
 2   `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
 3   `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
 4   `phone` varchar(50) CHARACTER SET utf8 DEFAULT NULL COMMENT '手机号码',
 5   `email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
 6   `password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
 7   `remember_token` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
 8   `status` tinyint(4) DEFAULT '1' COMMENT '帐户状态(0失效 1正常)',
 9   `created_at` timestamp NULL DEFAULT NULL,
10   `updated_at` timestamp NULL DEFAULT NULL,
11   `lastlogintime` timestamp NULL DEFAULT NULL COMMENT '最后登陆时间',
12   PRIMARY KEY (`id`)
13 ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

1.在 Laravel 中使用 Redis 你需用通过 Composer 来安装 predis/predis 包文件,不然会报错Class 'Predis\Client' not found

composer require predis/predis ^1.1

2. laravel队列配置(配置文件 .env 和 config/queue.php)

优先配置.env 文件如下:

1 QUEUE_DRIVER=redis
2 
3 REDIS_HOST=127.0.0.1
4 REDIS_PASSWORD=******
5 REDIS_PORT=6379

当.env 文件没有配置 或者 设置变量为空时,会按照 config/queue.php 文件的配置信息运行laravel,一般只配置.env文件,不修改queue.php文件
config/queue.php 文件如下:

 1 return [
 2     'default' => env('QUEUE_DRIVER', 'redis'),//修改队列驱动,使用redis
 3 
 4     'connections' => [
 5         'sync' => [
 6             'driver' => 'sync',
 7         ],
 8 
 9         'database' => [
10             'driver' => 'database',
11             'table' => 'jobs',
12             'queue' => 'default',
13             'retry_after' => 90,
14         ],
15 
16         'beanstalkd' => [
17             'driver' => 'beanstalkd',
18             'host' => 'localhost',
19             'queue' => 'default',
20             'retry_after' => 90,
21         ],
22 
23         'sqs' => [
24             'driver' => 'sqs',
25             'key' => env('SQS_KEY', 'your-public-key'),
26             'secret' => env('SQS_SECRET', 'your-secret-key'),
27             'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'),
28             'queue' => env('SQS_QUEUE', 'your-queue-name'),
29             'region' => env('SQS_REGION', 'us-east-1'),
30         ],
31 
32         'redis' => [
33             'driver' => 'redis',
34             'connection' => 'default',
35             'queue' => 'default',
36             'retry_after' => 90,
37             'block_for' => null,
38         ],
39     ],
40 
41     'failed' => [
42         'database' => env('DB_CONNECTION', 'mysql'),//队列执行失败 存放的数据库
43         'table' => 'failed_jobs',//队列执行失败 存放的表
44     ],
45 ];

Redis 在应用中的配置文件存储在 config/database.php,在这个文件中,你可以看到一个包含了 Redis 服务信息的 redis 数组:

1 'redis' => [
2     'client' => 'predis',
3     'default' => [
4         'host' => env('REDIS_HOST', '127.0.0.1'),
5         'password' => env('REDIS_PASSWORD', null),
6         'port' => env('REDIS_PORT', 6379),
7         'database' => 0,//选择使用的redis库
8     ],
9 ],

3. 创建队列任务类(app/Jobs/xxx.php)

使用artisan命令 在app/Jobs 目录下创建执行队列任务的类:
php artisan make:job SendEmail
app/Jobs/SendEmail.php 代码如下:

 1 <?php
 2 
 3 namespace App\Jobs;
 4 
 5 use Illuminate\Bus\Queueable;
 6 use Illuminate\Queue\SerializesModels;
 7 use Illuminate\Queue\InteractsWithQueue;
 8 use Illuminate\Contracts\Queue\ShouldQueue;
 9 use Illuminate\Foundation\Bus\Dispatchable;
10 use Illuminate\Support\Facades\Mail;
11 use App\Models\RecruitUser as User;
12 
13 class SendEmail implements ShouldQueue
14 {
15     use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
16 
17     protected $user;
18 
19     /**
20      * Create a new job instance.
21      *
22      * @return void
23      */
24     public function __construct(User $user)
25     {
26         $this->user = $user;
27     }
28 
29     /**
30      * Execute the job.
31      *
32      * @return void
33      */
34     public function handle()
35     {
36         $user = $this->user;
37         Mail::raw('这里填写邮件的内容', function ($message) {
38             // 收件人的邮箱地址
39             $message->to($this->user->email);
40             // 邮件主题
41             $message->subject('队列发送邮件');
42         });
43     }
44 }

4. 控制器将数据添加到队列中

 1 <?php
 2 
 3 namespace App\Http\Controllers\Home;
 4 
 5 use App\Jobs\SendEmail;
 6 use App\Http\Controllers\Controller;
 7 use Illuminate\Http\Request;
 8 use App\Models\RecruitUser as User;
 9 
10 class MessageController extends Controller
11 {
12     public function index()
13     {
14         $user = User::find(2);
15         $res = $this->dispatch(new SendEmail($user));
16         dd($res);
17     }
18 }

5. 启动、监听队列

5.1 php artisan queue:work —queue=sendEmail
指定启动sendEmail队列

5.2 php artisan queue:restart
重启队列

5.3 php artisan queue:work —timeout=60
队列进程 queue:work 可以设定超时 —timeout 项。该 —timeout 控制队列进程执行每个任务的最长时间,如果超时,该进程将被关闭。
注:参数项 —timeout 的值应该始终小于配置项 retry_after 的值,这是为了确保队列进程总在任务重试以前关闭。如果 —timeout 比retry_after 大,那么你的任务可能被执行两次。

5.4 php artisan queue:work —sleep=3
休眠时间,每执行一个任务后休眠3秒

 

监听三种情况:

 queue:work 默认只执行一次队列请求, 当请求执行完成后就终止;

 queue:listen 监听队列请求,只要运行着,就能一直接受请求,除非手动终止;

 queue:work --daemon 同listen一样,不同的是work不需要再次加载框架,直接运行任务,一般推荐使用这个来处理队列监听。

 注意: 使用 queue:work —daemon , 当更新代码的时候, 需要停止, 然后重新启动, 这样才能把修改的代码应用上

6. 设置API路由,执行请求,执行队列任务

1 Route::post('messageindex', ['uses' => $namespaces . 'MessageController@index', 'as' => 'messageIndex']);

使用postman发送post请求即可以测试发送邮件队列

 

 查看redis是否有队列数据

 

命令行监听界面:

 

查看邮箱发件箱,邮件已发出

7. 使用Supervisor将队列任务启动 添加到守护进程中

推荐安装Supervisor,将 php artisan queue:work —queue sendEmail 等一系列队列进程,添加到进程保护中,防止中途崩溃时候,可以自救,哈哈~😄
关于Supervisor,可以参考《centos安装Supervisor以及简单配置(添加进程守护)

总结

  1. 引入 predis/predis 包
  2. laravel队列配置(配置文件 .env 和 config/queue.php)
  3. 创建队列任务类(app/Jobs/xxx.php)
  4. 控制器将数据添加到队列中
  5. 启动、监听队列
  6. 设置API路由,执行请求,执行队列任务
  7. 使用Supervisor将队列任务启动 添加到守护进程中


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM