1 What is redis subscription

Redis publish subscription (PUB/SUB) is a message communication model: the sender (PUB) sends the message and the subscriber (sub) receives the message. Be direct, you can interpret as I follow you, you post information, articles, etc., I can receive it immediately.


2 Where is the publish and subscribe scenario

Here are some scenarios:

2.1 Messages on typical web pages can be notified in real time

2.2 Real-time notification of inventory changes via Redis subscription after an order is placed

2.3 When the interface needs to do some functions, such as sending emails and writing logs, it can be applied to redis subscription, which will speed up the interface return time


3. How to implement real-time publishing and subscription in PHP

Now that we know what subscription and publish scenarios are, let’s see how to implement publish subscriptions with PHP and Redis

3.1 CLI.php, the subscription-side code is mainly noted for executing PHP under the CLI

<? phpwhile (true) {echo time();
    ini_set('default_socket_timeout', 1); / / no timeout$redis = new Redis();
    $redis->connect('127.0.01', 6379, 3600);
    $redis->auth('123456'); // Set the password$result = $redis->subscribe(['test'].'callback');
    print_r($result); Sleep (0.1); }function callback($instance.$channelName.$message)
{
    print_r($message);
}
Copy the code

After startup, let’s go to the release side of the code

3.2 Release side code, pub.php this code can be placed in the ordinary web page execution

<? php$redis = new Redis();
$redis->connect('127.0.0.1', 6379, 3600);
$redis->auth('123456'); // Set the password$message = 'Test it out';
$ret=$redis->publish('test'.$message);Copy the code

PHP redis subscribe to publish successfully, is not very simple, mainly use redis subscribe method, publish method, of course, these code in the actual use process or can be optimized such as cli.php, according to their own needs to implement it.


Here is an example of a publish-subscribe implementation implemented by Laravel

Laravel’s PHP artisan list command can be executed in the Handle to view the current task, and then the nohub command can be used to stay in the background

    public function handle()
    {
      # Subscribe to message Redis
        $redis = new \Redis();
        $redis->pconnect(Config("host"), Config("port"));
        $redis->auth(Config("password")); // subscribe ORDERID ORDERID$redis->subscribe(['ORDERID'].function($redis.$channel.$message) {
            if ($channel= ='ORDERID') {$message = 10002
                if ($message){// Store to your own Redis library where multiple connections are configured$redis2 = Redis::connection('driver_outset_time');
                    $redis2->set('ORDERID_'.$message,time());#value为时间time()
                    $redis2->EXPIRE('ORDERID_'.$message,time(), 24*60*60);Set the key expiration time to 24 hours
                    $this->xxxxx($message,xxx);Call other methods to perform other business logic}}}); }Copy the code

Next, how to send SMS messages in batches

1. First, store the mobile phone number that needs to send information into redis cache

$redis = new \redis();
$conn = $redis->connect('localhost', 6379);
$auth = $redis->auth('* * * * *'); // Redis sets a password and requires authentication$list = Testuser::find()->asarray()->all();
for ($i= 0;$i < count($list); $i{+ +)$redis->lpush('list'.$list[$i] ['email']);
}
Copy the code

Store the mobile phone number that needs to be sent into redis cache

2. Invoke the SMS interface to send SMS messages

$redis = new \redis();
$conn = $redis->connect('localhost', 6379);
$auth = $redis->auth('* * * * *');
$lenth = $redis->llen('list');

for ($i= 0;$i < $lenth ; $i{+ +)$phone = $redis->brpop('list', 1, 60); // Pop a value from the end with a timeout of 60 seconds$phonenumber = $phone[1].$sendmsg = send($phonenumber);

    if($sendmsg){// Handle the logic that sent successfully}else{// Handle send failure logic} usleep(500000); // microsecond, call third-party interface, need to pay attention to the frequency,}Copy the code

Here, combined with THE CLI mode of PHP, the command is triggered by the function exec. Direct background execution.