本文引自网络

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; //
echo $oRedisCounter->incr($key).PHP_EOL; //
echo $oRedisCounter->incr($key, 10).PHP_EOL; //
echo $oRedisCounter->reset($key).PHP_EOL; //
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工具进行测试,设置执行次,个并发。

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 基于redis计数器类的更多相关文章

  1. 项目分布式部署那些事(1):ONS消息队列、基于Redis的Session共享,开源共享

    因业务发展需要现在的系统不足以支撑现在的用户量,于是我们在一周之前着手项目的性能优化与分布式部署的相关动作. 概况 现在的系统是基于RabbitHub(一套开源的开发时框架)和Rabbit.WeiXi ...

  2. 分布式锁 基于Redis

    分布式锁的实现(基于Redis) 参考:http://www.jb51.net/article/75439.htm http://www.linuxidc.com/Linux/2015-01/1118 ...

  3. 基于Redis的CAS服务端集群

    为了保证生产环境CAS(Central Authentication Service)认证服务的高可用,防止出现单点故障,我们需要对CAS Server进行集群部署. CAS的Ticket默认是以Ma ...

  4. 设计模式之PHP项目应用——单例模式设计Memcache和Redis操作类

    1 单例模式简单介绍 单例模式是一种经常使用的软件设计模式. 在它的核心结构中仅仅包括一个被称为单例类的特殊类. 通过单例模式能够保证系统中一个类仅仅有一个实例并且该实例易于外界訪问.从而方便对实例个 ...

  5. 基于Redis缓存的Session共享(附源码)

    基于Redis缓存的Session共享(附源码) 在上一篇文章中我们研究了Redis的安装及一些基本的缓存操作,今天我们就利用Redis缓存实现一个Session共享,基于.NET平台的Seesion ...

  6. 基于Redis的在线用户列表解决方案

    前言: 由于项目需求,需要在集群环境下实现在线用户列表的功能,并依靠在线列表实现用户单一登陆(同一账户只能一处登陆)功能: 在单机环境下,在线列表的实现方案可以采用SessionListener来完成 ...

  7. [项目回顾]基于Redis的在线用户列表解决方案

    迁移:基于Redis的在线用户列表解决方案 前言: 由于项目需求,需要在集群环境下实现在线用户列表的功能,并依靠在线列表实现用户单一登陆(同一账户只能一处登陆)功能: 在单机环境下,在线列表的实现方案 ...

  8. 记一次企业级爬虫系统升级改造(六):基于Redis实现免费的IP代理池

    前言: 首先表示抱歉,春节后一直较忙,未及时更新该系列文章. 近期,由于监控的站源越来越多,就偶有站源做了反爬机制,造成我们的SupportYun系统小爬虫服务时常被封IP,不能进行数据采集. 这时候 ...

  9. [转载] 基于Redis实现分布式消息队列

    转载自http://www.linuxidc.com/Linux/2015-05/117661.htm 1.为什么需要消息队列?当系统中出现“生产“和“消费“的速度或稳定性等因素不一致的时候,就需要消 ...

随机推荐

  1. Java基础——iO(三)

    一.管道流 演示:PipedInputStream  , PipedOutputStream 注意:管道流本身就不建议在一个线程中使用,这是因为向输出流中写的数据,都会存到输入流内部的一个1024字节 ...

  2. elasticsearch6.7 04.API规范

    API Conventions elasticsearch的REST的API是使用HTTP的JSON格式暴露的. 除非另有说明,本章中列出的约定可以在整个REST API中应用. 多索引 索引名称支持 ...

  3. Boring Sum(hdu4961)hash

    Boring Sum Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)Total S ...

  4. 4+1视图与UML对应关系

    4+1视图模型概况     Kruchten 提出了一个"4+1"视图模型,从5个不同的视角包括包括逻辑试图.进程视图.物理视图.开发视图.场景视图来描述软件体系结构.每一个视图只 ...

  5. windows 格式化D盘

    格式化D盘1.右击我的电脑2.高级系统设置3.高级4.性能->设置5.高级->虚拟内存(更改)6.双击D设置->无分页文件7.确定->重启计算机

  6. 鼠标滚轮更改transform的值(vue-scroller在PC端的上下滑动)

    目前上拉刷新,下拉加载,以及区域回弹的组件,绝大多数都是通过transform去实现的.在移动端效果很好,但是PC端使用鼠标拖拽的方式,查看下文首先不符合逻辑,其次容易点进其他页面. 起初,项目的初衷 ...

  7. css3 之 display 属性

    1.定义 语法:display:none | inline | block | list-item | inline-block | table | inline-table | table-capt ...

  8. 手把手在MyEclipse中搭建Hibernate开发环境

    (尊重劳动成果,转载请注明出处:http://blog.csdn.net/qq_25827845/article/details/53414303冷血之心的博客) 在MyEclipse中如何搭建Hib ...

  9. 活字格Web应用平台学习笔记 7 - 导出 Excel

    活字格一直强调和Excel的兼容,可以导入导出Excel,今天终于学到这一课了. 课程目标: 好吧,就是这么快,已经加了一个“导出到Excel”的按钮了 我以为多高深呢,原来人家都给写好逻辑了,直接选 ...

  10. Nginx的日志优化

    1.日志轮询切割: 这篇文章已经对日志轮询切割做个介绍:请点击这里 2.不记录不需要的日志 在实际的工作中,对于负载均衡器健康节点检查或某些特定文件的日志,一般不需要记录下来,因为统计PV是按照页面计 ...