PHP基于redis计数器类定义与用法示例

 更新时间:2018年02月08日 10:53:37   作者:傲雪星枫  
这篇文章主要介绍了PHP基于redis计数器类定义与用法,结合实例形式较为详细的分析了php定义的redis计数器类及其相关使用技巧,需要的朋友可以参考下

本文实例讲述了PHP基于redis计数器类定义与用法。分享给大家供大家参考,具体如下:

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

这里使用其incr(自增)get(获取)delete(清除)方法来实现计数器类。

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

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['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程序设计有所帮助。

相关文章

  • PHP概率计算函数汇总

    PHP概率计算函数汇总

    做项目的有时会弄个活动什么的,来让用户参加,既吸引用户注册,又提高网站的用户活跃度。同时参加的用户会获得一定的奖品,有100%中奖的,也有按一定概率中奖的,大的比如中个ipad,小的中个Q币。那么我们在程序里必然会设计到算法,即按照一定的概率让用户获得奖品。
    2015-09-09
  • 解析wamp5下虚拟机配置文档

    解析wamp5下虚拟机配置文档

    本篇文章是对wamp5下虚拟机配置文档的方法进行了详细的分析介绍,需要的朋友参考下
    2013-06-06
  • php动态生成JavaScript代码

    php动态生成JavaScript代码

    生成javascript的实现代码
    2009-03-03
  • PHP可逆加密/解密函数分享

    PHP可逆加密/解密函数分享

    很多项目的会员系统,都要求要有记住登录功能,在通过cookies实现功能是,由于要将客户信息直接保存到cookies,如果直接写入cookies势必会带来安全隐患,因此通过可逆加密后再保存到cookies相对就安全了
    2012-09-09
  • php_xmlhttp 乱码问题解决方法

    php_xmlhttp 乱码问题解决方法

    近来测试php_xmlhttp乱码问题,无他,仅是不想用那些乱七八糟的框架耳,或者高兴了,组织一组也不一定。
    2009-08-08
  • php动态添加url查询参数的方法

    php动态添加url查询参数的方法

    这篇文章主要介绍了php动态添加url查询参数的方法,涉及php通过正则替换操作URL的技巧,具有一定参考借鉴价值,需要的朋友可以参考下
    2015-04-04
  • php统计数组不同元素的个数的实例方法

    php统计数组不同元素的个数的实例方法

    在本篇文章里小编给大家整理的是关于php统计数组不同元素的个数的实例方法以及相关知识点,有需要的朋友们学习下。
    2019-09-09
  • php中简单的对称加密算法实现

    php中简单的对称加密算法实现

    最近突发奇想要往数据库里保存一些机密的东西,然后就想着怎么让别人即使进入到了数据库也看不懂存储的是什么,那么只有加密了;可是我们自己还要看呢,那只能找一些对称加密的算法了,我们想看的时候再解密回来。下面就介绍了php中简单的对称加密算法实现。
    2017-01-01
  • php数组保存文本与文本反编成数组实例

    php数组保存文本与文本反编成数组实例

    这篇文章主要介绍了php数组保存文本与文本反编成数组的方法,通过两个自定义函数string2array与array2string实例展示了php数组保存文本与文本反编成数组的实现方法,具有不错的参考借鉴价值,需要的朋友可以参考下
    2014-11-11
  • php ci框架验证码实例分析

    php ci框架验证码实例分析

    本篇文章是对ci框架验证码的实例进行了详细的分析介绍,需要的朋友参考下
    2013-06-06

最新评论