【SpringBoot】限制IP访问频率

引言

显示中存在恶意ip频繁请求情况,本文通过自定义注解+拦截器实现限制ip访问的频率

 

实现

1. 添加pom依赖

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
        <version>4.3.10.RELEASE</version>
    </dependency>

2. 添加自定义注解

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
@Order(Ordered.HIGHEST_PRECEDENCE)
public @interface RequestLimit {
   
   
    /**
     * 允许访问的最大次数
     */
    int count() default Integer.MAX_VALUE;
 
    /**
     * 时间段,单位为毫秒,默认值一分钟
     */
    long time() default 60000;
}

3. 添加自定义异常

public class RequestLimitException extends NestedRuntimeException {
   
   

    public RequestLimitException(){
   
   
        super("HTTP请求超出设定的限制");
    }

    public RequestLimitException(String msg) {
   
   
        super(msg);
    }
}

4. 添加自定义拦截器

interceptor

@Slf4j
@Aspect
@Component
public class RequestLimitInterceptor {
   
   

    @Before("within(@org.springframework.web.bind.annotation.RequestMapping * || @javax.ws.rs.Path *) && @annotation(limit)")
    public void requestLimit(final JoinPoint joinPoint, RequestLimit limit) throws RequestLimitException {
   
   
        try {
   
   
            // 获取 HttpServletRequest
            Object[] args = joinPoint.getArgs();
            HttpServletRequest request = null;
            for (int i = 0; i < args.length; i++) {
   
   
                if (<
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值