PHP is based on the definition and usage example of the redis counter class.

Source: Internet
Author: User

PHP is based on the definition and usage example of the redis counter class.

This article describes the definition and usage of PHP counter Class Based on redis. We will share this with you for your reference. The details are as follows:

Redis is an open-source log-type and Key-Value database written in ansi c language that supports Network, memory-based persistence, and provides APIs in multiple languages.

Here, the incr, get, and delete methods are used to implement the counter class.

1. Redis counter code and demo instance

RedisCounter. class. php

<? Php/*** PHP Based on Redis counter class * Date: 2017-10-28 * Author: fdipzone * Version: 1.0 ** Descripton: * php self-incrementing count based on Redis, the incr method of redis is used to ensure that the Count auto-increment is unique During Concurrent execution. ** Func: * public incr executes the auto-increment count and obtains the value * public get obtains the current count * public reset resets the count * private connect creates a redis connection */class RedisCounter {// class start private $ _ config; private $ _ redis;/*** initialize * @ param Array $ config redis connection setting */public function _ construct ($ config) {$ this-> _ config = $ config; $ this-> _ redis = $ this-> connect ();} /*** execute auto-increment count and obtain the auto-increment value * @ param String $ key to save the key value of the count * @ param Int $ incr auto-increment quantity The default value is 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 Count key value * @ return Int */public function get ($ key) {return intval ($ this->_redis-> get ($ key ));} /*** reset the Count ** @ param String $ key to save the Count key value * @ return Int */public function reset ($ key) {return $ this-> _ redis-> delete ($ key);}/*** create a redis connection * @ return Link */pr Ivate 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 a RedisCounter object $ oRedisCounter = new RedisCounter ($ config); // define the saved count key $ key = 'mycounter '; // execute auto-increment counting, returns the current count. resets the 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:

011110

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

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 a RedisCounter object $ oRedisCounter = new RedisCounter ($ config); // define the key for saving the count $ key = 'mytestcounter '; // execute the auto-increment count and return the auto-increment count. Record the temporary file file_put_contents ('/tmp/mytest_result.log', $ oRedisCounter-> incr ($ key ). PHP_EOL, FILE _ APPEND);?>

Test concurrency execution. We use the AB tool for testing and set the execution to 150 and 15 concurrency.

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

Execution result:

ab -c 15 -n 150 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 Port:      80Document Path:     /test.phpDocument Length:    0 bytesConcurrency Level:   15Time taken for tests:  0.173 secondsComplete requests:   150Failed requests:    0Total transferred:   24150 bytesHTML transferred:    0 bytesRequests 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] receivedConnection Times (ms)       min mean[+/-sd] median  maxConnect:    0  0  0.2   0    1Processing:   3  16  3.2   16   23Waiting:    3  16  3.2   16   23Total:     4  16  3.1   17   23Percentage 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

Total number of records generated wc-l/tmp/mytest_result.log 150/tmp/mytest_result.log unique count sort-u/tmp/mytest_result.log | wc-l 150

It can be seen that, in the case of concurrent calls, the generated count is also unique.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.