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());
});