SpringBoot自定义注解@Idempotent实现API幂等性(防止接口重复请求)

目的

一定时间内,同样的请求(业务参数相同)访问同一个接口,则只能成功一次,其余被拒绝。

自定义幂等性注解

import java.lang.annotation.*;

/**
 * 幂等注解
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Idempotent {
    /**
     * 幂等名称,作为redis缓存Key的一部分。
     */
    String value();
    
    /**
     * 幂等过期时间,即:在此时间段内,对API进行幂等处理。
     */
    long expireMillis();
}

幂等性切面

```java
在这里插入代码片import cn.edu.nfu.jw.annotation.Idempotent;
import cn.edu.nfu.jw.exception.ServiceException;
import cn.edu.nfu.jw.util.KeyUtil;
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.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

@Aspect
@Component
@ConditionalOnClass(RedisTemplate.class)
public class IdempotentAspect {
    private static final Logger LOGGER = LoggerFactory.getLogger(IdempotentAspect.class);
    /**
     * redis缓存key的模板
     */
    private static final String KEY_TEMPLATE = "idempotent_%s";

    @Resource
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 根据实际路径进行调整
     */
    @Pointcut("@annotation(cn.edu.nfu.jw.annotation.Idempotent)")
    public void executeIdempotent() {
    }

    @Around("executeIdempotent()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        ValueOperations<String, String> opsValue = redisTemplate.opsForValue();
      	//获取方法
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        //获取幂等注解
        Idempotent idempotent = method.getAnnotation(Idempotent.class);
      	//根据 key前缀 + @Idempotent.value() + 方法签名 + 参数 构建缓存键值
      	//确保幂等处理的操作对象是:同样的 @Idempotent.value() + 方法签名 + 参数
        //调用KeyUtil工具类生成key
        String key = String.format(KEY_TEMPLATE, idempotent.value() + "_" + KeyUtil.generate(method.toString(), joinPoint.getArgs()));
        //通过加锁确保只有一个接口能够正常访问
        String s = opsValue.get(key);
        if (s==null) {
            //缓存请求的key
            opsValue.set(key,"false",idempotent.expireMillis(),TimeUnit.MILLISECONDS);
            return joinPoint.proceed();
        } else {
            LOGGER.info("当前时间:"+System.currentTimeMillis()+"");
            throw new ServiceException(-1,"你的操作太频繁了!");
        }
    }
}```

接口标记幂等性注解

//防止重复提交,value:请求方法名,expireMillis:重复提交频率,单位ms
    @Idempotent(value = "/CssStudent/w-jxsqXkh", expireMillis = 3000L)
    @RequestMapping("w-jxsqXkh")//@SessionAttribute("user")
    public Object jxsqXkh(@RequestAttribute("user")BaseUser user,Long yjkcid,Long kczid,Long l3id,Long xyid,Integer kcxf,String xh,Integer kkxn,Integer xnxq,Double jxbxf,Long jxbid,Long dbid ,Boolean jxsqFlag,String reason,Long kkkcid,long pcid,Boolean fx, HttpServletRequest request, HttpServletResponse response) throws ServiceException {
       Map<String,Object> map = new HashMap<>();
        map.put("jxbid",jxbid);
        map.put("dbid",dbid);
        map.put("kkkcid",kkkcid);
        map.put("pcid",pcid);
        map.put("fx",fx);
        map.put("reason",reason);
        map.put("kkxn",kkxn);
        map.put("xnxq",xnxq);
        map.put("jxbxf",jxbxf);
        map.put("l3id",l3id);
        map.put("xyid",xyid);
        map.put("kczid",kczid);
        map.put("yjkcid",yjkcid);

        return getSuccessJSON(studentService.jxsqXkh(map,user), request);
    }
  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
Java自定义注解可以用于实现接口的幂等操作。所谓接口的幂等,就是同一个请求多次执行也不会产生重复的副作用。 要实现接口的幂等,可以通过以下步骤: 1. 定义一个自定义注解,例如@Idempotent,用于标识接口方法的幂等性。 ```java @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface Idempotent { } ``` 2. 在接口方法上使用@Idempotent注解,表示该接口方法是幂等的。 ```java public interface MyService { @Idempotent void myMethod(); } ``` 3. 在实现类中,通过AOP的方式实现接口方法的幂等逻辑。可以使用AspectJ或Spring AOP等框架来实现。 ```java @Component @Aspect public class IdempotentAspect { @Autowired private IdempotentService idempotentService; @Around("@annotation(com.example.Idempotent)") public void checkIdempotent(ProceedingJoinPoint joinPoint) throws Throwable { // 获取方法参数,生成幂等key String idempotentKey = generateIdempotentKey(joinPoint.getArgs()); // 判断该key是否已经执行过,如果执行过则直接返回 if (idempotentService.isExecuted(idempotentKey)) { return; } // 执行方法体 joinPoint.proceed(); // 标记该key已经执行过 idempotentService.markExecuted(idempotentKey); } // 生成幂等key的逻辑 private String generateIdempotentKey(Object[] args) { // 根据接口方法的参数生成唯一标识,例如将参数拼接成字符串 return StringUtils.join(args); } } ``` 通过以上步骤,我们就可以实现接口方法的幂等性。在执行接口方法之前,会先判断该方法是否已经执行过,如果已执行过,则直接返回,避免重复执行产生副作用。同时,通过自定义注解@Idempotent的标识,可以简化幂等逻辑的实现和管理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Richard Chijq

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

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

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

打赏作者

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

抵扣说明:

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

余额充值