An example of PHP+Redis message queue to realize registration number statistics under high concurrency

  • 2021-09-11 19:34:28
  • OfStack

Preface

Now more and more websites begin to pay attention to statistics and user behavior analysis. As a frequently used function of websites, how to make statistical performance higher is also something we need to consider. This article optimizes the statistical function through Redis (taking the statistics of registered people as an example).

The traditional statistical function is to directly operate the database and insert data into the table. In doing so, the performance consumption of the database will be relatively large.

Thoughts:

Here we use the redis queue, the registration time first add to the queue, and then in the processing time out of the queue, and add the number of redis.

Code:


<?php
//register.php 
$redis = new Redis();
$redis->connect('127.0.0.1',6379);
$i=0;
while(true){
  $i++;
  // Assumption 1 Someone is registering 
  $redis->rpush("register_success",$i);
}

<?php
//deal.php
$redis = new Redis();
$redis->connect('127.0.0.1',6379);
while (true) {
  //list Type dequeue operation 
  $value = $redis->lpop('register_success');
  if($value){
    echo "deal value : ".$value;
    // Self-increasing   Add registration statistics    If key Nonexistent   Is initialized to 0
    $redis->incr('register_num');
  }else{
    echo "deal finish";
  }
}

Related articles: