防止重复提交 根据redis+springboot aop +注解实现

该博客介绍了一种使用Spring AOP和Redis来防止API重复提交的方法。通过定义`@NoRepeatSubmit`注解和对应的切面`NoRepeatSubmitAspect`,实现了在达到特定临界值时清理Redis中存储的请求数据,从而避免重复操作。

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

/**
 * @Description 防止重复提交注解
 * @Author jinpk
 * @Date 2022/8/15 10:51
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface NoRepeatSubmit {

}
/**
 * @Description 定义切面,实现拦截功能
 * @Author jinpk
 * @Date 2022/8/15 10:58
 */
@Aspect
@Component
public class NoRepeatSubmitAspect {

    protected final Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    RedisTemplate redisTemplate;

    //临界值
    @Value("${redisConfig.criticality}")
    private Integer criticality;

    /**
     * 横切点
     */
    @Pointcut("@annotation(noRepeatSubmit)")
    public void repeatPoint(NoRepeatSubmit noRepeatSubmit) {
    }

    /**
     * 接收请求,并记录数据
     */
    @Around(value = "repeatPoint(noRepeatSubmit)")
    public Object doBefore(ProceedingJoinPoint joinPoint, NoRepeatSubmit noRepeatSubmit) {
        //参数
        Object[] args = joinPoint.getArgs();
        //参数转化成json
        String data = JsonUtils.objectToJson(args);
        //参数加密
        String key = MD5.stringToMD5(data);
        //方法名
        String methodName = joinPoint.getSignature().toShortString();
        log.info("进行防重复提交");
        try {
            // 如果缓存中有这个url视为重复提交
            if (redisTemplate.boundHashOps("repeat:key").get(key) == null) {
                //获取全部的key
                Set<String> keys = redisTemplate.boundHashOps("repeat:key").keys();
                if (!CollectionUtils.isEmpty(keys)){
                    System.out.println("========redis:防止重复提交的key的数量=========:"+keys.size());
                    //大于临界值时 redis repeat:key 此文件夹下所有数据清零
                    if (keys.size() >= criticality){
                        redisTemplate.delete("repeat:key");
                    }
                }
                redisTemplate.boundHashOps("repeat:key").put(key, methodName);
                return joinPoint.proceed();
            }else {
                log.info("重复提交");
                return AjaxResult.error("请勿重复提交!");
            }
        } catch (Throwable throwable) {
            log.info("运行业务代码出错", throwable);
            return AjaxResult.error("请求异常请稍后!");
        }
    }
}

可以使用 Redisson 实现分布式锁,具体实现如下: 1. 引入 Redisson 依赖: ```xml <dependency> <groupId>org.redisson</groupId> <artifactId>redisson-spring-boot-starter</artifactId> <version>3.16.1</version> </dependency> ``` 2. 定义自定义注解 `DistributedLock`: ```java @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface DistributedLock { String value() default ""; long leaseTime() default 30L; TimeUnit timeUnit() default TimeUnit.SECONDS; } ``` 3. 在需要加锁的方法上加上 `@DistributedLock` 注解: ```java @Service public class UserService { @DistributedLock("user:#{#userId}") public User getUserById(String userId) { // ... } } ``` 4. 实现 `DistributedLockAspect` 切面: ```java @Aspect @Component public class DistributedLockAspect { private final RedissonClient redissonClient; public DistributedLockAspect(RedissonClient redissonClient) { this.redissonClient = redissonClient; } @Around("@annotation(distributedLock)") public Object around(ProceedingJoinPoint joinPoint, DistributedLock distributedLock) throws Throwable { String lockKey = distributedLock.value(); if (StringUtils.isEmpty(lockKey)) { lockKey = joinPoint.getSignature().toLongString(); } RLock lock = redissonClient.getLock(lockKey); boolean locked = lock.tryLock(distributedLock.leaseTime(), distributedLock.timeUnit()); if (!locked) { throw new RuntimeException("获取分布式锁失败"); } try { return joinPoint.proceed(); } finally { lock.unlock(); } } } ``` 5. 在 `application.yml` 中配置 Redisson: ```yaml spring: redis: host: localhost port: 6379 password: database: 0 redisson: single-server-config: address: redis://${spring.redis.host}:${spring.redis.port} ``` 这样就实现了一个基于 Redis 的分布式锁。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值