小編這次要給大家分享的是如何實現(xiàn)Springboot過濾器禁止ip頻繁訪問功能,文章內(nèi)容豐富,感興趣的小伙伴可以來了解一下,希望大家閱讀完這篇文章之后能夠有所收獲。
為南江等地區(qū)用戶提供了全套網(wǎng)頁設(shè)計制作服務(wù),及南江網(wǎng)站建設(shè)行業(yè)解決方案。主營業(yè)務(wù)為做網(wǎng)站、網(wǎng)站設(shè)計、南江網(wǎng)站設(shè)計,以傳統(tǒng)方式定制建設(shè)網(wǎng)站,并提供域名空間備案等一條龍服務(wù),秉承以專業(yè)、用心的態(tài)度為用戶提供真誠的服務(wù)。我們深信只要達到每一位用戶的要求,就會得到認可,從而選擇與我們長期合作。這樣,我們也可以走得更遠!
在開發(fā) Web 項目的時候,經(jīng)常需要過濾器來處理一些請求,包括字符集轉(zhuǎn)換什么的,記錄請求日志什么的等等。在之前的 Web 開發(fā)中,我們習慣把過濾器配置到 web.xml 中,但是在 SpringBoot 中,兵沒有這個配置文件,該如何操作呢?
1.編寫一個過濾器:
import lombok.extern.slf4j.Slf4j; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Iterator; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; @Slf4j @WebFilter(urlPatterns="/dyflight/*") public class IpFilter implements Filter{ /** * 默認限制時間(單位:ms)3600000,3600(s), */ private static final long LIMITED_TIME_MILLIS = 10 * 1000; /** * 用戶連續(xù)訪問最高閥值,超過該值則認定為惡意操作的IP,進行限制 */ private static final int LIMIT_NUMBER = 5; /** * 用戶訪問最小安全時間,在該時間內(nèi)如果訪問次數(shù)大于閥值,則記錄為惡意IP,否則視為正常訪問 */ private static final int MIN_SAFE_TIME = 5000; private FilterConfig config; @Override public void init(FilterConfig filterConfig) throws ServletException { this.config = filterConfig; //設(shè)置屬性filterConfig } /* (non-Javadoc) * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain) */ @SuppressWarnings("unchecked") @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; ServletContext context = config.getServletContext(); // 獲取限制IP存儲器:存儲被限制的IP信息 //MaplimitedIpMap = (Map ) context.getAttribute("limitedIpMap"); ConcurrentHashMap limitedIpMap = (ConcurrentHashMap ) context.getAttribute("limitedIpMap"); // 過濾受限的IP filterLimitedIpMap(limitedIpMap); // 獲取用戶IP String ip = IPUtil.getRemoteIpAddr(request); System.err.println("ip:"+ip); // 判斷是否是被限制的IP,如果是則跳到異常頁面 if (isLimitedIP(limitedIpMap, ip)) { long limitedTime = limitedIpMap.get(ip) - System.currentTimeMillis(); // 剩余限制時間(用為從毫秒到秒轉(zhuǎn)化的一定會存在些許誤差,但基本可以忽略不計) request.setAttribute("remainingTime", ((limitedTime / 1000) + (limitedTime % 1000 > 0 ? 1 : 0))); System.err.println("ip訪問過于頻繁:"+ip); throw new RuntimeException("ip訪問過于頻繁"); } // 獲取IP存儲器 ConcurrentHashMap ipMap = (ConcurrentHashMap ) context.getAttribute("ipMap"); // 判斷存儲器中是否存在當前IP,如果沒有則為初次訪問,初始化該ip // 如果存在當前ip,則驗證當前ip的訪問次數(shù) // 如果大于限制閥值,判斷達到閥值的時間,如果不大于[用戶訪問最小安全時間]則視為惡意訪問,跳轉(zhuǎn)到異常頁面 if (ipMap.containsKey(ip)) { Long[] ipInfo = ipMap.get(ip); ipInfo[0] = ipInfo[0] + 1; log.debug("當前第[" + (ipInfo[0]) + "]次訪問"); if (ipInfo[0] > LIMIT_NUMBER) { Long ipAccessTime = ipInfo[1]; Long currentTimeMillis = System.currentTimeMillis(); log.debug("ip訪問過于頻繁:currentTimeMillis: "+currentTimeMillis+" - ipAccessTime:"+ipAccessTime+" : " + (currentTimeMillis - ipAccessTime) + "<="+ MIN_SAFE_TIME); if (currentTimeMillis - ipAccessTime <= MIN_SAFE_TIME) { limitedIpMap.put(ip, currentTimeMillis + LIMITED_TIME_MILLIS); request.setAttribute("remainingTime", LIMITED_TIME_MILLIS); log.debug("ip訪問過于頻繁:LIMITED_TIME_MILLIS:"+LIMITED_TIME_MILLIS); log.debug("ip訪問過于頻繁:"+ip); throw new RuntimeException("ip訪問過于頻繁"); } else { initIpVisitsNumber(ipMap, ip); } } } else { initIpVisitsNumber(ipMap, ip); System.out.println("您首次訪問該網(wǎng)站"); } context.setAttribute("ipMap", ipMap); chain.doFilter(request, response); } @Override public void destroy() { // TODO Auto-generated method stub } /** * @Description 過濾受限的IP,剔除已經(jīng)到期的限制IP * @param limitedIpMap */ private void filterLimitedIpMap(ConcurrentHashMap limitedIpMap) { if (limitedIpMap == null) { return; } Set keys = limitedIpMap.keySet(); Iterator keyIt = keys.iterator(); long currentTimeMillis = System.currentTimeMillis(); while (keyIt.hasNext()) { long expireTimeMillis = limitedIpMap.get(keyIt.next()); log.debug("expireTimeMillis <= currentTimeMillis:"+ expireTimeMillis+" <="+ currentTimeMillis); if (expireTimeMillis <= currentTimeMillis) { keyIt.remove(); } } } /** * @Description 是否是被限制的IP * @param limitedIpMap * @param ip * @return true : 被限制 | false : 正常 */ private boolean isLimitedIP(ConcurrentHashMap limitedIpMap, String ip) { if (limitedIpMap == null || ip == null) { // 沒有被限制 return false; } Set keys = limitedIpMap.keySet(); Iterator keyIt = keys.iterator(); while (keyIt.hasNext()) { String key = keyIt.next(); if (key.equals(ip)) { // 被限制的IP return true; } } return false; } /** * 初始化用戶訪問次數(shù)和訪問時間 * * @param ipMap * @param ip */ private void initIpVisitsNumber(ConcurrentHashMap ipMap, String ip) { Long[] ipInfo = new Long[2]; ipInfo[0] = 0L;// 訪問次數(shù) ipInfo[1] = System.currentTimeMillis();// 初次訪問時間 ipMap.put(ip, ipInfo); } }
2. 創(chuàng)建一個監(jiān)聽器:需要初始化倆個容器:
import lombok.extern.slf4j.Slf4j; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; import java.util.concurrent.ConcurrentHashMap; @Slf4j @WebListener public class MyApplicationListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) { log.debug("liting: contextInitialized"); log.debug("MyApplicationListener初始化成功"); ServletContext context = sce.getServletContext(); // IP存儲器 ConcurrentHashMapipMap = new ConcurrentHashMap<>(); context.setAttribute("ipMap", ipMap); // 限制IP存儲器:存儲被限制的IP信息 ConcurrentHashMap limitedIpMap = new ConcurrentHashMap (); context.setAttribute("limitedIpMap", limitedIpMap); log.debug("ipmap:"+ipMap.toString()+";limitedIpMap:"+limitedIpMap.toString()+"初始化成功。。。。。"); } @Override public void contextDestroyed(ServletContextEvent sce) { // TODO Auto-generated method stub } }
3.iputil
import javax.servlet.http.HttpServletRequest; import java.net.InetAddress; import java.net.UnknownHostException; public class IPUtil { public static String getRemoteIpAddr(HttpServletRequest request) { String ip = request.getHeader("x-forwarded-for"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_CLIENT_IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_X_FORWARDED_FOR"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); if("127.0.0.1".equals(ip)||"0:0:0:0:0:0:0:1".equals(ip)){ //根據(jù)網(wǎng)卡取本機配置的IP InetAddress inet=null; try { inet = InetAddress.getLocalHost(); } catch (UnknownHostException e) { e.printStackTrace(); } ip= inet.getHostAddress(); } } return ip; } }
4配置
springboot啟動類中添加過濾器和監(jiān)聽器的包掃描
@ServletComponentScan(basePackages="cn.xxx.common")
spring web.xml
過濾器
ipFilter com.xxxx.common.filter.IpFilter ipFilter /dyflight/**
監(jiān)聽器:
com.xxxx.common.Listener.MyApplicationListener
看完這篇關(guān)于如何實現(xiàn)Springboot過濾器禁止ip頻繁訪問功能的文章,如果覺得文章內(nèi)容寫得不錯的話,可以把它分享出去給更多人看到。