Redis is an open source API that is written in ANSI C, supports the web, can be persisted in memory, key-value databases, and provides multiple languages.
This uses its incr (self-increment), get (get), delete (purge) method to implement the Counter class. This paper mainly introduces PHP based on the definition and usage of the Redis counter class, combined with examples of the form of a more detailed analysis of the PHP definition of the Redis counter class and its related use skills, the need for friends can refer to, hope to help everyone.
1.Redis Counter Class Code and demo 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 implementation of the self-increment count, mainly use The incr method of Redis, which guarantees count self-increment only when concurrently executing. * Func: * Public incr perform the self-increment count and get the value since increment * Public get get current count * Public reset Reset Count * Private connect Create Redis connection */class Re discounter{//class start Private $_config; Private $_redis; /** * Initialize * @param Array $config redis Connection Settings */Public function __construct ($config) {$this->_config = $config; $this->_redis = $this->connect (); }/** * Performs the self-increment count and gets the value since increment * @param String $key The key value of the save Count * @param Int $incr increment, default is 1 * @return int * * Public fun Ction incr ($key, $incr =1) {return intval ($this->_redis->incr ($key, $INCR)); /** * Gets the current count * @param String $key Save Count's health value * @return INT */Public function get ($key) {return intval ($this-& Gt;_redis->get ($key)); }/** * Reset Count * @param String $key Save Count's health value * @return INT */Public Function reset ($key) {return $this->_red Is->delete ($key); /** * Create redis connection * @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
<?phprequire ' RedisCounter.class.php ';//redis connection settings $config = Array ( ' host ' = ' localhost ', ' port ' = 6379, ' index ' = 0, ' auth ' + ', ' timeout ' = 1, ' reserved ' + NULL, ' Retry_interval ' = 100,);//Create Rediscounter Object $orediscounter = new Rediscounter ($config);//define Save Count's health value $key = ' mycounter ';//Perform self-increment count, Gets the current count, resets the Count Echo $oRedisCounter->get ($key). Php_eol; 0echo $oRedisCounter->incr ($key). Php_eol; 1echo $oRedisCounter->incr ($key, 10). Php_eol; 11echo $oRedisCounter->reset ($key). Php_eol; 1echo $oRedisCounter->get ($key). Php_eol; 0?>
Output:
011110
2. Concurrent call counter, check count uniqueness
The test code is as follows:
<?phprequire ' RedisCounter.class.php ';//redis connection settings $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 health value of the save count $key = ' mytestcounter ';// Executes the self-increment count and returns the self-increment count, logged into the temporary file file_put_contents ('/tmp/mytest_result.log ', $oRedisCounter->incr ($key). Php_eol, file_append);? >
Test concurrent execution, we use the AB tool to test, set execution 150 times, 15 concurrency.
Ab-c 15-n http://localhost/test.php
Execution Result:
Ab-c 15-n Http://localhost/test.phpThis 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) ... doneserver software:nginx/1.6.3server hostname:localhostserver Po Rt:80document Path:/test.phpdocument length:0 bytesconcurrency level:15time taken for tests:0.173 Seco Ndscomplete requests:150failed requests:0total transferred:24150 byteshtml transferred:0 bytesRequests per s econd:864.86 [#/sec] (mean) time per request:17.344 [MS] (mean) time per request:1.156 [MS] (mean, across all conc urrent requests) Transfer rate:135.98 [Kbytes/sec] receivedconnection times (ms) min MEAN[+/-SD] Median maxconn ect:0 0 0.2 0 1processing:3 3.2 16 3.1 17 2 23waiting:3 3.2 3Percentage of the RequestsServed within a certain time (ms) 50% (66%) 75% 80% (90%) 95% (98%) 99% 100% St request)
Check if Count is unique
Total number of builds Wc-l/tmp/mytest_result.log 150/tmp/mytest_result.log generated unique count sort-u/tmp/mytest_result.log | wc-l 150
You can see that the generated count is also guaranteed to be unique in the case of concurrent calls.