<kbd id='woaibaidu'></kbd><address id='woaibaidu'><style id='woaibaidu'></style></address><button id='woaibaidu'></button>

          当前位置:主页 > 网络编程 > PHP编程 >
            PHP基于redis计数器类定义与用法示例
            2018-02-12 22:01 发布 次浏览

          本文实例讲述了PHP基于redis计数器类界说与用法。分享给各人供各人参考,详细以下:

          Redis是1个开源的运用ANSI C言语编写、支持网络、可基于内存亦可耐久化的日志型、Key-Value数据库,并提供多种言语的API。

          这里运用其incr(自增),get(获得),delete(肃清)办法来完成计数器类。

          1.Redis计数器类代码及演示实例

          RedisCounter.class.php

          <?php
          /**
           * PHP基于Redis计数器类
           * Date:  2017⑴0⑵8
           * 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['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衔接设定
          $config = array(
            'host' => 'localhost',
            'port' => 6379,
            'index' => 0,
            'auth' => '',
            'timeout' => 1,
            'reserved' => NULL,
            'retry_interval' => 100,
          );
          // 创立RedisCounter工具
          $oRedisCounter = new RedisCounter($config);
          // 界说保管计数的健值
          $key = 'mycounter';
          // 履行自增计数,获得以后计数,重置计数
          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
          ?>
          
          

          输入:

          0
          1
          11
          1
          0
          
          

          2.并发挪用计数器,反省计数独一性

          测试代码以下:

          <?php
          Require 'RedisCounter.class.php';
          // redis衔接设定
          $config = array(
            'host' => 'localhost',
            'port' => 6379,
            'index' => 0,
            'auth' => '',
            'timeout' => 1,
            'reserved' => NULL,
            'retry_interval' => 100,
          );
          // 创立RedisCounter工具
          $oRedisCounter = new RedisCounter($config);
          // 界说保管计数的健值
          $key = 'mytestcounter';
          // 履行自增计数并前往自增后的计数,记载入暂时文件
          file_put_contents('/tmp/mytest_result.log', $oRedisCounter->incr($key).PHP_EOL, FILE_APPEND);
          ?>
          
          

          测试并发履行,我们运用ab工具停止测试,设置履行150次,15个并发。

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

          履行后果:

          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)
          
          

          反省计数能否独一

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

          可以看到在并发挪用的状况下,生成的计数也保证独一。

          更多关于PHP相干内容感兴味的读者可检查本站专题:《php+redis数据库顺序设计技能总结》、《php面向工具顺序设计入门教程》、《PHP根本语法入门教程》、《PHP数组(Array)操作技能大全》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php罕见数据库操作技能汇总》

          希望本文所述对各人PHP顺序设计有所协助。