PHP Based on Redis counter class

Source: Internet
Author: User
Tags auth redis reserved server port

Redis is an open source, with the use of ANSI C language, support network, can be based on memory can also be persistent log-type, Key-value database, and provide a variety of language APIs.

This article uses its incr, get (fetch), delete (purge) method to implement the Counter class.

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
 To realize the increment count, the main use of the Redis incr method, the concurrent implementation of the guarantee count is unique. * * Func: * Public INCR performs the increment count and obtains the increment value * Public gets get 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 ();  /** * Performs a self-increment count and obtains the self-increment value * @param String $key Save count Key value * @param Int $incr The number of numbers, default to 1 * @return
    Int/Public Function incr ($key, $incr =1) {return intval ($this->_redis->incr ($key, $INCR));
        /** * Gets Current count * @param String $key Save Count's health value * @return Int/Public function get ($key) {
    Return Intval ($this->_redis->get ($key));
  }

    /**   * Reset Count * @param String $key The health value of the save Count * @return Int/Public Function Reset ($key) {return $
    This->_redis->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

<?php
Require ' RedisCounter.class.php ';

Redis Connection Setting
$config = Array (
    ' host ' => ' localhost ', '
    Port ' => 6379,
    ' index ' => 0,
    ' auth ' = > ',
    ' timeout ' => 1,
    ' reserved ' => NULL,
    ' retry_interval ' =>
;

Create a Rediscounter object
$oRedisCounter = new Rediscounter ($config);

Defines the health value of the save count
$key = ' mycounter ';

Performs an increment count, gets 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; One
echo $oRedisCounter->reset ($key). Php_eol; 1
Echo $oRedisCounter->get ($key). Php_eol; 0 
?>

Output:

0
1
1
0


2. Concurrent Call counter, check count uniqueness

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 ' =>
;

Create a Rediscounter object
$oRedisCounter = new Rediscounter ($config);

Defines the health value of the save count
$key = ' mytestcounter ';

Executes the self count and returns the count after the increment, recording 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 concurrent.

Ab-c 15-n http://localhost/test.php

Execution Results:

Ab-c 15-n http://localhost/test.php This is apachebench, Version 2.3 < $Revision: 1554214 $> Copyright 1996 Ada

M 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:local      Host Server port:80 document Path:/test.php document length:0 bytes concurrency level: Taken for tests:0.173 seconds Complete requests:150 Failed requests:0 Total Transferred:2 4150 bytes HTML transferred:0 bytes Requests/second:864.86 [#/sec] (mean) time per request:17.344 [m S] (mean) time/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:33.2 Waiting:3 3.2 Total:4 3.1 (Percentag)      E of the requests served within a certain time (ms) 50% 17 66% 18 75% 18 80% 19 90% 20 95% 98% 99% 100% (longest request)

Check if count is unique

The 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 in the case of a concurrent invocation, the generated count is guaranteed to be unique.


Source Download Address: Click to view

Related Article

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.