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


Posted in PHP onFebruary 08, 2018

本文实例讲述了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 相关文章推荐
PHP中10个不常见却非常有用的函数
Mar 21 PHP
PHP OPCode缓存 APC详细介绍
Oct 12 PHP
仿Aspnetpager的一个PHP分页类代码 附源码下载
Oct 08 PHP
php全角字符转换为半角函数
Feb 07 PHP
PHP中file_get_contents高?用法实例
Sep 24 PHP
PHP合并静态文件详解
Nov 14 PHP
php实现的农历算法实例
Aug 11 PHP
php中preg_match的isU代表什么意思
Oct 01 PHP
PHP经典算法集锦【经典收藏】
Sep 14 PHP
[原创]php正则删除img标签的方法示例
May 27 PHP
浅谈laravel框架与thinkPHP框架的区别
Oct 23 PHP
浅谈Laravel中使用Slack进行异常通知
May 29 PHP
php处理抢购类功能的高并发请求
Feb 08 #PHP
php+redis实现商城秒杀功能
Nov 19 #PHP
php+redis消息队列实现抢购功能
Feb 08 #PHP
PHP多线程模拟实现秒杀抢单
Feb 07 #PHP
PHP设计模式之装饰器模式实例详解
Feb 07 #PHP
PHP使用星号替代用户名手机和邮箱的实现代码
Feb 07 #PHP
PHP unlink与rmdir删除目录及目录下所有文件实例代码
Feb 07 #PHP
You might like
广播爱好者需要了解的天线知识
2021/03/01 无线电
PHP4与PHP3中一个不兼容问题的解决方法
2006/10/09 PHP
php_xmlhttp 乱码问题解决方法
2009/08/07 PHP
PHP中simplexml_load_string函数使用说明
2011/01/01 PHP
php连接mssql的一些相关经验及注意事项
2013/02/05 PHP
PHP实现获取图片颜色值的方法
2014/07/11 PHP
php格式化时间戳显示友好的时间实现思路及代码
2014/10/23 PHP
php curl 上传文件代码实例
2015/04/27 PHP
jquery实现多行文字图片滚动效果示例代码
2014/10/10 Javascript
jQuery手机浏览器中拖拽动作的艰难性分析
2015/02/04 Javascript
jQuery多条件筛选如何实现
2015/11/04 Javascript
每天一篇javascript学习小结(Function对象)
2015/11/16 Javascript
JavaScript模拟push
2016/03/06 Javascript
原生JavaScript实现Ajax的方法
2016/04/07 Javascript
基于bootstrap的选择框插件icheck
2016/12/23 Javascript
H5图片压缩与上传实例
2017/04/21 Javascript
Ionic2开发环境搭建教程
2020/08/20 Javascript
js实现简单掷骰子小游戏
2019/10/24 Javascript
微信小程序实现下滑到底部自动翻页功能
2020/03/07 Javascript
js+canvas绘制图形验证码
2020/09/21 Javascript
vue使用vue-quill-editor富文本编辑器且将图片上传到服务器的功能
2021/01/13 Vue.js
介绍Python的Django框架中的QuerySets
2015/04/20 Python
Python基本socket通信控制操作示例
2019/01/30 Python
在python 中split()使用多符号分割的例子
2019/07/15 Python
Python使用内置函数setattr设置对象的属性值
2020/10/16 Python
捷克领先的户外服装及配件市场零售商:ALPINE PRO
2018/01/09 全球购物
匡威西班牙官网:Converse西班牙
2019/10/01 全球购物
定义一结构体变量,用其表示点坐标,并输入两点坐标,求两点之间的距离
2015/08/17 面试题
婚礼新郎父母答谢词
2014/01/16 职场文书
《充气雨衣》教学反思
2014/04/07 职场文书
买房协议书
2014/04/11 职场文书
企业文化标语大全
2014/06/10 职场文书
大学生标准自荐书
2014/06/15 职场文书
2014基建处领导班子“四风”对照检查材料思想汇报
2014/10/04 职场文书
工作失误检讨书(经典集锦版)
2014/10/17 职场文书
mongoDB数据库索引快速入门指南
2022/03/23 MongoDB