PHP can use GO or not
Queue usage scenario, massive user information push, massive blessing SMS sending, etc
Core technology point: Redis's lpush brpop
- lpush is responsible for writing data to the key
- brpop blocking mode obtains the value in the key to realize the service
Simulate an instance. Send SMS to users
PHP version code
Producer
<?php /** * Created by PhpStorm. * User: smallForest<1032817724@qq.com> * Date: 2019-12-02 * Time: 11:11 */ ini_set('default_socket_timeout', -1); //No timeout // Declared object $redis = new \Redis(); // Connect Redis $r = $redis->connect('127.0.0.1', 6379); // Select Redis DB $redis->select(4); // Declare the key of SMS queue $key = 'SMS_QUEUE'; //Write data for ($i = 0; $i < 10; $i++) { // Get random mobile number $m = randomPhoneNumber(); // Left queue $redis->lPush($key, $m); // Sometimes it is better to set the text content separately for different users. Note that the key name can be changed according to the situation $redis->set($m, '[Hello, dear user! Happy new year to you!'); echo 'yes:' . $i . PHP_EOL; } function randomPhoneNumber() { // Mobile phone number $header = ["133", "149", "153", "173", "177", "180", "181", "189", "199", "130", "131", "132", "145", "155", "156", "166", "171", "175", "176", "185", "186", "166", "134", "135", "136", "137", "138", "139", "147", "150", "151", "152", "157", "158", "159", "172", "178", "182", "183", "184", "187", "188", "198", "170", "171"]; $count = count($header); $header_value = rand(0, $count - 1); return $header[$header_value] . '****' . rand(1000, 9999); }
Consumer
<?php /** * Created by PhpStorm. * User: smallForest<1032817724@qq.com> * Date: 2019-12-02 * Time: 10:58 */ ini_set('default_socket_timeout', -1); //No timeout $redis = new \Redis(); $redis->connect('127.0.0.1', 6379); $redis->select(4);//Switch to db3 $redis->setOption(\Redis::OPT_READ_TIMEOUT, -1); While ($key_arr = $redis->brpop('SMS_QUEUE', 0)) { // Key? Arr is an array. 0 represents the key name SMS? Queue, and 1 represents the acquired value usleep(100000); $key = $key_arr[1]; if ($msg = $redis->get($key)) { sms($key, $msg); $redis->del(key()); } } // Send SMS function function sms($mobile, $msg) { echo 'User mobile number:' . $mobile . ',Message:' . $msg . ' Sending succeeded!' . PHP_EOL; }
Daemons can be created with nohup to create daemons for consumers
? question - what if there are many phone numbers in lpush?
swoole multithreading