版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/t1g2q3/article/details/87694643
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.util.Objects;
/**
* Redis+Connection实现简单的分布式锁
* 未能获取到锁应该按照业务逻辑进行阻塞或者放弃
* @author Array
*/
@Component
public class DistributeLockByRedisTemplate {
public static final String LOCK_PREFIX = "redis_lock";
public static final int LOCK_EXPIRE = 300;
@Autowired
RedisTemplate redisTemplate;
/**
* 加锁
* @param key key值
* @return 是否获取到
*/
public boolean lock(String key) {
String lock = LOCK_PREFIX + key;
return (Boolean) redisTemplate.execute((RedisCallback) connection -> {
long expireAt = System.currentTimeMillis() + LOCK_EXPIRE + 1;
/**
* SET IF NOT EXISTS
* 如果当前没有任何人持有锁,占有锁
*/
Boolean acquire = connection.setNX(lock.getBytes(),
String.valueOf(expireAt).getBytes());
if (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()) {
/**
* 如果锁已经过期,获取锁
*/
byte[] oldValue = connection.getSet(lock.getBytes(), String.valueOf(System.currentTimeMillis() + LOCK_EXPIRE + 1).getBytes());
return Long.parseLong(new String(oldValue)) < System.currentTimeMillis();
}
}
}
return false;
});
}
/**
* 手动释放锁
*
* @param key
*/
public void delete(String key) {
redisTemplate.delete(key);
}
}