【解决大量提交垃圾数据可导致占用大量服务器资源,导致类 DDOS 的攻击行为产生的问题】

有用到redis的setIfAbsent方法、AOP中的before以及自定义注解

不废话,上代码

注解:IgnoreBatchProcess

这个注解的作用是:如果哪个接口不需要做限制就在哪个接口加这个注解

import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface IgnoreBatchProcess {
}

切面:BatchProcessAspect(获取ip的工具类自己随便找一个吧,我就不写了;注意execution的值,填自己的包路径)

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

@Aspect
@Component
@Slf4j
public class BatchProcessAspect {
    @Autowired
    private RedisService redisService;

    @Pointcut("execution(* com.server.web.controller.*.*.*(..))")
    public void pointcutExpression() {
    }

    @Pointcut("@annotation(com.server.log.vo.IgnoreBatchProcess)")
    public void pointcutAnnotation() {
    }

    @Before(value = "pointcutExpression() && !pointcutAnnotation()")
    public void before(JoinPoint joinPoint) {
        // 获取请求信息
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String apiPath = request.getServletPath();
        String ipKey = IpAddressUtils.getClientIpAddress(request) + apiPath;
        if (judge(ipKey)) {
            throw new BusinessException("短时间内提交请求的次数超过限制");
        }
    }

    private boolean judge(String key) {
        return !redisService.setIfAbsent(key, "batchProcess", 1l, TimeUnit.SECONDS);
    }
}
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值