后端保证幂等性


@Slf4j
@Aspect
@Component
public class IdempotentAOP {
    /** Redis前缀 */
    private final String API_IDEMPOTENT_CHECK = "API_IDEMPOTENT_CHECK:";

    @Resource
    private HttpServletRequest request;
    @Resource
    private RedisUtil redisUtil;

    /**
     * 定义切面
     */
    @Pointcut("@annotation(com.uinnova.product.eam.web.aop.NotRepeat)")
    public void notRepeat() {
    }

    /**
     * 在接口原有的方法执行前,将会首先执行此处的代码
     */
    @Before("notRepeat()")
    public void doBefore(JoinPoint joinPoint) {
        String uri = request.getRequestURI();

        // 登录后才做校验
        SysUser loginUser = SysUtil.getCurrentUserInfo();
        if (loginUser != null) {
            assert uri != null;
            String key = loginUser.getLoginCode() + "_" + uri;
            log.info(">>>>>>>>>> 【IDEMPOTENT】开始幂等性校验,加锁,account: {},uri: {}", loginUser.getLoginCode(), uri);

            // 加分布式锁
            boolean lockSuccess = redisUtil.setnx(API_IDEMPOTENT_CHECK + key, "1", 60, TimeUnit.SECONDS);
            log.info(">>>>>>>>>> 【IDEMPOTENT】分布式锁是否加锁成功:{}", lockSuccess);
            if (!lockSuccess) {
                if (uri.contains("/uploadContextFile")) {
                    log.error(">>>>>>>>>> 【IDEMPOTENT】文件保存中,请稍候");
                    throw new IllegalArgumentException("文件保存中,请稍候");

                } else if (uri.contains("contract/saveContract")) {
                    log.error(">>>>>>>>>> 【IDEMPOTENT】文件发起中,请稍后");
                    throw new IllegalArgumentException("文件发起中,请稍后");
                }
            }
        }
    }

    /**
     * 在接口原有的方法执行后,都会执行此处的代码(final)
     */
    @After("notRepeat()")
    public void doAfter(JoinPoint joinPoint) {
        // 释放锁
        String uri = request.getRequestURI();
        assert uri != null;
        SysUser loginUser = SysUtil.getCurrentUserInfo();
        if (loginUser != null) {
            String key = loginUser.getLoginCode()+ "_" + uri;
            log.info(">>>>>>>>>> 【IDEMPOTENT】幂等性校验结束,释放锁,account: {},uri: {}", loginUser.getLoginCode(), uri);
            redisUtil.del(API_IDEMPOTENT_CHECK + key);
        }
    }


}

用分布式锁解决

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值