溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

PHP中怎么利用redis定義一個計(jì)數(shù)器類

發(fā)布時間:2021-06-23 15:50:22 來源:億速云 閱讀:140 作者:Leah 欄目:開發(fā)技術(shù)

PHP中怎么利用redis定義一個計(jì)數(shù)器類,相信很多沒有經(jīng)驗(yàn)的人對此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個問題。

1.Redis計(jì)數(shù)器類代碼及演示實(shí)例

RedisCounter.class.php

<?php
/**

 * Descripton:
 * php基于Redis實(shí)現(xiàn)自增計(jì)數(shù),主要使用redis的incr方法,并發(fā)執(zhí)行時保證計(jì)數(shù)自增唯一。
 *
 * Func:
 * public incr  執(zhí)行自增計(jì)數(shù)并獲取自增后的數(shù)值
 * public get   獲取當(dāng)前計(jì)數(shù)
 * public reset  重置計(jì)數(shù)
 * private connect 創(chuàng)建redis連接
 */
class RedisCounter{ // class start
  private $_config;
  private $_redis;
  /**
   * 初始化
   * @param Array $config redis連接設(shè)定
   */
  public function __construct($config){
    $this->_config = $config;
    $this->_redis = $this->connect();
  }
  /**
   * 執(zhí)行自增計(jì)數(shù)并獲取自增后的數(shù)值
   * @param String $key 保存計(jì)數(shù)的鍵值
   * @param Int  $incr 自增數(shù)量,默認(rèn)為1
   * @return Int
   */
  public function incr($key, $incr=1){
    return intval($this->_redis->incr($key, $incr));
  }
  /**
   * 獲取當(dāng)前計(jì)數(shù)
   * @param String $key 保存計(jì)數(shù)的健值
   * @return Int
   */
  public function get($key){
    return intval($this->_redis->get($key));
  }
  /**
   * 重置計(jì)數(shù)
   * @param String $key 保存計(jì)數(shù)的健值
   * @return Int
   */
  public function reset($key){
    return $this->_redis->delete($key);
  }
  /**
   * 創(chuàng)建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連接設(shè)定
$config = array(
  'host' => 'localhost',
  'port' => 6379,
  'index' => 0,
  'auth' => '',
  'timeout' => 1,
  'reserved' => NULL,
  'retry_interval' => 100,
);
// 創(chuàng)建RedisCounter對象
$oRedisCounter = new RedisCounter($config);
// 定義保存計(jì)數(shù)的健值
$key = 'mycounter';
// 執(zhí)行自增計(jì)數(shù),獲取當(dāng)前計(jì)數(shù),重置計(jì)數(shù)
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.并發(fā)調(diào)用計(jì)數(shù)器,檢查計(jì)數(shù)唯一性

測試代碼如下:

<?php
Require 'RedisCounter.class.php';
// redis連接設(shè)定
$config = array(
  'host' => 'localhost',
  'port' => 6379,
  'index' => 0,
  'auth' => '',
  'timeout' => 1,
  'reserved' => NULL,
  'retry_interval' => 100,
);
// 創(chuàng)建RedisCounter對象
$oRedisCounter = new RedisCounter($config);
// 定義保存計(jì)數(shù)的健值
$key = 'mytestcounter';
// 執(zhí)行自增計(jì)數(shù)并返回自增后的計(jì)數(shù),記錄入臨時文件
file_put_contents('/tmp/mytest_result.log', $oRedisCounter->incr($key).PHP_EOL, FILE_APPEND);
?>

測試并發(fā)執(zhí)行,我們使用ab工具進(jìn)行測試,設(shè)置執(zhí)行150次,15個并發(fā)。

ab -c 15 -n 150 http://localhost/test.php

執(zhí)行結(jié)果:

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)

檢查計(jì)數(shù)是否唯一

生成的總計(jì)數(shù)

wc -l /tmp/mytest_result.log
   150 /tmp/mytest_result.log

生成的唯一計(jì)數(shù)

sort -u /tmp/mytest_result.log | wc -l
   150

看完上述內(nèi)容,你們掌握PHP中怎么利用redis定義一個計(jì)數(shù)器類的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI