php 基於redis計數器類

來源:互聯網
上載者:User

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

<?phpRequire '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; // 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 ?>

輸出:

011110


2.並發調用計數器,檢查計數唯一性

測試代碼如下:

<?phpRequire '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.phpThis 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).....doneServer Software:        nginx/1.6.3Server Hostname:        localhostServer Port:            80Document Path:          /test.phpDocument 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] receivedConnection 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

可以看到在並發調用的情況下,產生的計數也保證唯一。


源碼下載地址:點擊查看

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.