關於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['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 ?>
輸出:
#0 1 11 1 0
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.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中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

熱門話題

PHP的未來將通過適應新技術趨勢和引入創新特性來實現:1)適應云計算、容器化和微服務架構,支持Docker和Kubernetes;2)引入JIT編譯器和枚舉類型,提升性能和數據處理效率;3)持續優化性能和推廣最佳實踐。

PHP和Python各有優勢,選擇應基於項目需求。 1.PHP適合web開發,語法簡單,執行效率高。 2.Python適用於數據科學和機器學習,語法簡潔,庫豐富。

Redis集群模式通過分片將Redis實例部署到多個服務器,提高可擴展性和可用性。搭建步驟如下:創建奇數個Redis實例,端口不同;創建3個sentinel實例,監控Redis實例並進行故障轉移;配置sentinel配置文件,添加監控Redis實例信息和故障轉移設置;配置Redis實例配置文件,啟用集群模式並指定集群信息文件路徑;創建nodes.conf文件,包含各Redis實例的信息;啟動集群,執行create命令創建集群並指定副本數量;登錄集群執行CLUSTER INFO命令驗證集群狀態;使

PHP不是在消亡,而是在不斷適應和進化。 1)PHP從1994年起經歷多次版本迭代,適應新技術趨勢。 2)目前廣泛應用於電子商務、內容管理系統等領域。 3)PHP8引入JIT編譯器等功能,提升性能和現代化。 4)使用OPcache和遵循PSR-12標準可優化性能和代碼質量。

使用 Redis 指令需要以下步驟:打開 Redis 客戶端。輸入指令(動詞 鍵 值)。提供所需參數(因指令而異)。按 Enter 執行指令。 Redis 返迴響應,指示操作結果(通常為 OK 或 -ERR)。

啟動 Redis 服務器的步驟包括:根據操作系統安裝 Redis。通過 redis-server(Linux/macOS)或 redis-server.exe(Windows)啟動 Redis 服務。使用 redis-cli ping(Linux/macOS)或 redis-cli.exe ping(Windows)命令檢查服務狀態。使用 Redis 客戶端,如 redis-cli、Python 或 Node.js,訪問服務器。

使用Redis進行鎖操作需要通過SETNX命令獲取鎖,然後使用EXPIRE命令設置過期時間。具體步驟為:(1) 使用SETNX命令嘗試設置一個鍵值對;(2) 使用EXPIRE命令為鎖設置過期時間;(3) 當不再需要鎖時,使用DEL命令刪除該鎖。

要從 Redis 讀取隊列,需要獲取隊列名稱、使用 LPOP 命令讀取元素,並處理空隊列。具體步驟如下:獲取隊列名稱:以 "queue:" 前綴命名,如 "queue:my-queue"。使用 LPOP 命令:從隊列頭部彈出元素並返回其值,如 LPOP queue:my-queue。處理空隊列:如果隊列為空,LPOP 返回 nil,可先檢查隊列是否存在再讀取元素。
