PHP + redis solves practical problem 1: order flow restriction


1. Each issue of this series of articles will solve a practical redis problem

2. Questions in each issue will be selected from the comments in each issue

3. Questions are limited to those related to redis. If I am interested in other questions, I will not rule out opening up a new series

4. I often use PHP, so the solution is mainly PHP

5. When there are no appropriate questions in the comments, I will write my own questions

Problem Description:

This is the first issue, so I can only write my own questions

How to use redis to limit the flow of orders, such as allowing n accesses per M seconds


<? php

Code interpretation:

  1. Model the time so that each key name$timeIntervalUpdate every second
  2. incr()Method automatically increments the value of the key. If the key does not exist, first create a value of0The key increases automatically
  3. According to the principle of self increment, the number under the same key name isNThe value returned from this increment isN
  4. Key name per$timeIntervalIt is updated every 2 seconds, so the key is created$timeInterval+1Seconds later, the key is no longer valuable

Above, welcomeput questions toerror correctionsupplementoptimization

This work adoptsCC agreement, reprint must indicate the author and the link to this article