支付优化

This commit is contained in:
seesaw
2024-10-22 15:55:54 +08:00
parent dbe0c9a61b
commit a995bbbe8b
2 changed files with 22 additions and 32 deletions

View File

@ -67,9 +67,16 @@ public class CashRechargeServiceImpl implements CashRechargeService{
synchronized (getUserLock(userId)) {
MemberUserDO memberUserDO = userMapper.selectById(userId);
//金额变动
BigDecimal oldMoney = memberUserDO.getMoney();
System.out.println(oldMoney);
memberUserDO.setMoney(memberUserDO.getMoney().add(money));
if (memberUserDO.getMoney().compareTo(BigDecimal.ZERO) > 0) {
if (oldMoney.compareTo(BigDecimal.ZERO) > 0) {
memberUserDO.setCashAmount(memberUserDO.getCashAmount().add(money));
} else {
memberUserDO.setCashAmount(memberUserDO.getMoney());
}
}
userMapper.updateById(memberUserDO);

View File

@ -5,31 +5,14 @@ import java.util.concurrent.ConcurrentHashMap;
public class LockManager {
private static final ConcurrentHashMap<Long, WeakReference<Object>> userLocks = new ConcurrentHashMap<>();
private static final ConcurrentHashMap<Long, Object> userLocks = new ConcurrentHashMap<>();
private static final ConcurrentHashMap<Long, Object> storeLocks = new ConcurrentHashMap<>();
public static Object getUserLock(Long userId) {
// 从 Map 中获取 WeakReference 对象
WeakReference<Object> lockRef = userLocks.get(userId);
Object lock = (lockRef != null) ? lockRef.get() : null;
if (lock == null) {
// 如果锁对象不存在或者已被回收,创建新的锁对象
lock = new Object();
WeakReference<Object> newLockRef = new WeakReference<>(lock);
// 使用 putIfAbsent 确保线程安全
WeakReference<Object> existingLockRef = userLocks.putIfAbsent(userId, newLockRef);
if (existingLockRef != null) {
lock = existingLockRef.get();
if (lock == null) {
// 如果弱引用对象已经被 GC 回收,更新锁对象
userLocks.put(userId, newLockRef);
}
}
}
return lock;
return userLocks.computeIfAbsent(userId, k -> new Object());
}
public static Object getStoreLock(Long storeId) {