当前位置:网站首页>Three ways for redis to realize current limiting
Three ways for redis to realize current limiting
2022-07-01 19:12:00 【Floating across the sea】
Redis Three ways to realize current limiting
The first one is : be based on Redis Of setnx The operation of
We are using Redis When using distributed locks , We all know it depends on setnx Instructions , stay CAS(Compare and swap) During the operation of , At the same time, give the designated key Set up expired practices (expire), Our main purpose in limiting current is to , Yes and no N The number of requests that can access my code program . So rely on setnx You can easily do this function .
For example, we need to be in 10 Seconds limit 20 A request , So we're in setnx You can set the expiration time when 10, When requested setnx The number of 20 Then the current limiting effect is achieved . The code is relatively simple, so I won't show it .
Of course, there are many disadvantages of this approach , For example, when Statistics 1-10 seconds , Unable to statistics 2-11 In seconds , If you need statistics N Seconds M A request , So our Redis You need to keep N individual key Problems, etc.
The second kind : be based on Redis Data structure of zset
In fact, the most important part of current limiting is sliding window , As mentioned above 1-10 How to become 2-11. In fact, the starting value and the end value are respectively +1 that will do .
And if we use Redis Of list The data structure can easily realize this function
We can make the request into a zset Array , When every request comes in ,value Keep it unique , It can be used UUID Generate , and score Can be represented by the current timestamp , because score We can use it to calculate the number of requests within the current timestamp . and zset Data structures also provide range Methods make it easy for us to get 2 How many requests are in 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 time of current limiting
System.out.println(count);
if (count != null && count > 5) {
return Response.ok(" At most, you can only access 5 Time ");
}
}
redisTemplate.opsForZSet().add("limit",UUID.randomUUID().toString(),currentTime);
return Response.ok(" Successful visit ");
}
The third kind of : be based on Redis The token bucket algorithm of
When it comes to current limiting, we have to mention the token bucket algorithm . For details, please refer to Du Niang's explanation [ Token bucket algorithm ][Link 1]
The token bucket algorithm refers to input rate and output rate , When the output rate is greater than the input rate , Then the flow limit is exceeded .
That is, every time we visit a request , It can be downloaded from Redis Get a token from , If you get the token , That means the limit is not exceeded , And if you can't get it , The result is the opposite .
Rely on the above ideas , We can combine Redis Of List Data structure can easily do such code , It's just a simple implementation
rely on List Of leftPop To get the token
// Output token
public Response limitFlow2(Long id){
Object result = redisTemplate.opsForList().leftPop("limit_list");
if(result == null){
return Response.ok(" There is no token in the current token bucket ");
}
return Response.ok(articleDescription2);
}
Rely on Java Scheduled tasks for , Go regularly List in rightPush token , Of course, tokens also need uniqueness , So I still use UUID Generated
// 10S Add... To token bucket at the rate of UUID, Just to guarantee uniqueness
@Scheduled(fixedDelay = 10_000,initialDelay = 0)
public void setIntervalTimeTask(){
redisTemplate.opsForList().rightPush("limit_list",UUID.randomUUID().toString());
}
边栏推荐
- What designs are needed in the architecture to build a general monitoring and alarm platform
- ES6数组去重的三个简单办法
- Three. JS learning - basic operation of camera (learn from)
- 11. Users, groups, and permissions (1)
- AI 训练速度突破摩尔定律;宋舒然团队获得RSS 2022最佳论文奖
- 【直播预约】数据库OBCP认证全面升级公开课
- Why do independent website sellers start to do social media marketing? The original customer conversion rate can be improved so much!
- Excel之VBA简单宏编程
- [AGC] how to solve the problem that the local display of event analysis data is inconsistent with that in AGC panel?
- Games202 operation 0 - environment building process & solving problems encountered
猜你喜欢

精耕渠道共谋发展 福昕携手伟仕佳杰开展新产品培训大会

洞态在某互联⽹⾦融科技企业的最佳落地实践

SuperOptiMag 超导磁体系统 — SOM、SOM2 系列

bean的生命周期核心步骤总结

The market value evaporated by 74billion yuan, and the big man turned and entered the prefabricated vegetables

Altair HyperWorks 2022软件安装包和安装教程

kubernetes命令入门(namespaces,pods)

前4A高管搞代运营,拿下一个IPO

小红书上的爱情买卖

Write an open source, convenient and fast database document query and generation tool with WPF
随机推荐
市值蒸发740亿,这位大佬转身杀入预制菜
Lumiprobe lumizol RNA extraction reagent solution
AppGallery Connect场景化开发实战—图片存储分享
Create your own NFT collections and publish a Web3 application to show them (Introduction)
R language uses follow up of epidisplay package Plot function visualizes the longitudinal follow-up map of multiple ID (case) monitoring indicators, and uses n.of The lines parameter specifies the num
Lumiprobe 活性染料丨吲哚菁绿说明书
R language uses the DOTPLOT function of epidisplay package to visualize the frequency of data points in different intervals in the form of point graph, and uses PCH parameters to customize the shape o
Salesmartly has some tricks for Facebook chat!
GameFramework食用指南
用WPF写一款开源方便、快捷的数据库文档查询、生成工具
透过华为军团看科技之变(六):智慧公路
解决方案:可以ping别人,但是别人不能ping我
毕业季 | 华为专家亲授面试秘诀:如何拿到大厂高薪offer?
Viewing technological changes through Huawei Corps (VI): smart highway
Solution: you can ping others, but others can't ping me
Lake Shore 连续流动低温恒温器传输线
Leetcode-141 circular linked list
Taiaisu M source code construction, peak store app premium consignment source code sharing
助力数字经济发展,夯实数字人才底座—数字人才大赛在昆成功举办
数据仓库(四)之ETL开发