Home >Backend Development >PHP Tutorial >Interpret PHP-based redis counter class in one minute

Interpret PHP-based redis counter class in one minute

慕斯
慕斯forward
2021-06-22 09:55:282478browse

This article will introduce to you a one-minute interpretation of PHP-based redis counter class? It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

Interpret PHP-based redis counter class in one minute

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

This article will use its incr (increment) , get (get) , delete (clear) methods to implement the counter class.

1.Redis counter class code and demonstration example

RedisCounter.class.php

<?php/**
 * PHP基于Redis计数器类
 * Date:    2017-10-28
 * Author:  fdipzone
 * Version: 1.0
 *
 * Descripton:
 * php基于Redis实现自增计数,主要使用redis的incr方法,并发执行时保证计数自增唯一。
 *
 * Func:
 * public  incr    执行自增计数并获取自增后的数值
 * public  get     获取当前计数
 * public  reset   重置计数
 * private connect 创建redis连接
 */class RedisCounter{ // class start

    private $_config;    private $_redis;    /**
     * 初始化
     * @param Array $config redis连接设定
     */
    public function __construct($config){
        $this->_config = $config;
        $this->_redis = $this->connect();
    }    /**
     * 执行自增计数并获取自增后的数值
     * @param  String $key  保存计数的键值
     * @param  Int    $incr 自增数量,默认为1
     * @return Int
     */
    public function incr($key, $incr=1){        return intval($this->_redis->incr($key, $incr));
    }    /**
     * 获取当前计数
     * @param  String $key 保存计数的健值
     * @return Int
     */
    public function get($key){        return intval($this->_redis->get($key));
    }    /**
     * 重置计数
     * @param  String  $key 保存计数的健值
     * @return Int
     */
    public function reset($key){        return $this->_redis->delete($key);
    }    /**
     * 创建redis连接
     * @return Link
     */
    private function connect(){        try{
            $redis = new Redis();
            $redis->connect($this->_config[&#39;host&#39;],
            $this->_config[&#39;port&#39;],$this->_config[&#39;timeout&#39;],$this->_config[&#39;reserved&#39;],
            $this->_config[&#39;retry_interval&#39;]);            
            if(empty($this->_config[&#39;auth&#39;])){
                $redis->auth($this->_config[&#39;auth&#39;]);
            }
            $redis->select($this->_config[&#39;index&#39;]);
        }catch(RedisException $e){            throw new Exception($e->getMessage());            return false;
        }        return $redis;
    }


} // class end?>

demo.php

<?php
Require &#39;RedisCounter.class.php&#39;;

// redis连接设定
$config = array(
    &#39;host&#39; => &#39;localhost&#39;,
    &#39;port&#39; => 6379,
    &#39;index&#39; => 0,
    &#39;auth&#39; => &#39;&#39;,
    &#39;timeout&#39; => 1,
    &#39;reserved&#39; => NULL,
    &#39;retry_interval&#39; => 100,
);

// 创建RedisCounter对象
$oRedisCounter = new RedisCounter($config);

// 定义保存计数的健值
$key = &#39;mycounter&#39;;

// 执行自增计数,获取当前计数,重置计数
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. Concurrently call the counter and check the uniqueness of the count

The test code is as follows:

<?php
Require &#39;RedisCounter.class.php&#39;;

// redis连接设定
$config = array(
    &#39;host&#39; => &#39;localhost&#39;,
    &#39;port&#39; => 6379,
    &#39;index&#39; => 0,
    &#39;auth&#39; => &#39;&#39;,
    &#39;timeout&#39; => 1,
    &#39;reserved&#39; => NULL,
    &#39;retry_interval&#39; => 100,
);

// 创建RedisCounter对象
$oRedisCounter = new RedisCounter($config);

// 定义保存计数的健值
$key = &#39;mytestcounter&#39;;

// 执行自增计数并返回自增后的计数,记录入临时文件
file_put_contents(&#39;/tmp/mytest_result.log&#39;, $oRedisCounter->incr($key).PHP_EOL, FILE_APPEND);
?>

To test concurrent execution, we use ab Tool for testing, set to execute 150 times, 15 concurrency.

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

Execution 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 unique

生成的总计数
wc -l /tmp/mytest_result.log 
     150 /tmp/mytest_result.log生成的唯一计数
sort -u /tmp/mytest_result.log | wc -l
     150

You can see that in concurrent calls case, the resulting count is also guaranteed to be unique.
Recommended learning: php video tutorial

The above is the detailed content of Interpret PHP-based redis counter class in one minute. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete