springboot結合ehcache防止惡意刷新請求的實現
我們在把開發好的網站上線之前一定要考慮到別人惡意刷新你的網頁這種情況,最大限度的去限制他們。否則往往這將搞垮你的應用服務器,想象一下某個惡意用戶利用眾多肉雞在1分鐘內請求你網頁幾十萬次是個什么情形?部分內容參考網絡。
要達到什么效果?我限制請求的用戶,根據來訪IP去記錄它N分鐘之內請求單一網頁的次數,如果超過N次我就把這個IP添加到緩存黑名單并限制它3小時之內無法訪問類型網頁。
效果圖1分鐘內請求單網頁超過15次就被加入黑名單,凍結3小時!
配置ehcache
略。
創建注解
@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)@Documented@Order(Ordered.HIGHEST_PRECEDENCE)public @interface RequestLimit { /** * 允許訪問的最大次數 */ int count() default 15; /** * 時間段,單位為毫秒,默認值一分鐘 */ long time() default 1000*60;}
創建AOP
@Aspect@Componentpublic class RequestLimitAspect { private static final Logger logger = LoggerFactory.getLogger(RequestLimit.class); @Autowired EhcacheUtil ehcacheUtil; @Before('within(@org.springframework.stereotype.Controller *) && @annotation(limit)') public void requestLimit(final JoinPoint joinPoint , RequestLimit limit) throws RequestLimitException { try { Object[] args = joinPoint.getArgs(); HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); String ip = IpUtil.getRemoteIp(request); String uri = request.getRequestURI().toString(); String key = 'req_'+uri+'_'+ip; String blackKey = 'black_'+ip; // 黑名單IP封鎖一段時間 int count = 0; // 訪問次數 // 判斷是否在黑名單 if (ehcacheUtil.contains('countcache',blackKey)){throw new RequestLimitException(); }else{// 判斷是否已存在訪問計數if (!ehcacheUtil.contains('limitCache',key)) { ehcacheUtil.put('limitCache',key,1);} else { count = ehcacheUtil.getInt('limitCache',key)+1; ehcacheUtil.put('limitCache',key,count); if (count > limit.count()) { logger.info('用戶IP[' + ip + ']訪問地址[' + uri + ']超過了限定的次數[' + limit.count() + ']'); // 加入黑名單 ehcacheUtil.put('countcache',blackKey,'badguy'); throw new RequestLimitException(); }} } }catch (RequestLimitException e){ throw e; }catch (Exception e){ logger.error('發生異常',e); } }}
應用aop
找到要應用的接口加上注解@RequestLimit即可。
@RequestLimit(count=10) @OperLog(operModule = '更多文章',operType = '查詢',operDesc = '查詢更多文章') @GetMapping('/more/{categoryId}') public String getMore(@PathVariable('categoryId') String categoryId, Model model, HttpServletRequest request) { // 略 }
到此這篇關于springboot結合ehcache防止惡意刷新請求的實現的文章就介紹到這了,更多相關springboot 防止惡意刷新內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章: