Table of Contents
2. Concurrently call the counter and check the uniqueness of the count
Home Backend Development PHP Tutorial Detailed explanation of PHP-based redis counter class

Detailed explanation of PHP-based redis counter class

Jun 08, 2018 pm 04:16 PM
php redis

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

<?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?>

Copy after login

demo.php

1

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;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 ?>

Copy after login

Output:

1

2

3

4

5

0

1

11

1

0

Copy after login

2. Concurrently call the counter and check the uniqueness of the count

The test code is as follows:

1

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);?>

Copy after login

To test concurrent execution, we use the ab tool for testing, and set the execution 150 times, 15 concurrency.

1

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

Copy after login

Execution results:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

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)

Copy after login

Check whether the count is unique

1

2

3

4

5

生成的总计数

wc -l /tmp/mytest_result.log

     150 /tmp/mytest_result.log生成的唯一计数

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

     150

Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1657
14
PHP Tutorial
1257
29
C# Tutorial
1229
24
PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP's Purpose: Building Dynamic Websites PHP's Purpose: Building Dynamic Websites Apr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP: Handling Databases and Server-Side Logic PHP: Handling Databases and Server-Side Logic Apr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

Why Use PHP? Advantages and Benefits Explained Why Use PHP? Advantages and Benefits Explained Apr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

See all articles