In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "Springboot how to use redis for api anti-brush current limiting", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let Xiaobian take you to learn "Springboot how to use redis for api anti-brush current limit"!
API current limiting scenarios
The need for current limiting arises in many common scenarios
Second-kill activities, some people use software malicious swiping to grab goods, need to limit the current to prevent the machine from participating in the activity. An api is widely called by various systems, seriously consuming network, memory and other resources. It is necessary to reasonably limit the current to Taobao to obtain the interface of the city where the ip is located. Weixin Official Accounts identify WeChat users and other development interfaces. When it is provided to users for free, it needs to limit the current. The interface with more real-time and accuracy needs to pay.
api current limiting actual combat
First of all, we write the annotation class AccessLimit. It is more elegant and convenient to use annotations to cap the flow of methods! The three parameters represent valid time, maximum access times and whether login is required, which can be understood as the maximum access maxCount times in seconds.
import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)public @interface AccessLimit { int seconds(); int maxCount(); boolean needLogin() default true;}
Current Limiting Ideas
The path:ip is used as a key, and the number of visits is value. The unique identification of a user's request is determined at each visit. Whether the key exists or not is judged. If the number of visits exceeds the limit, the response should be returned. msg: The request is too frequent. Show it to the front end.
import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;import org.springframework.web.method.HandlerMethod;import org.springframework.web.servlet.HandlerInterceptor;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;@Componentpublic class AccessLimtInterceptor implements HandlerInterceptor { @Autowired private RedisService redisService;@Override public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (handler instanceof HandlerMethod) { HandlerMethod hm =(HandlerMethod) handler; AccessLimit accessLimit = hm.getMethodAnnotation (AccessLimit.class); if (null == accessLimit) { return true; } int seconds = accessLimit.seconds(); int maxCount = accessLimit.maxCount(); boolean needLogin = accessLimit.needLogin(); if (needLogin) { //Determine whether to log in} String key = request.getContextPath() + ":" + request.getServletPath() + ":" + ip ; Integer count = redisService.get(key); if (null == count|| -1 == count) { redisService.set(key, 1); redisService.expire(seconds); return true; } if (count
< maxCount) { redisService.inCr(key); return true; } if (count >= maxCount) {// response return json Request too frequent Please try again later return false; } } return true; }}
Register interceptors and configure intercept paths and non-intercept paths
import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.InterceptorRegistry;import org. springframework. web. servlet. config.annotation.WebMvcConfigurer;// extends WebMvcConfigurerAdapter Obsolete, java 8 can be inherited directly @ ConfigurationConfig public class Intercepterimplements WebMvcConfigurer { @Autowired private AccessLimtInterceptor accessLimtInterceptor;@Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(accessLimtInterceptor) .addPathPatterns("/intercept path") .excludePathPatterns("/not intercepted path usually login or home page"); }}
The annotation @AccessLimit can be used directly on methods in the Controller layer
import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RestController@RequestMapping("test")public class TestControler { @GetMapping("accessLimit") @AccessLimit(seconds = 3, maxCount = 10) public String testAccessLimit() { //xxxx return ""; }}
At this point, I believe everyone has a deeper understanding of "Springboot how to use redis for api anti-brush current limiting", so let's actually operate it! Here is the website, more related content can enter the relevant channels for inquiry, pay attention to us, continue to learn!
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.