如何在springcloud分布式系统中实现分布式锁
2个回答
展开全部
提醒你一下用, redis的setNx命令吧, 我这有一份demo, 可以看下. 千万别忘了设置超时时间, 因为如果持有锁的进程异常了, 那这个锁就释放不掉了, 导致这一份资源永远无法被访问, 所以要有个超时时间来确保线程死掉以后锁会被redis释放掉. 超简单的一份demo, 送给您.哈哈
package com.cloud.support.cache.redis;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Objects;
@Component
public class RedisLockManage {
private static final long LOCK_EXPIRE = 60 * 30;
@Resource
private RedisTemplate redisTemplate;
public boolean lock(String key) {
return (Boolean) redisTemplate.execute((RedisCallback) connection -> {
long expireAt = System.currentTimeMillis() + LOCK_EXPIRE + 1;
Boolean acquire = connection.setNX(key.getBytes(), String.valueOf(expireAt).getBytes());
if (acquire) {
return true;
} else {
byte[] value = connection.get(key.getBytes());
if (Objects.nonNull(value) && value.length > 0) {
long expireTime = Long.parseLong(new String(value));
if (expireTime < System.currentTimeMillis()) {
byte[] oldValue = connection.getSet(key.getBytes(),
String.valueOf(System.currentTimeMillis() + LOCK_EXPIRE + 1).getBytes());
return Long.parseLong(new String(oldValue)) < System.currentTimeMillis();
}
}
}
return false;
});
}
public boolean unlock(String key) {
String lock = key;
return (Boolean) redisTemplate.execute((RedisCallback) connection -> {
long i = connection.del(lock.getBytes());
if (i > 0) {
return true;
}
return false;
});
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询