PHP Counter Class Definition and Usage Example Based on redis

  • 2021-09-11 19:49:23
  • OfStack

This paper illustrates the definition and usage of PHP counter class based on redis. Share it for your reference, as follows:

Redis is an open source ANSI C language written, network-supported, memory-based and persistent log-type, Key-Value database, and provides API in multiple languages.

The counter class is implemented here using its incr (self-increment), get (get), delete (clear) methods.

1. Redis counter class code and demonstration example

RedisCounter.class.php


<?php
/**
 * PHP Based on Redis Counter class 
 * Date:  2017-10-28
 * Author: fdipzone
 * Version: 1.0
 *
 * Descripton:
 * php Based on Redis Realize self-increasing counting, mainly using redis Adj. incr Method, the count is guaranteed to increase only when executed concurrently 1 . 
 *
 * Func:
 * public incr   Perform a self-incremented count and obtain the self-incremented value 
 * public get    Get the current count 
 * public reset   Reset Count 
 * private connect  Create redis Connect 
 */
class RedisCounter{ // class start
  private $_config;
  private $_redis;
  /**
   *  Initialization 
   * @param Array $config redis Connection setting 
   */
  public function __construct($config){
    $this->_config = $config;
    $this->_redis = $this->connect();
  }
  /**
   *  Perform a self-incremented count and obtain the self-incremented value 
   * @param String $key  Save the key value of the count 
   * @param Int  $incr  Self-incremented quantity, default to 1
   * @return Int
   */
  public function incr($key, $incr=1){
    return intval($this->_redis->incr($key, $incr));
  }
  /**
   *  Get the current count 
   * @param String $key  Save the key value of the count 
   * @return Int
   */
  public function get($key){
    return intval($this->_redis->get($key));
  }
  /**
   *  Reset Count 
   * @param String $key  Save the key value of the count 
   * @return Int
   */
  public function reset($key){
    return $this->_redis->delete($key);
  }
  /**
   *  Create redis Connect 
   * @return Link
   */
  private function connect(){
    try{
      $redis = new Redis();
      $redis->connect($this->_config['host'],$this->_config['port'],$this->_config['timeout'],$this->_config['reserved'],$this->_config['retry_interval']);
      if(empty($this->_config['auth'])){
        $redis->auth($this->_config['auth']);
      }
      $redis->select($this->_config['index']);
    }catch(RedisException $e){
      throw new Exception($e->getMessage());
      return false;
    }
    return $redis;
  }
} // class end
?>

demo.php


<?php
Require 'RedisCounter.class.php';
// redis Connection setting 
$config = array(
  'host' => 'localhost',
  'port' => 6379,
  'index' => 0,
  'auth' => '',
  'timeout' => 1,
  'reserved' => NULL,
  'retry_interval' => 100,
);
//  Create RedisCounter Object 
$oRedisCounter = new RedisCounter($config);
//  Define the key value to save the count 
$key = 'mycounter';
//  Execute self-incrementing count, obtain current count and reset count 
echo $oRedisCounter->get($key).PHP_EOL; // 0
echo $oRedisCounter->incr($key).PHP_EOL; // 1
echo $oRedisCounter->incr($key, 10).PHP_EOL; // 11
echo $oRedisCounter->reset($key).PHP_EOL; // 1
echo $oRedisCounter->get($key).PHP_EOL; // 0
?>

Output:


0
1
11
1
0

2. Call the counter concurrently to check the uniqueness of the count

The test code is as follows:


<?php
Require 'RedisCounter.class.php';
// redis Connection setting 
$config = array(
  'host' => 'localhost',
  'port' => 6379,
  'index' => 0,
  'auth' => '',
  'timeout' => 1,
  'reserved' => NULL,
  'retry_interval' => 100,
);
//  Create RedisCounter Object 
$oRedisCounter = new RedisCounter($config);
//  Define the key value to save the count 
$key = 'mytestcounter';
//  Execute self-increment count and return the self-increment count, and record it in temporary file 
file_put_contents('/tmp/mytest_result.log', $oRedisCounter->incr($key).PHP_EOL, FILE_APPEND);
?>

Test concurrent execution, we use ab tool to test, set to execute 150 times, 15 concurrent.


ab -c 15 -n 150 http://localhost/test.php

Implementation results:


ab -c 15 -n 150 http://localhost/test.php
This is ApacheBench, Version 2.3 <$Revision: 1554214 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/
Benchmarking home.rabbit.km.com (be patient).....done
Server Software:    nginx/1.6.3
Server Hostname:    localhost
Server Port:      80
Document Path:     /test.php
Document Length:    0 bytes
Concurrency Level:   15
Time taken for tests:  0.173 seconds
Complete requests:   150
Failed requests:    0
Total transferred:   24150 bytes
HTML transferred:    0 bytes
Requests per second:  864.86 [#/sec] (mean)
Time per request:    17.344 [ms] (mean)
Time per request:    1.156 [ms] (mean, across all concurrent requests)
Transfer rate:     135.98 [Kbytes/sec] received
Connection Times (ms)
       min mean[+/-sd] median  max
Connect:    0  0  0.2   0    1
Processing:   3  16  3.2   16   23
Waiting:    3  16  3.2   16   23
Total:     4  16  3.1   17   23
Percentage of the requests served within a certain time (ms)
 50%   17
 66%   18
 75%   18
 80%   19
 90%   20
 95%   21
 98%   22
 99%   22
 100%   23 (longest request)

Check whether the count is only 1


 Total number generated 

wc -l /tmp/mytest_result.log
   150 /tmp/mytest_result.log

 Generated only 1 Count 

sort -u /tmp/mytest_result.log | wc -l
   150

You can see that in the case of concurrent calls, the generated count is also guaranteed to be only 1.

For more readers interested in PHP related content, please check the topics on this site: "Summary of php+redis Database Programming Skills", "Introduction to php Object-Oriented Programming", "Introduction to PHP Basic Syntax", "Encyclopedia of PHP Array (Array) Operation Skills", "Summary of php String (string) Usage", "Introduction to php+mysql Database Operation Skills" and "Summary of php Common Database Operation Skills"

I hope this article is helpful to everyone's PHP programming.


Related articles: