Home Backend Development PHP Tutorial How to trigger the background asynchronous batch sending of SMS messages in the foreground without affecting the user experience?

How to trigger the background asynchronous batch sending of SMS messages in the foreground without affecting the user experience?

Mar 31, 2025 pm 11:45 PM
redis red talk

This article introduces how to enable the front-end to trigger the background to send text messages in batches without affecting the user experience. After the user clicks the button, the front desk immediately returns the success prompt, and the back desk performs database query, Redis cache write and SMS sending asynchronously.

How to trigger the background asynchronous batch sending of SMS messages in the foreground without affecting the user experience?

Core idea: asynchronous processing

This solution uses an asynchronous processing mechanism to move time-consuming operations to the background to perform, avoiding blocking the foreground. The specific steps are as follows:

  1. Front-end Ajax request: The user clicks the send button, and the front-end uses Ajax to send a request to the background. The request parameters include the SMS template ID, mobile phone number list and SMS content.

     $.ajax({
        url: '/send-sms',
        type: 'POST',
        data: { template_id: 123, mobiles: ['13800138000', '13800138001'], content: 'Test SMS' },
        success: function(response) {
            alert('SMS send request has been submitted');
        },
        error: function(error) {
            alert('Request failed:' error.responseText);
        }
    });
    Copy after login
  2. The background receives the request and returns the response: After the background receives the Ajax request, it immediately returns a successful response (JSON format) to inform the front-end that the request has been received. The key is that the SMS sending logic is put into an asynchronous task.

     // Background controller method public function sendSmsAction() {
        $templateId = $_POST['template_id'];
        $mobiles = $_POST['mobiles'];
        $content = $_POST['content'];
    
        // Return the successful response immediately echo json_encode(['success' => true, 'message' => 'Request received, SMS sending task started']);
    
        // Add tasks to queues (for example using Redis or RabbitMQ)
        $this->addTaskToQueue($templateId, $mobiles, $content);
    }
    Copy after login
  3. Asynchronous task processing: addTaskToQueue method adds SMS sending task to the message queue. An independent background process (for example, using queue workers) continuously listens to the queue, fetches tasks and executes them.

     // Add tasks to queue (example using Redis)
    private function addTaskToQueue($templateId, $mobiles, $content) {
        $redis = new Redis();
        $redis->connect('127.0.0.1', 6379);
        $redis->lPush('sms_queue', json_encode(['template_id' => $templateId, 'mobiles' => $mobiles, 'content' => $content]));
    }
    Copy after login
  4. Queue Worker: Queue Worker obtains tasks from the sms_queue queue, performs SMS sending, and processes error logs.

     // Queue Worker (Example)
    while (true) {
        $task = $redis->rPop('sms_queue');
        if ($task) {
            $data = json_decode($task, true);
            $result = $this->sendSms($data['template_id'], $data['mobiles'], $data['content']);
            if ($result !== true) {
                // Log error_log("SMS send failed: " . $result);
            }
        }
        sleep(1); // Avoid excessive CPU usage}
    Copy after login
  5. SMS send function ( sendSms ) : This function calls the SMS service provider API to send SMS messages.

Through the above steps, the front-end user experience will not be affected, and the back-end will efficiently process batch SMS sending. Choosing the right queue system (Redis, RabbitMQ, Beanstalkd, etc.) is crucial, which ensures that tasks are processed reliably and supports distributed environments. In addition, a complete error handling and logging mechanism is also essential.

The above is the detailed content of How to trigger the background asynchronous batch sending of SMS messages in the foreground without affecting the user experience?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
Using Dicr/Yii2-Google to integrate Google API in YII2 Using Dicr/Yii2-Google to integrate Google API in YII2 Apr 18, 2025 am 11:54 AM

VprocesserazrabotkiveB-enclosed, Мнепришлостольностьсясзадачейтерациигооглапидляпапакробоглесхетсigootrive. LEAVALLYSUMBALLANCEFRIABLANCEFAUMDOPTOMATIFICATION, ČtookazaLovnetakProsto, Kakaožidal.Posenesko

How to use the Redis cache solution to efficiently realize the requirements of product ranking list? How to use the Redis cache solution to efficiently realize the requirements of product ranking list? Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

Redis's Role: Exploring the Data Storage and Management Capabilities Redis's Role: Exploring the Data Storage and Management Capabilities Apr 22, 2025 am 12:10 AM

Redis plays a key role in data storage and management, and has become the core of modern applications through its multiple data structures and persistence mechanisms. 1) Redis supports data structures such as strings, lists, collections, ordered collections and hash tables, and is suitable for cache and complex business logic. 2) Through two persistence methods, RDB and AOF, Redis ensures reliable storage and rapid recovery of data.

What should I do if the Redis cache of OAuth2Authorization object fails in Spring Boot? What should I do if the Redis cache of OAuth2Authorization object fails in Spring Boot? Apr 19, 2025 pm 08:03 PM

In SpringBoot, use Redis to cache OAuth2Authorization object. In SpringBoot application, use SpringSecurityOAuth2AuthorizationServer...

Laravel8 optimization points Laravel8 optimization points Apr 18, 2025 pm 12:24 PM

Laravel 8 provides the following options for performance optimization: Cache configuration: Use Redis to cache drivers, cache facades, cache views, and page snippets. Database optimization: establish indexing, use query scope, and use Eloquent relationships. JavaScript and CSS optimization: Use version control, merge and shrink assets, use CDN. Code optimization: Use Composer installation package, use Laravel helper functions, and follow PSR standards. Monitoring and analysis: Use Laravel Scout, use Telescope, monitor application metrics.

Title: How to use Composer to solve distributed locking problems Title: How to use Composer to solve distributed locking problems Apr 18, 2025 am 08:39 AM

Summary Description: Distributed locking is a key tool for ensuring data consistency when developing high concurrency applications. This article will start from a practical case and introduce in detail how to use Composer to install and use the dino-ma/distributed-lock library to solve the distributed lock problem and ensure the security and efficiency of the system.

Use Composer to simplify PHP project development: Practical application of pxniu/study library Use Composer to simplify PHP project development: Practical application of pxniu/study library Apr 18, 2025 am 11:06 AM

When developing PHP projects, we often encounter requirements such as frequent operation of databases, management of transactions, and dependency injection. If written manually, these operations are not only time-consuming and labor-intensive, but also prone to errors. Recently, I have encountered similar troubles in my projects, and handling these operations has become extremely complex and difficult to maintain. Fortunately, I found a Composer library called pxniu/study, which greatly simplified my development process. Composer can be learned through the following address: Learning address

What is the reason why the browser does not respond after the WebSocket server returns 401? How to solve it? What is the reason why the browser does not respond after the WebSocket server returns 401? How to solve it? Apr 19, 2025 pm 02:21 PM

The browser's unresponsive method after the WebSocket server returns 401. When using Netty to develop a WebSocket server, you often encounter the need to verify the token. �...

See all articles