SpringBoot在一定時間內限制接口請求次數的實現示例
需要用到的知識:注解、AOP、ExpiringMap(帶有有效期的映射)
我們可以自定義注解,把注解添加到我們的接口上。定義一個切面,執(zhí)行方法前去ExpiringMap查詢該IP在規(guī)定時間內請求了多少次,如超過次數則直接返回請求失敗。
需要用到的依賴
<!-- AOP依賴 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> <version>2.1.5.RELEASE</version> </dependency> <!-- Map依賴 --> <dependency> <groupId>net.jodah</groupId> <artifactId>expiringmap</artifactId> <version>0.5.8</version> </dependency>
自定義注解@LimitRequest
@Documented @Target(ElementType.METHOD) // 說明該注解只能放在方法上面 @Retention(RetentionPolicy.RUNTIME) public @interface LimitRequest { long time() default 6000; // 限制時間 單位:毫秒 int count() default 1; // 允許請求的次數 }
自定義AOP
@Aspect @Component public class LimitRequestAspect { private static ConcurrentHashMap<String, ExpiringMap<String, Integer>> book = new ConcurrentHashMap<>(); // 定義切點 // 讓所有有@LimitRequest注解的方法都執(zhí)行切面方法 @Pointcut("@annotation(limitRequest)") public void excudeService(LimitRequest limitRequest) { } @Around("excudeService(limitRequest)") public Object doAround(ProceedingJoinPoint pjp, LimitRequest limitRequest) throws Throwable { // 獲得request對象 RequestAttributes ra = RequestContextHolder.getRequestAttributes(); ServletRequestAttributes sra = (ServletRequestAttributes) ra; HttpServletRequest request = sra.getRequest(); // 獲取Map對象, 如果沒有則返回默認值 // 第一個參數是key, 第二個參數是默認值 ExpiringMap<String, Integer> uc = book.getOrDefault(request.getRequestURI(), ExpiringMap.builder().variableExpiration().build()); Integer uCount = uc.getOrDefault(request.getRemoteAddr(), 0); if (uCount >= limitRequest.count()) { // 超過次數,不執(zhí)行目標方法 return "接口請求超過次數"; } else if (uCount == 0){ // 第一次請求時,設置有效時間 // /** Expires entries based on when they were last accessed */ // ACCESSED, // /** Expires entries based on when they were created */ // CREATED; uc.put(request.getRemoteAddr(), uCount + 1, ExpirationPolicy.CREATED, limitRequest.time(), TimeUnit.MILLISECONDS); } else { // 未超過次數, 記錄加一 uc.put(request.getRemoteAddr(), uCount + 1); } book.put(request.getRequestURI(), uc); // result的值就是被攔截方法的返回值 Object result = pjp.proceed(); return result; } }
第一個靜態(tài)Map是多線程安全的Map(ConcurrentHashMap),它的key是接口對于的url,它的value是一個多線程安全且鍵值對是有有效期的Map(ExpiringMap)。
ExpiringMap的key是請求的ip地址,value是已經請求的次數。
ExpiringMap更多的使用方法可以參考:https://github.com/jhalterman/expiringmap
最后在方法上面加上@LimitRequest就行了
到此這篇關于SpringBoot在一定時間內限制接口請求次數的實現示例的文章就介紹到這了,更多相關SpringBoot 限制接口請求次數內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
在java中使用SPI創(chuàng)建可擴展的應用程序操作
這篇文章主要介紹了在java中使用SPI創(chuàng)建可擴展的應用程序操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09詳解SpringBoot+Thymeleaf 基于HTML5的現代模板引擎
本篇文章主要介紹了SpringBoot+Thymeleaf 基于HTML5的現代模板引擎,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-10-10