Redis is an open source log-type Key-Value database written in ANSI C language, supports network, can be memory-based and persistent, and provides APIs in multiple languages.
This article will use its incr(increment), get(get), delete(clear) methods to implement the counter kind.
1.Redis counter class code and demonstration example
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 ?>
Output:
0 1 11 1 0
2. Concurrently call the counter and check the uniqueness of the count
The test code is as follows:
<?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);?>
To test concurrent execution, we use the ab tool for testing, and set the execution 150 times, 15 concurrency.
ab -c 15 -n 150 http://localhost/test.php
Execution results:
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)
Check whether the count is unique
生成的总计数 wc -l /tmp/mytest_result.log 150 /tmp/mytest_result.log生成的唯一计数 sort -u /tmp/mytest_result.log | wc -l 150
You can see that in the case of concurrent calls, The resulting count is also guaranteed to be unique.
This article explains the relevant content of PHP based on the redis counter class. For more related knowledge, please pay attention to the PHP Chinese website.
Related recommendations:
Detailed explanation of how to check whether PHP matches the specified time period
How to get access with JS Device information method
mysql5.7 export data prompt --secure-file-priv option problem solution
The above is the detailed content of Detailed explanation of PHP-based redis counter class. For more information, please follow other related articles on the PHP Chinese website!

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php判断有没有小数点的方法:1、使用“strpos(数字字符串,'.')”语法,如果返回小数点在字符串中第一次出现的位置,则有小数点;2、使用“strrpos(数字字符串,'.')”语句,如果返回小数点在字符串中最后一次出现的位置,则有。

方法:1、用“str_replace(" ","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\ \;||\xc2\xa0)/","其他字符",$str)”语句。

在PHP中,可以利用implode()函数的第一个参数来设置没有分隔符,该函数的第一个参数用于规定数组元素之间放置的内容,默认是空字符串,也可将第一个参数设置为空,语法为“implode(数组)”或者“implode("",数组)”。

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 Chinese version
Chinese version, very easy to use

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version
Visual web development tools
