创建订单扣除库存

This commit is contained in:
2024-07-03 10:12:06 +08:00
parent dfdeca9612
commit 09bfa5bdec
6 changed files with 129 additions and 14 deletions

View File

@@ -0,0 +1,35 @@
package com.chaozhanggui.system.cashierservice.util;
import cn.hutool.core.lang.UUID;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
@Slf4j
public class LockUtils {
public static<T> T runFunAndCheckKey(Supplier<T> supplier, RedisTemplate<String, Object> redisTemplate, String lockKey) {
try{
// 创建线程id, 用作判断
String clientId = UUID.randomUUID().toString();
// 设置分布式锁
boolean lock = Boolean.TRUE.equals(redisTemplate.opsForValue().setIfAbsent(lockKey, clientId, 30, TimeUnit.SECONDS));
int count = 0;
while (!lock) {
if (count++ > 100) {
throw new RuntimeException("系统繁忙, 稍后再试");
}
Thread.sleep(20);
lock = Boolean.TRUE.equals(redisTemplate.opsForValue().setIfAbsent(lockKey, clientId, 30, TimeUnit.SECONDS));
}
return supplier.get();
} catch (Exception e){
log.info("执行出错:{}", e.getMessage());
throw new RuntimeException(e.getMessage());
}finally{
redisTemplate.delete(lockKey);
}
}
}