登录  /  注册

一分钟解读php基于redis计数器类

慕斯
发布: 2021-06-22 09:55:28
转载
2225人浏览过

本篇文章给大家介绍一分钟解读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[&#39;host&#39;],
            $this->_config[&#39;port&#39;],$this->_config[&#39;timeout&#39;],$this->_config[&#39;reserved&#39;],
            $this->_config[&#39;retry_interval&#39;]);            
            if(empty($this->_config[&#39;auth&#39;])){
                $redis->auth($this->_config[&#39;auth&#39;]);
            }
            $redis->select($this->_config[&#39;index&#39;]);
        }catch(RedisException $e){            throw new Exception($e->getMessage());            return false;
        }        return $redis;
    }


} // class end?>
登录后复制

demo.php

<?php
Require &#39;RedisCounter.class.php&#39;;

// redis连接设定
$config = array(
    &#39;host&#39; => &#39;localhost&#39;,
    &#39;port&#39; => 6379,
    &#39;index&#39; => 0,
    &#39;auth&#39; => &#39;&#39;,
    &#39;timeout&#39; => 1,
    &#39;reserved&#39; => NULL,
    &#39;retry_interval&#39; => 100,
);

// 创建RedisCounter对象
$oRedisCounter = new RedisCounter($config);

// 定义保存计数的健值
$key = &#39;mycounter&#39;;

// 执行自增计数,获取当前计数,重置计数
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 &#39;RedisCounter.class.php&#39;;

// redis连接设定
$config = array(
    &#39;host&#39; => &#39;localhost&#39;,
    &#39;port&#39; => 6379,
    &#39;index&#39; => 0,
    &#39;auth&#39; => &#39;&#39;,
    &#39;timeout&#39; => 1,
    &#39;reserved&#39; => NULL,
    &#39;retry_interval&#39; => 100,
);

// 创建RedisCounter对象
$oRedisCounter = new RedisCounter($config);

// 定义保存计数的健值
$key = &#39;mytestcounter&#39;;

// 执行自增计数并返回自增后的计数,记录入临时文件
file_put_contents(&#39;/tmp/mytest_result.log&#39;, $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中文网其它相关文章!

智能AI问答
PHP中文网智能助手能迅速回答你的编程问题,提供实时的代码和解决方案,帮助你解决各种难题。不仅如此,它还能提供编程资源和学习指导,帮助你快速提升编程技能。无论你是初学者还是专业人士,AI智能助手都能成为你的可靠助手,助力你在编程领域取得更大的成就。
来源:CSDN网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
关于CSS思维导图的课件在哪? 课件
凡人来自于2024-04-16 10:10:18
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号