In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >
Share
Shulou(Shulou.com)06/01 Report--
Today, the editor shares with you the three ways to achieve current limitation in redis. I believe many people don't know much about it. In order to make you understand better, I summarized the following contents for you. Let's look down together. I'm sure you'll get something.
The first: the operation of setnx based on Redis
When we use Redis's distributed lock, we all know that we rely on the instructions of setnx. During the operation of CAS (Compare and swap), we also set the expiration practice (expire) for the specified key. The main purpose of our current limit is to have and only N requests per unit time to access my code program. So relying on setnx can easily do this function.
For example, if we need to limit 20 requests within 10 seconds, we can set the expiration time 10 when we setnx. When the number of setnx requests reaches 20, the current limit will be achieved. The code is relatively simple and there is no need to show it.
Of course, this approach has many disadvantages. For example, when counting 1-10 seconds, it is impossible to count within 2-11 seconds. If we need to count M requests within N seconds, then we need to keep N key in our Redis and so on.
The second kind: Redis-based data structure zset
In fact, the most important thing involved in current restriction is the sliding window, which also mentions how 1-10 becomes 2-11. In fact, both the starting value and the end value are + 1.
And we can easily implement this function if we use the list data structure of Redis.
We can make the request into an zset array. When each request comes in, the value remains unique and can be generated by UUID, while the score can be represented by the current timestamp, because score can be used to calculate the number of requests within the current timestamp. And the zset data structure also provides a range method that allows us to easily get the number of requests in two timestamps.
The code is as follows
Public Response limitFlow () {Long currentTime = new Date (). GetTime (); System.out.println (currentTime); if (redisTemplate.hasKey ("limit")) {Integer count = redisTemplate.opsForZSet (). RangeByScore ("limit", currentTime-intervalTime, currentTime). Size (); / / intervalTime is the current-limiting time System.out.println (count); if (count! = null & & count > 5) {return Response.ok ("up to 5 visits per minute") }} redisTemplate.opsForZSet () .add ("limit", UUID.randomUUID () .toString (), currentTime); return Response.ok ("access successful");}
Through the above code can achieve the effect of sliding window, and can guarantee up to M requests per N seconds, the disadvantage is that the data structure of zset will become larger and larger. The way of implementation is also relatively simple.
Third: token bucket algorithm based on Redis
When it comes to current limitation, we have to mention the token bucket algorithm. Token bucket algorithm is also called bucket algorithm, which can be explained by du Niang.
The token bucket algorithm refers to the input rate and the output rate. When the output rate is greater than the input rate, then the traffic limit is exceeded.
In other words, each time we visit a request, we can get a token from Redis. If we get a token, it means we are within the limit, while if we do not get it, the result is the opposite.
With the above ideas, we can easily do this code in combination with Redis's List data structure.
Rely on List's leftPop to get tokens
/ output token public Response limitFlow2 (Long id) {Object result = redisTemplate.opsForList () .leftPop ("limit_list"); if (result = = null) {return Response.ok ("no token in the current token bucket");} return Response.ok (articleDescription2);}
Then rely on the scheduled task of Java to regularly rightPush tokens in List. Of course, tokens also need to be unique, so I still use UUID to generate them here.
/ / add UUID to the token bucket at the rate of / / 10s, only to ensure the uniqueness @ Scheduled (fixedDelay = 10000token initialDelay = 0) public void setIntervalTimeTask () {redisTemplate.opsForList () .rightPush ("limit_list", UUID.randomUUID () .toString ());}
To sum up, it is not very difficult to implement the code at the beginning. For these current-limiting methods, we can add the above code to AOP or filter to limit the flow of the interface and ultimately protect your website.
Redis actually has many other uses, and its role is not just caching, distributed locking. His data structure is not just String,Hash,List,Set,Zset. If you are interested, you can follow up on his GeoHash algorithm; BitMap,HLL and Bloom filter data (added after Redis4.0, you can install redislabs/rebloom directly with Docker) structure.
This is the end of the three current-limiting methods of redis. I hope the above content can be of certain reference value to everyone and can be put into practice. If you like this article, you might as well share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.