In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-09-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
Editor to share with you how to achieve Java interface current limit, I hope you will learn something after reading this article, let's discuss it together!
RateLimiter
Google open source toolkit Guava provides a current-limiting tool class RateLimiter, which is implemented based on token bucket algorithm.
1.maven dependence: com.google.guava guava 27.1-jre2. Custom annotation import java.lang.annotation.*;import java.util.concurrent.TimeUnit;/** * token bucket annotation implementation * / @ Target ({ElementType.METHOD}) @ Retention (RetentionPolicy.RUNTIME) @ Documentedpublic @ interface RequestLimiter {/ * create tokens per second. Default: 10 * / double QPS () token 10D / * * get token wait timeout default: 500 * / long timeout () default 500; / * timeout unit default: millisecond * / TimeUnit timeunit () default TimeUnit.MILLISECONDS; / * unable to get token return message * / String msg () default "Please try again later!";} 3. Interceptor import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONObject;import com.google.common.util.concurrent.RateLimiter;import com.tiam.panshi.cloud.appback.annotation.RequestLimiter;import lombok.extern.slf4j.Slf4j;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;import java.io.PrintWriter;import java.util.Map;import java.util.concurrent.ConcurrentHashMap @ Component@Slf4jpublic class RequestLimitingInterceptor implements HandlerInterceptor {private final Map rateLimiterMap = new ConcurrentHashMap (); @ Override public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) {/ / you can pull out and define the return information JSONObject jsonObject = new JSONObject (); jsonObject.put ("10001", "loading with life, please try again later") Try {if (handler instanceof HandlerMethod) {HandlerMethod handlerMethod = (HandlerMethod) handler; RequestLimiter rateLimit = handlerMethod.getMethodAnnotation (RequestLimiter.class); / / determine whether there is an annotation if (rateLimit! = null) {/ / get request url String url = request.getRequestURI () RateLimiter rateLimiter; / / determine whether there is a created token bucket in the map collection if (! rateLimiterMap.containsKey (url)) {/ / create a token bucket, and put the token rateLimiter = RateLimiter.create (rateLimit.QPS ()) in the bucket with n r _ packs. RateLimiterMap.put (url, rateLimiter);} rateLimiter = rateLimiterMap.get (url); / / get token boolean acquire = rateLimiter.tryAcquire (rateLimit.timeout (), rateLimit.timeunit ()) If (acquire) {/ / token obtained successfully return true;} else {log.warn ("request is restricted, url: {}", request.getServletPath ()); makeResult (response, renderJson (jsonObject)) Return false;} return true;} catch (Exception var6) {var6.printStackTrace (); makeResult (response, renderJson (jsonObject)); return false } private void makeResult (HttpServletResponse response, JSONObject jo) {response.setContentType ("application/json; charset=utf-8"); response.setCharacterEncoding ("UTF-8"); try (PrintWriter out = response.getWriter ()) {out.append (jo.toJSONString ());} catch (Exception e) {e.printStackTrace () } private JSONObject renderJson (Object o) {return JSONObject.parseObject (JSON.toJSONString (o));} 4. Register interceptor @ Configurationpublic class WebMvcConfig extends WebMvcConfigurationSupport {/ * request current limit interceptor * / @ Autowired protected RequestLimitingInterceptor requestLimitingInterceptor; @ Override public void addInterceptors (InterceptorRegistry registry) {/ / request current limit registry.addInterceptor (requestLimitingInterceptor) .addPathPatterns ("/ * *");}} 5. Configure @ RequestLimiter on the interface (QPS = 5D, timeout = 200, timeunit = TimeUnit.MILLISECONDS,msg = "loading with life, please try again later") @ GetMapping ("/ test") @ ResponseBodypublic String test () {return ";} after reading this article, I believe you have some understanding of" how Java implements interface current limiting ". If you want to know more about it, welcome to follow the industry information channel. Thank you for reading!
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.
The market share of Chrome browser on the desktop has exceeded 70%, and users are complaining about
The world's first 2nm mobile chip: Samsung Exynos 2600 is ready for mass production.According to a r
A US federal judge has ruled that Google can keep its Chrome browser, but it will be prohibited from
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
This article mainly introduces how to achieve the wave effect of HTML, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor with you to understand. 50.0%
Wechat
About us
Contact us
Product review
car news
thenatureplanet
More Form oMedia:
AutoTimes.
Bestcoffee.
SL News.
Jarebook.
Coffee Hunters.
Sundaily.
Modezone.
NNB.
Coffee.
Game News.
FrontStreet.
GGAMEN
© 2024 shulou.com SLNews company. All rights reserved.