您好,登錄后才能下訂單哦!
小編這次要給大家分享的是如何實現Springboot過濾器禁止ip頻繁訪問功能,文章內容豐富,感興趣的小伙伴可以來了解一下,希望大家閱讀完這篇文章之后能夠有所收獲。
在開發 Web 項目的時候,經常需要過濾器來處理一些請求,包括字符集轉換什么的,記錄請求日志什么的等等。在之前的 Web 開發中,我們習慣把過濾器配置到 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; /** * 用戶連續訪問最高閥值,超過該值則認定為惡意操作的IP,進行限制 */ private static final int LIMIT_NUMBER = 5; /** * 用戶訪問最小安全時間,在該時間內如果訪問次數大于閥值,則記錄為惡意IP,否則視為正常訪問 */ private static final int MIN_SAFE_TIME = 5000; private FilterConfig config; @Override public void init(FilterConfig filterConfig) throws ServletException { this.config = filterConfig; //設置屬性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信息 //Map<String, Long> limitedIpMap = (Map<String, Long>) context.getAttribute("limitedIpMap"); ConcurrentHashMap<String ,Long> limitedIpMap = (ConcurrentHashMap<String, Long>) 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(); // 剩余限制時間(用為從毫秒到秒轉化的一定會存在些許誤差,但基本可以忽略不計) request.setAttribute("remainingTime", ((limitedTime / 1000) + (limitedTime % 1000 > 0 ? 1 : 0))); System.err.println("ip訪問過于頻繁:"+ip); throw new RuntimeException("ip訪問過于頻繁"); } // 獲取IP存儲器 ConcurrentHashMap<String, Long[]> ipMap = (ConcurrentHashMap<String, Long[]>) context.getAttribute("ipMap"); // 判斷存儲器中是否存在當前IP,如果沒有則為初次訪問,初始化該ip // 如果存在當前ip,則驗證當前ip的訪問次數 // 如果大于限制閥值,判斷達到閥值的時間,如果不大于[用戶訪問最小安全時間]則視為惡意訪問,跳轉到異常頁面 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("您首次訪問該網站"); } context.setAttribute("ipMap", ipMap); chain.doFilter(request, response); } @Override public void destroy() { // TODO Auto-generated method stub } /** * @Description 過濾受限的IP,剔除已經到期的限制IP * @param limitedIpMap */ private void filterLimitedIpMap(ConcurrentHashMap<String, Long> limitedIpMap) { if (limitedIpMap == null) { return; } Set<String> keys = limitedIpMap.keySet(); Iterator<String> 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<String, Long> limitedIpMap, String ip) { if (limitedIpMap == null || ip == null) { // 沒有被限制 return false; } Set<String> keys = limitedIpMap.keySet(); Iterator<String> keyIt = keys.iterator(); while (keyIt.hasNext()) { String key = keyIt.next(); if (key.equals(ip)) { // 被限制的IP return true; } } return false; } /** * 初始化用戶訪問次數和訪問時間 * * @param ipMap * @param ip */ private void initIpVisitsNumber(ConcurrentHashMap<String, Long[]> ipMap, String ip) { Long[] ipInfo = new Long[2]; ipInfo[0] = 0L;// 訪問次數 ipInfo[1] = System.currentTimeMillis();// 初次訪問時間 ipMap.put(ip, ipInfo); } }
2. 創建一個監聽器:需要初始化倆個容器:
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存儲器 ConcurrentHashMap<String, Long[]> ipMap = new ConcurrentHashMap<>(); context.setAttribute("ipMap", ipMap); // 限制IP存儲器:存儲被限制的IP信息 ConcurrentHashMap<String, Long> limitedIpMap = new ConcurrentHashMap<String, Long>(); 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)){ //根據網卡取本機配置的IP InetAddress inet=null; try { inet = InetAddress.getLocalHost(); } catch (UnknownHostException e) { e.printStackTrace(); } ip= inet.getHostAddress(); } } return ip; } }
4配置
springboot啟動類中添加過濾器和監聽器的包掃描
@ServletComponentScan(basePackages="cn.xxx.common")
spring web.xml
過濾器
<filter> <filter-name>ipFilter</filter-name> <filter-class>com.xxxx.common.filter.IpFilter</filter-class> </filter> <filter-mapping> <filter-name>ipFilter</filter-name> <url-pattern>/dyflight/**</url-pattern> </filter-mapping>
監聽器:
<listener> <listener-class>com.xxxx.common.Listener.MyApplicationListener</listener-class> </listener>
看完這篇關于如何實現Springboot過濾器禁止ip頻繁訪問功能的文章,如果覺得文章內容寫得不錯的話,可以把它分享出去給更多人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。