search
HomeBackend DevelopmentPHP Tutorial队列是什么意思?

能详细的说下吗,整天听到队列,头都疼了,百度也找不到好的解释

回复内容:

首先,队列是一种数据结构,用链表和数组都可以实现,队列的特点就是先放入队列的数据先出队列。
不过看到话题标签有Redis,猜测题主想问的应该是现在很广泛使用的消息队列(MQ)。这里的消息不只是简单的文本信息,也可以是序列化后的对象。现在比较流行的开源消息队列系统有Beanstalkd,RabbitMQ,Redis(可以作为队列系统使用)等,其核心作用都是先将消息数据通过系统接口按顺序放入队列(暂存于内存),需要时再按放入的顺序依次取出以作后续处理。
就拿我前段时间做的邮件发送系统举例:
系统以HTTP协议提供服务,对外提供的主要功能是发送邮件,API地址为 /api/msg.send。使用者只要以POST请求此地址,传入subject,body,recipient这三个参数,即可发送一封邮件。


方案1: 不使用数据库,不使用队列
请求接口时,控制器直接调用sendmail或外部smtp服务器发送邮件,整个发送过程HTTP请求处于等待状态,待邮件发送完成,返回发送结果(只是调用发送程序是否成功的结果,不是邮件真正的发送结果,真正发送结果需要分析邮件日志)
这个方案最简单直接,平时发送少量邮件是可以的,但是缺点也很明显:
1. 因为接口调用时整个邮件发送过程都是同步进行的,每次请求都要等待邮件发送端完成处理,必然导致每次调用接口的等待时间增长。
2. 当系统接口并发请求较高时,系统可用性不仅受限于WebServer的处理能力,还完全受限于邮件发送端软件的处理能力,其中任一环节故障就会导致整个系统无法提供服务。
3. 若邮件发送端软件出现故障(比如SMTP连接超时),导致某次请求时邮件发送失败,那这封邮件内容便彻底丢失了,系统没有任何存留,不能实现自动重发。

方案2: 使用数据库,不使用队列
请求接口时,将要发送的邮件信息存入数据库,表结构如下:
id | subject | body | recipient | sent_at | failed_at | failed_times
然后在服务器上运行一个定时任务,每秒一次读取 sent_at=0 && failed_times
相对于方案1的提升:
1. 去掉了同步发送邮件的操作,接口请求响应会快很多
2. 邮件发送失败后可以重发,邮件不会丢失
3. 当邮件发送端完全失效后系统也可以接受邮件发送请求,待发送端恢复后可以继续发送邮件。

但还是存在缺点:
每次请求都会写一次数据库,当大并发量或者大数据量(一次请求包含100万个收件人)时,数据库负载过高影响稳定性,同时也会严重增加接口的响应时间(一下子写入100万条记录不是闹着玩的)

方案3: 数据库 + 队列

请求接口时,将要发送的邮件信息以JSON格式存入队列系统,放入的单个消息形如:
{
"subject" : "今天没吃药",
"body" : "感觉自己",
"recipient" : "mengmeng@da.com"
}

现在的队列基本上都是内存队列,数据存取非常快,一瞬间写入100万条数据再也不是难事。
随后,在服务器上运行一个常驻进程任务(Worker),实时监听队列中是否有新的消息(Job,此处指邮件信息)。当新消息进入时,从队列中取出消息,调用邮件发送端完成处理,发送成功后将此消息销毁并将消息内容插入数据库(同方案2),如果发送失败,将此消息重新放入队列,并加入一个60秒的延时标记,意味60秒后再取出处理。

这样改进后整个系统的吞吐量和响应速度将大大提升,而且同时也让系统支持了分布式运行的能力。每个Worker进程都可以视为一个处理节点,倘若把worker分散到不同的服务器上,便实现整个系统的分布式处理了,这也是队列的一个重要特性之一。

在我实际项目中还是做了许多基于方案3的改进,对于群发还使用了邮件列表和邮件模板等设计,整个系统类似Mailgun和Sendcloud的设计,等整个系统稳定下来,我会考虑将代码开源到Github。

这个例子只是队列的一个常见使用场景,一般来说在需要缓解数据库写入压力的场景下面,都可以考虑使用消息队列,还有一些需要分布式处理的情况下,也是队列很好的使用场景。

现在大部分语言都有成熟的消息队列处理组件,可以很方便的使用各种队列系统,比如我常用的
Laravel 便原生支持了 Beanstalkd,Amazon SQS,IronMQ,Redis。

抱砖引玉,不足之处请指正,谢谢。 排队听说过吧?先来的站前面(队首),后来的跟在后面(队尾),出队的时候从队首出,入队的跟在队尾,这就是队列!至于实现,链表和数组都行!
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

PHP Logging: Best Practices for PHP Log AnalysisPHP Logging: Best Practices for PHP Log AnalysisMar 10, 2025 pm 02:32 PM

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Explain the concept of late static binding in PHP.Explain the concept of late static binding in PHP.Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Customizing/Extending Frameworks: How to add custom functionality.Customizing/Extending Frameworks: How to add custom functionality.Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor