redis分布式锁

该博客介绍了如何利用Redisson库实现分布式锁来确保业务操作的原子性和防止重复提交。通过`invoke`方法,传入锁的key和一个Callable任务,如果在3秒内获取到锁,则执行任务,否则抛出异常。示例中展示了在支付预处理场景下,如何在加锁保护下执行订单状态检查、优惠券应用等操作。
摘要由CSDN通过智能技术生成
import lombok.extern.log4j.Log4j2;
import org.redisson.api.RLock;

import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

@Log4j2
public class RedissonUtil {
    /**
     * 分布式加锁执行
     * @Date 2019-05-24 23:59
     * @param key
     * @return
     * @throws InterruptedException
     */
    public  static <T> T invoke(String key, RedissonLockFunc<T> func) throws InterruptedException {
        RedissonService redissonService = BeanHeader.getBean(RedissonService.class);
        // 分布式锁 -锁状态 和防重复提交
        RLock lock = redissonService.getRLock(key);
        try {
            // 3秒内获取不到锁,返回false 。20秒后自动释放
            boolean bs = lock.tryLock(3, 4, TimeUnit.SECONDS);
            if (bs) {
                return func.run();
            } else {
                throw new ReSubmitException("当前业务繁忙,请稍后再试");
            }
        } catch (InterruptedException e) {
            log.error("执行异常", e);
            throw e;
        } finally {
            lock.unlock();
        }
    }

}

使用例子:

  Result<PayPrepayDTO> prepay = RedissonUtil.invoke(paySurplusVO.getOrderCode(), () -> {
            OrOrder order2 = this.orOrderService.getByCodeStatus(paySurplusVO.getOrderCode(), OrderStatusEnum.SER_FINISHED);
            Assert.notNull(order2, "-------");
            ProCouponCustomerPOJO customerCoupons4Week = proCouponCustomerService.customerCoupons4Week(getUserCode(), order2.getServiceCode());
            if (customerCoupons4Week != null && StringUtils.isEmpty(paySurplusVO.getCouponCustomerCode())) {
                paySurplusVO.setCouponCustomerCode(customerCoupons4Week.getCouponCustomerCode());
            }
            order2.setCouponCustomerCode(paySurplusVO.getCouponCustomerCode());
            return orderPayService.prepay(order2, customCode, PayTypeEnum.RM, paySurplusVO.getPayChannelEnum(), paySurplusVO.getTradeType());
        });
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

科学熊

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

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

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

打赏作者

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

抵扣说明:

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

余额充值