Laravel异步队列全攻略
最近项目需求,研究了laravel的异步队列。官方文档虽然很是详细,但也有些晦涩难懂,在此记录下步骤,供大家参考。
1、修改/config/queue.php文件
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Queue Connection Name
|--------------------------------------------------------------------------
|
| Laravel's queue API supports an assortment of back-ends via a single
| API, giving you convenient access to each back-end using the same
| syntax for every one. Here you may define a default connection.
|
*/
'default' => env('QUEUE_CONNECTION', 'sync'),
/*
|--------------------------------------------------------------------------
| Queue Connections
|--------------------------------------------------------------------------
|
| Here you may configure the connection information for each server that
| is used by your application. A default configuration has been added
| for each back-end shipped with Laravel. You are free to add more.
|
| Drivers: "sync", "database", "beanstalkd", "sqs", "redis", "null"
|
*/
'connections' => [
'sync' => [
'driver' => 'sync',
],
'database' => [
'driver' => 'database',
'table' => 'jobs',
'queue' => 'default',
'retry_after' => 90,
],
'beanstalkd' => [
'driver' => 'beanstalkd',
'host' => 'localhost',
'queue' => 'default',
'retry_after' => 90,
'block_for' => 0,
],
'sqs' => [
'driver' => 'sqs',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'),
'queue' => env('SQS_QUEUE', 'your-queue-name'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
],
'redis' => [
'driver' => 'redis',
'connection' => 'default',
'queue' => env('REDIS_QUEUE', 'default'),
'retry_after' => 90,
'block_for' => null,
],
],
/*
|--------------------------------------------------------------------------
| Failed Queue Jobs
|--------------------------------------------------------------------------
|
| These options configure the behavior of failed queue job logging so you
| can control which database and table are used to store the jobs that
| have failed. You may change them to any database / table you wish.
|
*/
'failed' => [
'database' => env('DB_CONNECTION', 'mysql'),
'table' => 'failed_jobs',
],
];
注意:修改.env文件如下参数,设置队列连接默认为数据库连接
QUEUE_CONNECTION=database
2、新建/app/Job/EmailJob.php,此文件为队列主文件
<?php
namespace App\Job;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use App\Service\EmailService;
class EmailJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
private $content,$to;
public function __construct($content,$to){
$this->content=$content;
$this->to=$to;
}
public function handle(){
$res=false;
$times=0;
while($res!==true && $times<3){
try{
$times++;
$res=EmailService::send($this->content,$this->to);
}catch (\Exception $e){
Log::error(date('Y-m-d h:i:s',time()).' send email error:'.$e->getMessage());
}
}
if($res===true){
Log::info(date('Y-m-d h:i:s',time()).' send email success:');
}
}
}
3、新建/app/Service/EmailJobService.php服务,此文件为封装服务文件,可以不用,直接在使用的地方调用队列。
<?php
namespace App\Service;
use App\Job\EmailJob;
class EmailJobService
{
public static function add($content,$to){
$job=new EmailJob($content,$to);
dispatch($job);
}
}
4、打开终端切换目录进入Laravel项目根目录,执行如下命令,创建队列任务需要的数据表。
php artisan queue:table php artisan queue:failed-table php artisan migrate
5、通过下面这条指令启动队列监听服务,它会自动处理 jobs 表中的队列任务。
php artisan queue:listen
监听指定队列:
php artisan queue:work --queue=default,mytask --tries=2
这是监听 default和mytask两个队列,区分先后顺序。
6、如果需要在linux中后台运行,有两种方法:
6.1 执行如下命令:
nohup php artisan queue:listen > /tmp/artisan.log 2>&1 &
6.2.1 安装Supervisor,我的服务器系统为CentOs7.5,所以使用yum安装。
yum install supervisor
6.2.2 在/etc/supervisord.d下新建ini文件,eg:laraver-worker.ini,设置自动运行命令等相关参数
[program:laravel-worker] process_name=%(program_name)s_%(process_num)02d command=php 这里需要写项目目录/artisan queue:work --sleep= --tries= autostart=true autorestart=true user=root numprocs= stdout_logfile=/root/queue/daily_english_queue.log
6.2.3 启动supervisor,laravel队列监听进程便在后台运行了。
supervisord -c /etc/supervisord.conf
6.2.4 配置supervisor开机启动(否则服务器重启后必须手动启动supervisor)
cd /usr/lib/systemd/system/ //切换目录
touch supervisord.service //新建文件
vim supervisord.service //编辑文件
文件内容:
[Unit]
Description=Supervisor daemon [Service]
Type=forking
ExecStart=/usr/bin/supervisord -c /etc/supervisor/supervisord.conf
ExecStop=/usr/bin/supervisorctl shutdown
ExecReload=/usr/bin/supervisorctl reload
KillMode=process
Restart=on-failure
RestartSec=42s [Install]
WantedBy=multi-user.target
设置开机启动
systemctl enable supervisord
验证是否设置成功
systemctl is-enabled supervisord
7、注意:如果修改了job内的代码(包括job调用的方法类),需要重启queue。
php artisan queue:restart
Enjoy it !
Laravel异步队列全攻略的更多相关文章
- JavaScript 异步开发全攻略(转)
写了一本介绍 JavaScript 异步开发的小书: https://meathill.gitbooks.io/javascript-async-tutorial/content/ 除了比较详细的介绍 ...
- Windows Socket五种I/O模型——代码全攻略(转)
Winsock 的I/O操作: 1. 两种I/O模式 阻塞模式:执行I/O操作完成前会一直进行等待,不会将控制权交给程序.套接字 默认为阻塞模式.可以通过多线程技术进行处理. 非阻塞模式:执行I/O操 ...
- 【C#代码实战】群蚁算法理论与实践全攻略——旅行商等路径优化问题的新方法
若干年前读研的时候,学院有一个教授,专门做群蚁算法的,很厉害,偶尔了解了一点点.感觉也是生物智能的一个体现,和遗传算法.神经网络有异曲同工之妙.只不过当时没有实际需求学习,所以没去研究.最近有一个这样 ...
- 【转】轻松搞定FTP之FlashFxp全攻略
转载网址:http://www.newhua.com/2008/0603/39163.shtml 轻松搞定FTP之FlashFxp全攻略 导读: FlashFXP是一款功能强大的FXP/FTP软件,融 ...
- 谈谈Vue.js——vue-resource全攻略
本篇文章主要介绍了谈谈Vue.js——vue-resource全攻略,小编觉得挺不错的,现在分享给大家,也给大家做个参考.一起跟随小编过来看看吧 概述 上一篇我们介绍了如何将$.ajax和Vue. ...
- 生成 PDF 全攻略【2】在已有PDF上添加内容
项目在变,需求在变,不变的永远是敲击键盘的程序员..... PDF 生成后,有时候需要在PDF上面添加一些其他的内容,比如文字,图片.... 经历几次失败的尝试,终于获取到了正确的代码书写方式. 在此 ...
- 从小工到专家 ——读《Java程序员职场全攻略》有感
从小工到专家 ——读<Java程序员职场全攻略>有感 <Java程序员职场全攻略>是以故事的形式,向读者介绍Java程序员的职场经验.作者牛开复在北京从事软件开发,已经是一 ...
- Android屏幕适配全攻略 (转载)
http://blog.csdn.net/jdsjlzx/article/details/45891551 https://github.com/hongyangAndroid/AndroidAuto ...
- Moon.Orm3.8技术全攻略
Moon.ORM技术全攻略 一.绪论 本文主要是针对Moon.ORM的技术的讨论及其使用使用指导.如有其它疑问,请留言.本文主要针对Moon.ORM3.9版本,同时将会对4.0做一个技术预览.本文从 ...
随机推荐
- 一夜搞懂 | JVM GC&内存分配
前言 本文已经收录到我的Github个人博客,欢迎大佬们光临寒舍: 我的GIthub博客 学习导图 一.为什么要学习GC&内存分配? 时代发展到现在,如今的内存动态分配与内存回收技术已经相当成 ...
- React入门(1)
今天继续来学习react 首先,先写几个小demo来感受一下什么是react,以及react的语法规则,来建立对react的一个总体认识 上demo: demo01: demo01涉及的知识点有: 1 ...
- HDU - 1962 二分图最大匹配模板(扑克牌得分最大)
题意: 直接说数据,第一行给定几组数据,每一组数据的第一行是两个人扑克牌分别的数量,第一行是亚当的扑克牌,第二行是夏娃的扑克牌,每一个扑克牌的大小用两个字符来表示,第一个表示是几号扑克牌,第二个表示扑 ...
- JavaScript的URLSearchParams方法
URLSearchParams 接口定义了一些实用的方法来处理 URL 的查询字符串. 一个实现了 URLSearchParams 的对象可以直接用在 for…of 结构中,不需要使用 entries ...
- [noip模拟]种花<快速幂+结论>
描述: OI太可怕了,我决定回家种田.我在后院里开辟了一块圆形的花圃,准备种花.种花是一种艺术,通过一定技术手法,花材的排列组合会让花变得更加的赏心悦目,这就是花艺.当然你知道,我在种田之前是OIer ...
- [noip模拟]画展<队列的基础知识>
Description 博览馆正在展出由世上最佳的M位画家所画的图画.人们想到博览馆去看这几位大师的作品.可是,那里的博览馆有一个很奇怪的规定,就是在购买门票时必须说明两个数字,a和b,代表要看展览中 ...
- Activiti网关--排他网关
排他网关 1.什么是排他网关 排他网关(也叫异或(XOR)网关,或叫基于数据的排他网关),用来在流程中实现决策. 当流程执行到这个网关,所有分支都会判断条件是否为true,如果为 true 则执行该分 ...
- .NET(C#)实现桌面背景切换(控制台应用程序,windows服务版的未实现成功)
AdvancedBackgroundJimmy.Program.cs using AdvancedBackground; using Microsoft.Win32; using System; us ...
- linux 之虚拟机的安装与介绍
linux 零基础入门1.1linux介绍 操作系统用途: 管理硬件 驱动硬件 管理软件 分配资源1.2 linux的发展unix -> windows ->linuxlinux 免费 开 ...
- 1018 Public Bike Management (30 分)
There is a public bike service in Hangzhou City which provides great convenience to the tourists fro ...