Method Analysis of PHP+MySQL Implementation of Message Queue
- 2021-10-11 17:45:15
- OfStack
In this paper, the method of realizing message queue by PHP+MySQL is described as an example. Share it for your reference, as follows:
Recently, I encountered a demand for sending short messages in batches, and the short message interface was provided by the third party. At first, it occurred to me that after getting the mobile phone number, it is ok to call the interface circularly and send it.
However, the problem was soon discovered: when the number of short messages is large, it is not only time-consuming, but also has a low success rate.
So I thought of using PHP and MySQL to realize a message queue and send short messages one by one. The specific implementation method is introduced below:
First, create a data table sms with the following fields:
id,
phone,//Mobile phone number
content//SMS content
Save the short message and mobile phone number to be sent in sms table.
Next, you need to use PHP to implement a timer, read a record regularly, and send a short message:
<?php
$db = new Db();
$sms = new Sms();
while(true){
$item = $db->getFirstRecord(); // Get the data table 1 A record
if(!$item){
// End the timer if there is no data in the queue
break;
}
$res = $sms->send($item['phone'],$item['content']); // Send a text message
if($res){
$db->deleteFristRecord(); // Delete the record of successful sending
echo $item['phone'].' Send successful ';
}else{
echo $item['phone'].' Send failed, try again later ' ;
}
sleep(10); // Every interval 10 Second cycle 1 Times
}
echo ' Send out! ';
?>
Save the code as timer_sms. php, open the command line, and execute the timer:
php timer_sms.php
Ok, the php timer will automatically complete the task of sending short messages according to the set time interval (set here is 10 seconds). After the task is completed, it will automatically exit the timer and no longer occupy server resources.
According to my tests, the PHP timer does not consume much resources and does not put pressure on the server. Moreover, it accesses the database asynchronously and will not affect the operation of the database.
The advantages of this approach are:
1. Running in the background, the foreground does not need to wait
2. The success rate is high, and the failure record will be automatically resent until it succeeds
For more readers interested in PHP related contents, please check the topics on this site: "Introduction to php+mysql Database Operation", "Summary of php+mysqli Database Programming Skills", "Introduction to php Object-Oriented Programming", "Encyclopedia of PHP Array (Array) Operation Skills", "Summary of php String (string) Usage" and "Summary of php Common Database Operation Skills"
I hope this article is helpful to everyone's PHP programming.