java ehcahce刷新_springboot结合ehcache防止恶意刷新请求的实现
說明
我們在把開發好的網站上線之前一定要考慮到別人惡意刷新你的網頁這種情況,最大限度的去限制他們。否則往往這將搞垮你的應用服務器,想象一下某個惡意用戶利用眾多肉雞在1分鐘內請求你網頁幾十萬次是個什么情形?
部分內容參考網絡。
要達到什么效果?
我限制請求的用戶,根據來訪ip去記錄它n分鐘之內請求單一網頁的次數,如果超過n次我就把這個ip添加到緩存黑名單并限制它3小時之內無法訪問類型網頁。
效果圖
1分鐘內請求單網頁超過15次就被加入黑名單,凍結3小時!
開發步驟
采用aop+ehcache方式。(redis也可以)
aop用于攔截和邏輯判斷,ehcache負責計數和緩存。
配置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
@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; // 訪問次數
// 判斷是否在黑名單
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 防止惡意刷新內容請搜索萬仟網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持萬仟網!
如您對本文有疑問或者有任何想說的,請點擊進行留言回復,萬千網友為您解惑!
總結
以上是生活随笔為你收集整理的java ehcahce刷新_springboot结合ehcache防止恶意刷新请求的实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SQLserver数据库反编译生成Hib
- 下一篇: testng.xml文件配置