为什么要用到分布式锁?
在分布式系统中,不同的系统需要使用到同一个资源的时候,需要对这个资源进行加锁,使得在某一时刻只有一个系统操作资源,以此来保证数据的一致性。
两个原子方法
setnx():不存在时设置值返回true,存在则不进行设置并返回false(对应java的setIfAbsent()方法)
getset():设置新值并返回旧值。
可以访问Redis中文网站查看具体的介绍:http://www.redis.cn/commands/setnx.html
java代码实现如下:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
/**
* @author river
* 2020/1/16
*/
@Component
public class RedisDistributedLock {
private static final int EXPIRE_TIME = 30;//设置默认过期时间为30秒
@Autowired
StringRedisTemplate stringRedisTemplate;
/**
* 加锁
* @param key 加锁对象
* @return 加锁成功返回true,失败返回false
*/
public boolean lock(String key) {
return lock(key, EXPIRE_TIME);
}
/**
* 加锁
*
* @param key 加锁键值
* @param expire 过期时间,单位秒
* @return 加锁成功返回true,失败返回false
*/
public boolean lock(String key, int expire) {
if (null == key) {
System.out.println("key can not be null!");
return false;
}
ValueOperations<String, String> valueOperations = stringRedisTemplate.opsForValue();
final long currentTimeMillis = System.currentTimeMillis();
final String expireTime = String.valueOf(currentTimeMillis + expire * 1000 + 1);
//如果不存在就设置,设置成功后直接返回true
Boolean flag = valueOperations.setIfAbsent(key, expireTime);
if (null != flag && flag) {
return true;
}
String savedTime = valueOperations.get(key);
//锁过期
if (null != savedTime && Long.parseLong(savedTime) < currentTimeMillis) {
String oldTime = valueOperations.getAndSet(key, expireTime);
//旧的时间就是保存的时间时,加锁成功,返回true
return savedTime.equals(oldTime);
}
return false;
}
/**
* 解锁
* @param key 解锁对象
*/
public void unlock(String key) {
if (null == key)
return;
ValueOperations<String, String> valueOperations = stringRedisTemplate.opsForValue();
String savedTime = valueOperations.get(key);
//没有过期就删除锁,过期了不进行操作
if (!StringUtils.isEmpty(savedTime) && System.currentTimeMillis() < Long.parseLong(savedTime)) {
valueOperations.getOperations().delete(key);
}
}
}