關於php 基於redis計數器類別的詳解

jacklove
發布: 2023-03-30 20:48:02
原創
1716 人瀏覽過

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

<?phpRequire &#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; // 0echo $oRedisCounter->incr($key).PHP_EOL; // 1echo $oRedisCounter->incr($key, 10).PHP_EOL; // 11echo $oRedisCounter->reset($key).PHP_EOL; // 1echo $oRedisCounter->get($key).PHP_EOL; // 0 ?>
登入後複製

輸出:

#
0
1
11
1
0
登入後複製

2.並發呼叫計數器,檢查計數唯一性

測試程式碼如下:

<?phpRequire &#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.3Server Hostname:        localhost
Server Port:            80Document Path:          /test.php
Document Length:        0 bytesConcurrency Level:      15Time taken for tests:   0.173 secondsComplete requests:      150Failed requests:        0Total transferred:      24150 bytesHTML transferred:       0 bytesRequests 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   maxConnect:        0    0   0.2      0       1Processing:     3   16   3.2     16      23Waiting:        3   16   3.2     16      23Total:          4   16   3.1     17      23Percentage 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計數器類別的相關內容,更多相關知識請關注php中文網。 #########相關推薦:#########詳解php 檢查是否符合指定時間段的方法##############如何JS取得訪問裝置資訊的方法############mysql5.7匯出資料提示--secure-file-priv選項問題的解決方法########

以上是關於php 基於redis計數器類別的詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!