


What should you pay attention to when using message queue in Laravel?
本文主要给大家介绍了关于Laravel使用消息队列需要注意的一些问题,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,希望能帮助到大家。
前言
消息队列对于大型的Web项目来说是必不可少的一个模块,通过消息队列可以解决大并发和多种语言通信接口等问题。对于大并发的问题,可以将耗时的任务或者不能同时大量并行的任务封装起来传输到消息队列中,由处理程序不断从消息队列中提取消息并进行处理,这样通过消息队列的缓冲可以使得在大并发情况下不再阻塞,如果性能不够用还可以添加多个处理任务从消息队列中获取消息进行处理。比如数据库的操作,当对数据库的读、写操作过多时就会存在锁表等问题,读的问题可以通过缓存等方案解决,写的问题就需要消息队列来解决。而且,在大型的Web项目开发中,很多情况下不可能通过一种语言实现,需要发挥不同语言的优势,比如PHP,虽然在理论意义上它可以做Web开发中的所有事情,但是有些问题用它解决效率将会非常低,比如实时socket连接和分布式事务处理等。
使用 Laravel 的消息队列处理异步任务,Redis 作为队列数据库,Supervisor 监控脚本异常中断并自动重启,这是 Laravel 处理队列任务的标准流程,但是实际中可能还会出现各种各样的问题,为了保证系统可靠性,还要注意几个问题。
一、执行失败重试次数设置
一定要设置任务执行失败重试次数,避免无限失败重试,超过重试次数 Laravel 会默认写到失败任务表中,也可以自己写执行失败后续处理逻辑。
php artisan queue:work redis --tries=3
需要先执行以下命令创建数据表:
php artisan queue:failed-table php artisan migrate
二、程序异常的处理
有时候程序执行过程会发生异常,比如依赖其他接口,请求 HTTP 接口超时等等,如果不捕捉异常,那么当前这个队列就会中断不能继续运行下去,比如给 10000 个用户推送内容,需要依赖接口推送,如果中间的请求挂了就会影响到后面的推送。
这里的异常是指程序执行过程中发生的异常,不是指常驻进程挂掉,程序异常不一定导致常驻进程中断,况且进程中断有 Supervisor 监控并重启。
如捕获异常代码片段:
try { $r = $client->request('POST', '', [ 'query' => [ 'client_name' => 'filemail', 'client_version' => '1.0', 'client_sequence' => 0, 'uid' => 692934013,//119481237 'r' => 1508312484, ], 'body' => \GuzzleHttp\json_encode($body), ]); $result = $r->getBody()->getContents(); $result = json_decode($result, true); if ($result['result'] == 0) { info("sendMail fail:" . json_encode($result)); $this->pushLog($task['id'], $task['mail_id'], implode(',', $userIds), json_encode($result), 0); } else { Log::warning("sendMail fail:" . json_encode($result)); $this->pushLog($task['id'], $task['mail_id'], implode(',', $userIds), json_encode($result), $result['result']); } } catch (RequestException $e) { Log::warning('RequestException' . $e->getMessage()); } catch (Exception $e) { Log::emergency('Exception' . $e->getMessage()); }
三、修改代码记得重启 Supervisor
最后一点,修改了处理队列的程序,记得要重启 Supervisor,否则脚本不会生效。
Laravel 往 Redis 写队列的数据结构
队列用 list 类型存储,如图:
value 内容如下:
{ "job": "Illuminate\\Queue\\CallQueuedHandler@call", "data": { "commandName": "App\\Jobs\\SendFile", "command": "O:17:\"App\\Jobs\\SendFile\":5:{s:23:\"\u0000App\\Jobs\\SendFile\u0000task\";a:8:{s:5:\"title\";s:4:\"1111\";s:4:\"note\";s:2:\"11\";s:6:\"reward\";s:0:\"\";s:7:\"mail_id\";s:5:\"66681\";s:4:\"nums\";i:20;s:8:\"uid_file\";s:33:\"uidfile\/file-66681-1513058185.txt\";s:5:\"gcids\";s:40:\"1B9DD95645AAE8119F7DA9B9FF738D52BC8A1BD5\";s:2:\"id\";i:29;}s:6:\"\u0000*\u0000job\";N;s:10:\"connection\";N;s:5:\"queue\";s:8:\"sendfile\";s:5:\"delay\";N;}" }, "id": "l0mjsUthbxm4TgIJNUH13km9N8DIpErK", "attempts": 1 }
包含失败重试次数,队列标识,处理队列的类,以及队列的数据等等。
相关推荐:
The above is the detailed content of What should you pay attention to when using message queue in Laravel?. For more information, please follow other related articles on the PHP Chinese website!

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 Linux new version
SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver CS6
Visual web development tools