SpringBoot防止大量请求攻击

SpringBoot防止大量请求攻击我们使用Jmeter测试同学的网站时,就会出现网站无法访问,403等错误。Anerroroccurred.Sorry,thepageyouarelookingforiscurrentlyunavailable.Pleasetryagainlater.Ifyouarethesystemadministratorofthisresourcethenyoushouldchecktheerrorlogfordetails.Faithfull

大家好,又见面了,我是你们的朋友全栈君。

我们使用Jmeter测试同学的网站时,就会出现网站无法访问,403等错误。

An error occurred. Sorry, the page you are looking for is currently unavailable. Please try again later. If you are the system administrator of this resource then you should check the error log for details. Faithfully yours, nginx.

所以我们需要加上IP访问时间限制,防止一个IP多次访问请求,导致整个网站崩溃。

  • 自定义注解:
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/** * 自定义注解,用于拦截过于频繁的请求 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface AccessLimit { 
   
    int seconds();
    int maxCount();
    boolean needLogin() default true;
}
  • 自定义拦截器:
    我采用了抛出自定义异常的方式来解决相同IP多次访问的问题:
    throw new DujiaoshouException(20001,"操作过于频繁");
import com.qykhhr.dujiaoshouservice.exceptionhandler.DujiaoshouException;
import com.qykhhr.dujiaoshouservice.mycomment.AccessLimit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/** * 自定义拦截器 */
@Component
public class AccessLimtInterceptor implements HandlerInterceptor { 
   

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { 
   

        if (handler instanceof HandlerMethod) { 
   
            HandlerMethod hm = (HandlerMethod) handler;
            AccessLimit accessLimit = hm.getMethodAnnotation(AccessLimit.class);
            if (null == accessLimit) { 
   
                return true;
            }
            int seconds = accessLimit.seconds();
            int maxCount = accessLimit.maxCount();
            boolean needLogin = accessLimit.needLogin();

            if (needLogin) { 
   
                //判断是否登录
            }
            String ip=request.getRemoteAddr();
            String key = request.getServletPath() + ":" + ip ;
            Integer count = (Integer) redisTemplate.opsForValue().get(key);

            if (null == count || -1 == count) { 
   
                redisTemplate.opsForValue().set(key, 1,seconds, TimeUnit.SECONDS);
                return true;
            }

            if (count < maxCount) { 
   
                count = count+1;
                redisTemplate.opsForValue().set(key, count,0);
                return true;
            }

            // response 返回 json 请求过于频繁请稍后再试
            throw new DujiaoshouException(20001,"操作过于频繁");
        }

        return true;
    }
}
  • 在webconfig中配置拦截器

import com.qykhhr.dujiaoshouservice.Interceptor.AccessLimtInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/** * 在webconfig中配置拦截器 */
@Configuration
public class MyWebMvcConfigurer extends WebMvcConfigurerAdapter { 
   

    @Autowired
    private AccessLimtInterceptor accessLimtInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) { 
   
        registry.addInterceptor(accessLimtInterceptor);
        super.addInterceptors(registry);
    }
}

  • 在Controller前面加上注解就可以生效了
@RestController
public class AppHomeController { 
   

    @GetMapping("/index")
    @AccessLimit(seconds = 1, maxCount = 3) //1秒内 允许请求3次
    public R getImageList(){ 
   
        return R.ok().data("appHome","hahaha");
    }
}

使用python发送100次请求,可以发现请求被拦截了多少
在这里插入图片描述
对于注解,我们也可以不使用它,但是我们需要在拦截器中写入固定的参数。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/162102.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • AutoEventWireup属性的确切含义

    AutoEventWireup属性的确切含义使用Asp.NET时,新建的aspx页面第一行page指令中包含了一个AutoEventWireup属性。网上的很多教程认为这一属性,甚至这一行代码都是没用的。其实,这是不了解Asp.NET事件处理模型的表现。简单来说,这一属性决定了当前页是否自动关联某些特殊事件。    首先,从浏览器页面触发的事件不能立刻在本地得到处理,而是POST至服务器上,因此,Asp.NET建立了委托(代理)机制

    2022年5月28日
    48
  • bitblt函数_统计参数的含义

    bitblt函数_统计参数的含义【转载请注明出处: http://blog.csdn.net/lzl124631x】接口BOOLBitBlt( _In_ HDChdcDest, _In_ intnXDest, _In_ intnYDest, _In_ intnWidth, _In_ intnHeight, _In_ HDChdcSrc, _I

    2022年10月19日
    2
  • windows10如何关闭默认共享(关闭windows默认共享)

    方法一 首先,我们右键桌面上的计算机图标,点击管理选项,如图所示。   接着,在系统工具里的共享文件选项,在右边会列出共享的内容,选择你要停止的共享,右键,选择停止即可,如图所示。   方法二   依旧是打开计算机右键,打开管理选项,然后再左侧的树状列表里找到服务选项,双击打开,如图所示。   然后,在右侧的服务列表里,找到se…

    2022年4月15日
    73
  • Java BigDecimal和double-BigDecimal转double-double转BigDecimal

    Java BigDecimal和double-BigDecimal转double-double转BigDecimalBigDecimal类对于不需要任何准确计算精度的数字可以直接使用float或double,但是如果需要精确计算的结果,则必须使用BigDecimal类,而且使用BigDecimal类也可以进行大数的操作。BigDecimal类的常用方法如表11-15所示。表11-15BigDecimal类的常用方法序号方   法类型描   

    2022年5月4日
    61
  • java实现各种数据统计图(柱形图,饼图,折线图)

    java实现各种数据统计图(柱形图,饼图,折线图)

    2021年12月16日
    45
  • mac phpstorm 2021.4.14 激活码_通用破解码

    mac phpstorm 2021.4.14 激活码_通用破解码,https://javaforall.net/100143.html。详细ieda激活码不妨到全栈程序员必看教程网一起来了解一下吧!

    2022年3月15日
    58

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号