闸机扣费接口调整
This commit is contained in:
@@ -0,0 +1,73 @@
|
||||
package org.jeecg.common.util;
|
||||
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@Component
|
||||
public class RedisLockUtil {
|
||||
|
||||
private final StringRedisTemplate stringRedisTemplate;
|
||||
|
||||
// 锁的默认过期时间:1分钟
|
||||
private static final long DEFAULT_LOCK_EXPIRE = 60;
|
||||
// 锁的前缀,避免键名冲突
|
||||
private static final String LOCK_PREFIX = "food:lock:";
|
||||
|
||||
public RedisLockUtil(StringRedisTemplate stringRedisTemplate) {
|
||||
this.stringRedisTemplate = stringRedisTemplate;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取分布式锁
|
||||
* @param key 业务键(这里使用菜品ID)
|
||||
* @return 锁标识(释放锁时需要),null表示获取锁失败
|
||||
*/
|
||||
public String tryLock(String key) {
|
||||
return tryLock(key, DEFAULT_LOCK_EXPIRE, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取分布式锁
|
||||
* @param key 业务键
|
||||
* @param expire 过期时间
|
||||
* @param timeUnit 时间单位
|
||||
* @return 锁标识,null表示获取锁失败
|
||||
*/
|
||||
public String tryLock(String key, long expire, TimeUnit timeUnit) {
|
||||
// 生成唯一标识,用于释放锁时的验证
|
||||
String lockValue = UUID.randomUUID().toString();
|
||||
String lockKey = LOCK_PREFIX + key;
|
||||
|
||||
// 使用setIfAbsent实现分布式锁,原子操作
|
||||
Boolean success = stringRedisTemplate.opsForValue()
|
||||
.setIfAbsent(lockKey, lockValue, expire, timeUnit);
|
||||
|
||||
return Boolean.TRUE.equals(success) ? lockValue : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 释放分布式锁
|
||||
* @param key 业务键
|
||||
* @param lockValue 获取锁时返回的标识
|
||||
* @return 是否释放成功
|
||||
*/
|
||||
public boolean releaseLock(String key, String lockValue) {
|
||||
if (lockValue == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
String lockKey = LOCK_PREFIX + key;
|
||||
String currentValue = stringRedisTemplate.opsForValue().get(lockKey);
|
||||
|
||||
// 验证是否是自己持有的锁
|
||||
if (lockValue.equals(currentValue)) {
|
||||
// 执行删除操作
|
||||
return Boolean.TRUE.equals(stringRedisTemplate.delete(lockKey));
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user