springboot結合ehcache防止惡意刷新請求的實現(xiàn)
說明
我們在把開發(fā)好的網(wǎng)站上線之前一定要考慮到別人惡意刷新你的網(wǎng)頁這種情況,最大限度的去限制他們。否則往往這將搞垮你的應用服務器,想象一下某個惡意用戶利用眾多肉雞在1分鐘內請求你網(wǎng)頁幾十萬次是個什么情形?
部分內容參考網(wǎng)絡。
要達到什么效果?
我限制請求的用戶,根據(jù)來訪IP去記錄它N分鐘之內請求單一網(wǎng)頁的次數(shù),如果超過N次我就把這個IP添加到緩存黑名單并限制它3小時之內無法訪問類型網(wǎng)頁。
效果圖
1分鐘內請求單網(wǎng)頁超過15次就被加入黑名單,凍結3小時!

開發(fā)步驟
- 采用AOP+Ehcache方式。(Redis也可以)
- AOP用于攔截和邏輯判斷,Ehcache負責計數(shù)和緩存。
配置ehcache
略。
創(chuàng)建注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
@Order(Ordered.HIGHEST_PRECEDENCE)
public @interface RequestLimit {
/**
* 允許訪問的最大次數(shù)
*/
int count() default 15;
/**
* 時間段,單位為毫秒,默認值一分鐘
*/
long time() default 1000*60;
}
創(chuàng)建AOP
@Aspect
@Component
public 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; // 訪問次數(shù)
// 判斷是否在黑名單
if (ehcacheUtil.contains("countcache",blackKey)){
throw new RequestLimitException();
}else{
// 判斷是否已存在訪問計數(shù)
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 + "]超過了限定的次數(shù)[" + limit.count() + "]");
// 加入黑名單
ehcacheUtil.put("countcache",blackKey,"badguy");
throw new RequestLimitException();
}
}
}
}catch (RequestLimitException e){
throw e;
}catch (Exception e){
logger.error("發(fā)生異常",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防止惡意刷新請求的實現(xiàn)的文章就介紹到這了,更多相關springboot 防止惡意刷新內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Java編程實現(xiàn)beta分布的采樣或抽樣實例代碼
這篇文章主要介紹了Java編程實現(xiàn)beta分布的采樣或抽樣實例,分享了相關代碼示例,小編覺得還是挺不錯的,具有一定借鑒價值,需要的朋友可以參考下2018-01-01
Java加密解密工具(適用于JavaSE/JavaEE/Android)
這篇文章主要介紹了Java加密解密工具,適用于JavaSE/JavaEE/Android,感興趣的小伙伴們可以參考一下2016-04-04
SpringBoot多數(shù)據(jù)源配置的全過程記錄
在用SpringBoot開發(fā)項目時,隨著業(yè)務量的擴大,我們通常會進行數(shù)據(jù)庫拆分或是引入其他數(shù)據(jù)庫,從而我們需要配置多個數(shù)據(jù)源,下面這篇文章主要給大家介紹了關于SpringBoot多數(shù)據(jù)源配置的相關資料,需要的朋友可以參考下2021-11-11
mybatis多層嵌套resultMap及返回自定義參數(shù)詳解
這篇文章主要介紹了mybatis多層嵌套resultMap及返回自定義參數(shù)詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-12-12

