Springboot过滤器禁⽌ip频繁访问功能实现
在开发 Web 项⽬的时候,经常需要过滤器来处理⼀些请求,包括字符集转换什么的,记录请求⽇志什么的等等。在之前的 Web 开发中,我们习惯把过滤器配置到 l 中,但是在 SpringBoot 中,兵没有这个配置⽂件,该如何操作呢?
1.编写⼀个过滤器:
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 urrent.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 {
}
/
* (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 = ServletContext();
// 获取限制IP存储器:存储被限制的IP信息
//Map<String, Long> limitedIpMap = (Map<String, Long>) Attribute("limitedIpMap");
ConcurrentHashMap<String ,Long> limitedIpMap = (ConcurrentHashMap<String, Long>) Attribute("limitedIpMap");
// 过滤受限的IP
filterLimitedIpMap(limitedIpMap);
// 获取⽤户IP
String ip = RemoteIpAddr(request);
// 判断是否是被限制的IP,如果是则跳到异常页⾯
if (isLimitedIP(limitedIpMap, ip)) {
long limitedTime = (ip) - System.currentTimeMillis();
// 剩余限制时间(⽤为从毫秒到秒转化的⼀定会存在些许误差,但基本可以忽略不计)
request.setAttribute("remainingTime", ((limitedTime / 1000) + (limitedTime % 1000 > 0 ? 1 : 0)));
throw new RuntimeException("ip访问过于频繁");
}
// 获取IP存储器
ConcurrentHashMap<String, Long[]> ipMap = (ConcurrentHashMap<String, Long[]>) Attribute("ipMap");
// 判断存储器中是否存在当前IP,如果没有则为初次访问,初始化该ip
// 如果存在当前ip,则验证当前ip的访问次数
// 如果⼤于限制阀值,判断达到阀值的时间,如果不⼤于[⽤户访问最⼩安全时间]则视为恶意访问,跳转到异常页⾯
if (ainsKey(ip)) {
Long[] ipInfo = (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 = (());
log.debug("expireTimeMillis <= currentTimeMillis:"+ expireTimeMillis+" <="+ currentTimeMillis);      if (expireTimeMillis <= currentTimeMillis) {
}
}
}
/**
* @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;
}
springcloud和springbootSet<String> keys = limitedIpMap.keySet();
Iterator<String> keyIt = keys.iterator();
while (keyIt.hasNext()) {
String key = ();
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. 创建⼀个:需要初始化俩个容器:
slf4j.Slf4j;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import urrent.ConcurrentHashMap;
@Slf4j
@WebListener
public class MyApplicationListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
log.debug("liting: contextInitialized");
log.debug("MyApplicationListener初始化成功");
ServletContext context = ServletContext();
// 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:"+String()+";limitedIpMap:"+String()+"初始化成功。。。。。");  }
@Override
public void contextDestroyed(ServletContextEvent sce) {
// TODO Auto-generated method stub
}
}
3.iputil
import javax.servlet.http.HttpServletRequest;
import java.InetAddress;
import java.UnknownHostException;
public class IPUtil {
public static String getRemoteIpAddr(HttpServletRequest request) {
String ip = Header("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = Header("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = Header("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = Header("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = Header("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = RemoteAddr();
if("127.0.0.1".equals(ip)||"0:0:0:0:0:0:0:1".equals(ip)){
//根据⽹卡取本机配置的IP
InetAddress inet=null;
try {
inet = LocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
}
ip= HostAddress();
}
}
return ip;
}
}
4配置
springboot启动类中添加过滤器和的包扫描
@ServletComponentScan(basePackages="cn.xxxmon")
l
过滤器
<filter>
<filter-name>ipFilter</filter-name>
<filter-class&n.filter.IpFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>ipFilter</filter-name>
<url-pattern>/dyflight/**</url-pattern>
</filter-mapping>
<listener>
<listener-class&n.Listener.MyApplicationListener</listener-class>
</listener>
以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。