refactor: 使用redis分布式锁

This commit is contained in:
CaptainB 2022-03-30 17:09:04 +08:00 committed by 刘瑞斌
parent f645105525
commit 8bef9d47cb
2 changed files with 3 additions and 63 deletions

View File

@ -142,8 +142,9 @@
<version>${shiro.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-boot-starter</artifactId>
<version>3.17.0</version>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>

View File

@ -1,61 +0,0 @@
package io.metersphere.commons.utils;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Objects;
@Service
public class RedisLockHelper {
public static final String LOCK_PREFIX = "REDIS_LOCK_";
@Resource
private RedisTemplate<String, String> redisTemplate;
public boolean lock(String key) {
return lock(key, 1000);
}
/**
* @param key key
* @param expire 过期时间默认 1000 ms
*/
public boolean lock(String key, int expire) {
if (expire <= 0) {
expire = 1000;
}
String lock = LOCK_PREFIX + key;
//
int LOCK_EXPIRE = expire;
Boolean result = redisTemplate.execute((RedisCallback<Boolean>) connection -> {
long expireAt = System.currentTimeMillis() + LOCK_EXPIRE + 1;
Boolean acquire = connection.setNX(lock.getBytes(), String.valueOf(expireAt).getBytes());
if (BooleanUtils.toBoolean(acquire)) {
return true;
} else {
byte[] value = connection.get(lock.getBytes());
if (Objects.nonNull(value) && value.length > 0) {
long expireTime = Long.parseLong(new String(value));
if (expireTime < System.currentTimeMillis()) {
// in case the lock is expired
byte[] oldValue = connection.getSet(lock.getBytes(), String.valueOf(System.currentTimeMillis() + LOCK_EXPIRE + 1).getBytes());
// avoid dead lock
return Long.parseLong(new String(oldValue)) < System.currentTimeMillis();
}
}
}
return false;
});
return BooleanUtils.toBoolean(result);
}
public boolean unlock(String key) {
return redisTemplate.delete(key);
}
}