In software development, delayed message sending is a common requirement, such as sending SMS verification codes or system notifications. Using PHP queues can effectively achieve delayed sending by placing messages into a queue with a specified delay time, enabling asynchronous processing. This article introduces a solution using Redis as the queue server along with complete PHP example code to help you get started quickly.
Redis is a high-performance in-memory database that supports various data structures including lists and sorted sets, making it suitable for use as a message queue. First, install Redis and the corresponding PHP extension. On Ubuntu, use the following commands:
sudo apt-get install redis-server sudo apt-get install php-redis
After installation, the following code demonstrates how to connect to the Redis server:
$redis = new Redis(); $redis->connect('127.0.0.1', 6379);
The following example shows how to add messages to the Redis queue with a delay time, and continuously check and send messages that are due:
// Add message to the queue with delay time (seconds) function addDelayedMessage($message, $delay) { global $redis; // Calculate the message sending timestamp $delayedTime = time() + $delay; // Add message to the sorted set with score as the sending time $redis->zAdd('delayed_queue', $delayedTime, $message); } // Check and send messages that are due function checkDelayedMessages() { global $redis; while (true) { // Get messages with score less than or equal to current time $message = $redis->zRangeByScore('delayed_queue', 0, time(), ['limit' => [0, 1]]); if (count($message) > 0) { // Simulate sending the message by echoing it echo "Sending message: " . $message[0] . PHP_EOL; // Remove the sent message from the queue $redis->zRem('delayed_queue', $message[0]); } else { // No messages to send, break the loop break; } } } // Add sample delayed messages addDelayedMessage('Message 1', 300); // Send after 5 minutes addDelayedMessage('Message 2', 600); // Send after 10 minutes // Perform sending check checkDelayedMessages();
In the code above, the addDelayedMessage function adds messages to a Redis sorted set, with scores representing future timestamps (delays), thus implementing the delay feature. The checkDelayedMessages function continuously checks for messages whose scheduled time has arrived, simulates sending them, and removes them from the queue to avoid duplicate sends.
Combining PHP with Redis queues provides an efficient way to handle delayed message sending requirements. Redis sorted sets offer a convenient way to manage time-ordered messages, making delay handling straightforward. Mastering this method significantly enhances your system’s asynchronous processing capability and performance.