SpringBoot Redis使用AOP防止重复提交

本文介绍了如何使用自定义注解和AOP切面来防止HTTP请求的重复提交,通过Redis缓存记录同一IP的请求次数,在指定时间内限制请求频率,从而保护系统稳定。示例代码展示了注解的定义、切面的处理逻辑以及实际应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

自定义注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
 * @ProjectName: gswr-ets-cloud
 * @ClassName:
 * @Description: 防止重复提交的自定义注解
 * @Date: 2022-2-8 9:28
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface NoRepeatSubmit {
    int seconds();
    int maxCount();
}
防止重复请求切面
import com.alibaba.fastjson.JSONObject;
import io.renren.commons.tools.utils.Result;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.util.Assert;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * @ProjectName: gswr-ets-cloud
 * @ClassName:
 * @Description: 防止重复请求
 * @Date: 2022-2-8 11:12
 */
@Aspect
@Component
public class NoRepeatSubmitAspect {

    protected Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private RedisTemplate redisTemplate;

    @Pointcut("@annotation(noRepeatSubmit)")
    public void pointCut(NoRepeatSubmit noRepeatSubmit) {
    }

    @Around("pointCut(noRepeatSubmit)")
    public Result around(ProceedingJoinPoint pjp, NoRepeatSubmit noRepeatSubmit) throws Throwable {
        ServletRequestAttributes ra= (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = ra.getRequest();
        Assert.notNull(request, "request can not null");

        int seconds = noRepeatSubmit.seconds();
        int maxCount = noRepeatSubmit.maxCount();
        //获取请求Ip
        String ip=request.getRemoteAddr();
        //将请求路径及ip组成键值 如:/finance/fastApply/test:192.168.56.1
        String key = request.getServletPath() + ":" + ip ;
        //获取请求次数
        Integer count = (Integer) redisTemplate.opsForValue().get(key);

        if (null == count) {//第一次访问
            redisTemplate.opsForValue().set(key, 1,seconds, TimeUnit.SECONDS);
            pjp.proceed();
            return new Result().ok("第一次请求成功");
        }else if (count < maxCount) {//在允许的访问次数内
            count = count+1;
            redisTemplate.opsForValue().set(key, count,0);
            pjp.proceed();
            return new Result().ok("请求成功");
        }else  {//超出访问次数
            logger.info("访问过快ip ===> " + ip + " 且在 " + seconds + " 秒内超过最大限制 ===> " + maxCount + " 请求次数达到 ===> " + count);
            return new Result().error("请求过快");
        }
    }
}


使用样例
	/**
     * 测试重复提交 30s内允许请求1次
     */
    @NoRepeatSubmit(seconds=30, maxCount=1)
    @GetMapping("/test")
    public Result test()
    {
        System.out.println("我被请求了");
        return new Result().ok("请求成功");
    }

此方法只是简单的根据记录同一IP提交次数去防止重复请求

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Dream答案

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值