一、Redis分布式锁的出现
如果是单机情况下(单JVM),线程之间共享内存,只要使用线程锁就可以解决并发问题。
如果是分布式情况下(多JVM),线程A和线程B很可能不是在同一JVM中,这样线程锁就无法起到作用了,这时候就要用到分布式锁来解决。
二、普通分布式锁(不推荐)
1、pom依赖
<!--Jedis依赖-->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
2、普通版本的分布式锁
redis连接池
/**
* Redis连接池
* @author lichangyuan
* @create 2021-08-31 14:32
*/
public class RedisPool {
private static JedisPool pool;//jedis连接池
private static int maxTotal = 20;//最大连接数
private static int maxIdle = 10;//最大空闲连接数
private static int minIdle = 5;//最小空闲连接数
private static boolean testOnBorrow = true;//在取连接时测试连接的可用性
private static boolean testOnReturn = false;//再还连接时不测试连接的可用性
static {
initPool();//初始化连接池
}
public static Jedis getJedis(){
return pool.getResource();
}
public static void close(Jedis jedis){
jedis.close();
}
private static void initPool(){
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(maxTotal);
config.setMaxIdle(maxIdle);
config.setMinIdle(minIdle);
config.setTestOnBorrow(testOnBorrow);
config.setTestOnReturn(testOnReturn);
config.setBlockWhenExhausted(true);
pool = new JedisPool(config, "127.0.0.1", 6379, 5000, "123123");
}
}
对Jedis的api进行封装,封装一些实现分布式锁需要用到的操作。
/**
* 对Jedis的api进行封装,封装一些实现分布式锁需要用到的操作。
*
* @author lichangyuan
* @create 2021-08-31 15:23
*/
public class RedisPoolUtil {
private RedisPoolUtil() {
}
private static RedisPool redisPool;
/**
* 通过key获取value
* @param key
* @return
*/
public static String get(String key) {
Jedis jedis = null;
String result = null;
try {
jedis = RedisPool.getJedis();
result = jedis.get(key);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) {
jedis.close();
}
return result;
}
}
/**
* 若该key-value不存在,则成功加入缓存并且返回1,否则返回0。
* @param key
* @param value
* @return
*/
public static Long setnx(String key, String value) {
Jedis jedis = null;
Long result = null;
try {
jedis = RedisPool.getJedis();
result = jedis.setnx(key, value);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) {
jedis.close();
}
return result;
}
}
/**
* 先获取key对应的value值,若不存在则返回nil,然后将旧的value更新为新的value。
* @param key
* @param value
* @return
*/
public static String getSet(String key, String value) {
Jedis jedis = null;
String result = null;
try {
jedis = RedisPool.getJedis();
result = jedis.getSet(key, value);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) {
jedis.close();
}
return result;
}
}
/**
* 设置key-value的有效期为seconds秒。
* @param key
* @param seconds
* @return
*/
public static Long expire(String key, int seconds) {
Jedis jedis = null;
Long result = null;
try {
jedis = RedisPool.getJedis();
result = jedis.expire(key, seconds);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) {
jedis.close();
}
return result;
}
}
/**
*删除已存在的键返回1。不存在的 key返回0
* @param key
* @return
*/
public static Long del(String key) {
Jedis jedis = null;
Long result = null;
try {
jedis = RedisPool.getJedis();
result = jedis.del(key);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) {
jedis.close();
}
return result;
}
}
}
分布式锁工具类
/**
* 分布式锁工具类
* @author lichangyuan
* @create 2021-08-31 15:33
*/
public class DistributedLockUtil {
private DistributedLockUtil(){
}
public static boolean lock(String lockName){//lockName可以为共享变量名,也可以为方法名,主要是用于模拟锁信息
System.out.println(Thread.currentThread() + "开始尝试加锁!");
Long result = RedisPoolUtil.setnx(lockName, String.valueOf(System.currentTimeMillis() + 5000));
if (result != null && result.intValue() == 1){
System.out.println(Thread.currentThread() + "加锁成功!");
RedisPoolUtil.expire(lockName, 5);
System.out.println(Thread.currentThread() + "执行业务逻辑!");
//打开之后,我们假设当前业务出现业务执行时间大于自动解锁时间,达到时长大于自动解锁时间。
// try {
// Thread.sleep(6000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
RedisPoolUtil.del(lockName);
return true;
} else {
String lockValueA = RedisPoolUtil.get(lockName);
//前者为自动解锁锁的时间,后者为当前时间,因此如果时间在lock自动解除的时间内
if (lockValueA != null && Long.parseLong(lockValueA) <= System.currentTimeMillis()){
//如果解锁时间小于当前时间则解掉之前的锁,然后新增锁
String lockValueB = RedisPoolUtil.getSet(lockName, String.valueOf(System.currentTimeMillis() + 5000));
if (lockValueB == null || lockValueB.equals(lockValueA)){
System.out.println(Thread.currentThread() + "加锁成功!");
RedisPoolUtil.expire(lockName, 5);
System.out.println(Thread.currentThread() + "执行业务逻辑!");
RedisPoolUtil.del(lockName);
return true;
} else {
return false;
}
} else {
//如果自动解锁的时间大于当前时间,则不能加锁。
return false;
}
}
}
}
效果测试
两个样例
public class LockTest {
public static void main(String[] args) {
boolean sb = DistributedLockUtil.lock("sb");
System.out.println(sb);
}
}
public class LockTest1 {
public static void main(String[] args) {
boolean sb1 = DistributedLockUtil.lock("sb");
System.out.println(sb1);
}
}
3、redis分布式锁保证
互斥性。在任意时刻,只有一个客户端能持有锁。
不会发生死锁。即使有一个客户端在持有锁的期间崩溃而没有主动解锁,也能保证后续其他客户端能加锁。
具有容错性。只要大部分的Redis节点正常运行,客户端就可以加锁和解锁。
解铃还须系铃人。加锁和解锁必须是同一个客户端,客户端自己不能把别人加的锁给解了。
三、升级版分布式锁
1、工具类
/**
* @author lichangyuan
* @create 2021-08-31 16:00
*/
public class RedisTool {
private static final String LOCK_SUCCESS = "OK";
private static final String SET_IF_NOT_EXIST = "NX";
private static final String SET_WITH_EXPIRE_TIME = "PX";
/**
* 加锁代码,尝试获取分布式锁
*
* @param jedis Redis客户端
* @param lockKey 锁
* @param requestId 请求标识
* @param expireTime 超期时间
* @return 是否获取成功
*/
public static boolean tryGetDistributedLock(Jedis jedis, String lockKey, String requestId, int expireTime) {
// 第一个参数key当锁,第二个参数value解锁人,第三个参数当key不存在时,我们进行set操作;若key已经存在,则不做任何操作
// 第四个参数标志第五个参数为设置锁时间,第五个参数设置时间
String result = jedis.set(lockKey, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime);
// 返回结果只有两种
// 1. 当前没有锁(key不存在),那么就进行加锁操作,并对锁设置个有效期,同时value表示加锁的客户端。
// 2. 已有锁存在,不做任何操作。
if (LOCK_SUCCESS.equals(result)) {
return true;
}
return false;
}
private static final Long RELEASE_SUCCESS = 1L;
/**
* 解锁代码,释放分布式锁
* @param jedis Redis客户端
* @param lockKey 锁
* @param requestId 请求标识
* @return 是否释放成功
*/
public static boolean releaseDistributedLock(Jedis jedis, String lockKey, String requestId) {
// 那么这段Lua代码的功能是什么呢?其实很简单,首先获取锁对应的value值,检查是否与requestId相等,如果相等则删除锁(解锁)。
// 那么为什么要使用Lua语言来实现呢?因为要确保上述操作是原子性的。
// 简单来说,就是在eval命令执行Lua代码的时候,Lua代码将被当成一个命令去执行,并且直到eval命令执行完成,Redis才会执行其他命令。
String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
Object result = jedis.eval(script, Collections.singletonList(lockKey), Collections.singletonList(requestId));
if (RELEASE_SUCCESS.equals(result)) {
return true;
}
return false;
}
}
2、场景一程序运行时间大于锁时间提前结束
public class LockTest2 {
public static void main(String[] args) {
//为锁的内容
String myMessage = "sb";
//随机数
String random = UUID.randomUUID().toString();
//获取redis
Jedis jedis = RedisPool.getJedis();
//加锁
boolean b1 = RedisTool.tryGetDistributedLock(jedis, myMessage, random , 50000);
System.out.println(b1);
//逻辑代码,这里用线程睡眠代替
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//解锁
boolean b2 = RedisTool.releaseDistributedLock(jedis, myMessage, random );
System.out.println(b2);
}
}
可以提前解锁
3、场景二程序运行时间小于锁自动释放时间,触发自动解锁
public class LockTest2 {
public static void main(String[] args) {
//为锁的内容
String myMessage = "sb";
//随机数
String random = UUID.randomUUID().toString();
//获取redis
Jedis jedis = RedisPool.getJedis();
//加锁
boolean b1 = RedisTool.tryGetDistributedLock(jedis, myMessage, random , 1000);
System.out.println(b1);
//逻辑代码,这里用线程睡眠代替
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//解锁
boolean b2 = RedisTool.releaseDistributedLock(jedis, myMessage, random );
System.out.println(b2);
}
}
解锁失败
4、场景三锁一正在运行(自动释放锁没有触发)此时锁二尝试加锁
public class LockTest2 {
public static void main(String[] args) {
//为锁的内容
String myMessage = "sb";
//随机数
String random = UUID.randomUUID().toString();
//获取redis
Jedis jedis = RedisPool.getJedis();
//加锁
boolean b1 = RedisTool.tryGetDistributedLock(jedis, myMessage, random , 10000);
System.out.println(b1);
//逻辑代码,这里用线程睡眠代替
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//解锁
boolean b2 = RedisTool.releaseDistributedLock(jedis, myMessage, random );
System.out.println(b2);
}
}
public class LockTest3 {
public static void main(String[] args) {
//为锁的内容
String myMessage = "sb";
//随机数
String random = UUID.randomUUID().toString();
//获取redis
Jedis jedis = RedisPool.getJedis();
//加锁
boolean b1 = RedisTool.tryGetDistributedLock(jedis, myMessage, random , 1000);
System.out.println(b1);
//逻辑代码,这里用线程睡眠代替
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//解锁
boolean b2 = RedisTool.releaseDistributedLock(jedis, myMessage, random );
System.out.println(b2);
}
}
尝试加锁失败
5、场景四锁一正在运行,锁二由于携带相同解锁密钥解锁一
public class LockTest2 {
public static void main(String[] args) {
//为锁的内容
String myMessage = "sb";
//指定数
String random = "lock1";
//获取redis
Jedis jedis = RedisPool.getJedis();
//加锁
boolean b1 = RedisTool.tryGetDistributedLock(jedis, myMessage, random, 10000);
System.out.println(b1);
//逻辑代码,这里用线程睡眠代替
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//解锁
boolean b2 = RedisTool.releaseDistributedLock(jedis, myMessage, random);
System.out.println(b2);
}
}
public class LockTest3 {
public static void main(String[] args) {
//为锁的内容
String myMessage = "sb";
//指定数
String random = "lock1";
//获取redis
Jedis jedis = RedisPool.getJedis();
//加锁
boolean b1 = RedisTool.tryGetDistributedLock(jedis, myMessage, random, 1000);
System.out.println(b1);
//逻辑代码,这里用线程睡眠代替
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//解锁
boolean b2 = RedisTool.releaseDistributedLock(jedis, myMessage, random);
System.out.println(b2);
}
}
锁二解锁成功,锁一解锁失败
四、商品抢购实践案例
1、样例代码
/**
* @author lichangyuan
* @create 2021-09-02 14:45
*/
@RestController
public class ShoppingController {
@RequestMapping("buy")
public String buy(@RequestParam("name") String name) {
//指定数
String random = UUID.randomUUID().toString();
//获取redis
Jedis jedis = RedisPool.getJedis();
//加锁,这里锁我设置为方法名,设置自动过期时间为3秒
boolean lockedState = RedisTool.tryGetDistributedLock(jedis, "buy", random, 3000);
//如果加锁成功
if (lockedState) {
//逻辑代码,这里用线程睡眠代替,设置抢购业务用时两秒
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//解锁
boolean state = RedisTool.releaseDistributedLock(jedis, "buy", random);
return "抢购者:" + name + "——抢购成功——解锁状态" + state + "——抢购时间" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
} else {
return "抢购者:" + name + "——抢购失败,其他人正在抢购——抢购时间" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
}
}
}
2、当抢购者一抢购完成后抢购者二抢购成功
3、当抢购者一抢购的同时抢购者二抢购失败
五、另一种分布式锁
我们发现可以通过expire续锁时间
1、通过守护线程保证锁时间大于业务执行时间
redisson里面有一个看门狗的机制,其实可以根据这个思路来,加锁成功后,启动一条守护线程,守护线程给锁进行无限续期!当锁不存在的时候就跳过,存在就续期,可以保证锁的时间大于业务时间!线程为守护线程的原因是,守护线程依赖于主线程,当主线程挂了之后,守护线程也会挂掉!这样能避免程序宕机之后,续期的线程依旧续期,造成死锁!
/**
* @author lichangyuan
* @create 2021-08-31 16:00
*/
public class RedisTool {
private static final String LOCK_SUCCESS = "OK";
private static final String SET_IF_NOT_EXIST = "NX";
private static final String SET_WITH_EXPIRE_TIME = "PX";
/**
* 加锁代码,尝试获取分布式锁
*
* @param jedis Redis客户端
* @param lockKey 锁
* @param requestId 请求标识
* @param expireTime 超期时间,时间为毫秒
* @return 是否获取成功
*/
public static boolean tryGetDistributedLock(Jedis jedis, String lockKey, String requestId, int expireTime) {
// 第一个参数key当锁,第二个参数value解锁人,第三个参数当key不存在时,我们进行set操作;若key已经存在,则不做任何操作
// 第四个参数标志第五个参数为设置锁时间,第五个参数设置时间
String result = jedis.set(lockKey, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime);
// 返回结果只有两种
// 1. 当前没有锁(key不存在),那么就进行加锁操作,并对锁设置个有效期,同时value表示加锁的客户端。
// 2. 已有锁存在,不做任何操作。
if (LOCK_SUCCESS.equals(result)) {
return true;
}
return false;
}
private static final Long RELEASE_SUCCESS = 1L;
/**
* 解锁代码,释放分布式锁
*
* @param jedis Redis客户端
* @param lockKey 锁
* @param requestId 请求标识
* @return 是否释放成功
*/
public static boolean releaseDistributedLock(Jedis jedis, String lockKey, String requestId) {
// 那么这段Lua代码的功能是什么呢?其实很简单,首先获取锁对应的value值,检查是否与requestId相等,如果相等则删除锁(解锁)。
// 那么为什么要使用Lua语言来实现呢?因为要确保上述操作是原子性的。
// 简单来说,就是在eval命令执行Lua代码的时候,Lua代码将被当成一个命令去执行,并且直到eval命令执行完成,Redis才会执行其他命令。
String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
Object result = jedis.eval(script, Collections.singletonList(lockKey), Collections.singletonList(requestId));
if (RELEASE_SUCCESS.equals(result)) {
return true;
}
return false;
}
/**
*
* 重新加锁代码,解决逻辑代码未完成而出现自动解锁
* @param jedis Redis客户端
* @param lockKey 锁
* @param requestId 请求标识
* @param expireTime 超期时间时间为秒
* @return
*/
public static boolean continuedDistributedLock(Jedis jedis, String lockKey, String requestId, int expireTime) {
String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('expire', KEYS[1] , ARGV[2]) else return 0 end";
Object result = jedis.eval(script, Collections.singletonList(lockKey), new ArrayList<String>() {
{
add(requestId);
add(String.valueOf(expireTime));
}
});
if (RELEASE_SUCCESS.equals(result)) {
return true;
}
return false;
}
}
2、守护线程工具类
实现目标,给程序开一个线程,当程序没完成是自动更新时间
/**
* 守护线程工具类
*
* @author lichangyuan
* @create 2021-09-01 14:16
*/
public class DaemonThread implements Runnable {
//为锁的内容
private String myMessage;
//指定数
private String random;
//获取redis
private Jedis jedis;
//锁持续时长
int lockTime;
//线程关闭的标记
private volatile Boolean signal;
void stop() {
this.signal = Boolean.FALSE;
}
public DaemonThread(Jedis jedis, String myMessage, String random, int lockTime) {
this.myMessage = myMessage;
this.random = random;
this.jedis = jedis;
this.lockTime = lockTime;
this.signal = Boolean.TRUE;
}
@Override
public void run() {
//将睡眠时间控制在自动解锁时间内
int waitTime = lockTime * 2 / 3;
while (signal) {
try {
Thread.sleep(waitTime*1000);
//如果自动解锁没触发,且程序还未完成,则续锁
if (RedisTool.continuedDistributedLock(jedis, myMessage, random, lockTime) == true) {
System.out.println("守护线程帮助锁续成功,时长" + lockTime);
} else {
//如果程序在自动解锁之前已完成手动解锁时,则不续锁
System.out.println("守护线程帮助锁续失败");
this.stop();
}
} catch (Exception e) {
System.out.println("守护线程帮助锁续出现异常");
}
}
System.out.println("处理线程已停止");
}
}
3、主业务代码举例
/**
* @author lichangyuan
* @create 2021-08-31 16:49
*/
public class LockTest5 {
public static void main(String[] args) {
//为锁的内容
String myMessage = "sb";
//指定数
String random = UUID.randomUUID().toString();
//获取redis
Jedis jedis = RedisPool.getJedis();
//默认锁持续时长
int lockTime = 3;
//创建主线程
Thread mainThread = new Thread(new Runnable() {
@Override
public void run() {
//加锁
boolean b1 = RedisTool.tryGetDistributedLock(jedis, myMessage, random, lockTime*1000);
System.out.println("主线程加锁" + b1);
//逻辑代码,这里用线程睡眠代替
try {
Thread.sleep(9000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//解锁
boolean b2 = RedisTool.releaseDistributedLock(jedis, myMessage, random);
System.out.println("主线程解锁" + b2);
}
}, "主线程");
//创建守护线程
Thread daemonThread = new Thread(new DaemonThread(jedis, myMessage, random, lockTime), "守护线程");
//设置守护线程
daemonThread.setDaemon(true);
//开始执行分进程
daemonThread.start();
//开始执行主进程
mainThread.start();
}
}
六、个人推荐使用RedisTemplate
1、依赖
<!--redis设置-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--redis连接池-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
2、逻辑代码一
@Autowired
StringRedisTemplate redisTemplate;
/**
* 公共锁key
*/
private final String LOCK_KEY = "lock";
public void best() {
//获取锁,设置有效期,防止程序异常没有释放锁导致死锁
UUID uid = UUID.randomUUID();
String str = uid.toString();
try {
boolean state = RedisTool.tryGetDistributedLock(redisTemplate, LOCK_KEY, str, 10);
if (state) {
//获取锁成功
//执行业务逻辑
try {
Thread.sleep(9000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
//获取锁失败
//快速失败,响应给客户端
}
} finally {
//释放锁
boolean b2 = RedisTool.releaseDistributedLock(redisTemplate, LOCK_KEY, str);
}
}
工具类
public class RedisTool {
/**
* 加锁代码,尝试获取分布式锁
*
* @param lockKey 锁
* @param requestId 请求标识
* @param expireTime 超期时间,时间为秒
* @return 是否获取成功
*/
public static boolean tryGetDistributedLock(RedisTemplate redisTemplate, String lockKey, String requestId, int expireTime) {
Boolean result = redisTemplate.opsForValue().setIfAbsent(lockKey, requestId, Duration.ofSeconds(expireTime));
return result;
}
/**
* @param lockKey 锁
* @param requestId 请求标识
* @return 是否释放成功
*/
public static boolean releaseDistributedLock(RedisTemplate redisTemplate, String lockKey, String requestId) {
//添加key值
String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
DefaultRedisScript<Boolean> redisScript = new DefaultRedisScript<>(script, Boolean.class);
Boolean result = (Boolean) redisTemplate.execute(redisScript, Collections.singletonList(lockKey), requestId);
return result;
}
}
3、逻辑代码二个人推荐
@Autowired
StringRedisTemplate redisTemplate;
/**
* 公共锁key
*/
private final String LOCK_KEY = "lock";
public void best2() {
//获取锁,设置有效期,防止程序异常没有释放锁导致死锁
UUID uid = UUID.randomUUID();
String str = uid.toString();
try {
Boolean b = redisTemplate.opsForValue().setIfAbsent(LOCK_KEY, str, Duration.ofSeconds(10));
if (b) {
//获取锁成功
//执行业务逻辑
try {
Thread.sleep(9000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
//获取锁失败
//快速失败,响应给客户端
}
} finally {
//释放锁
if (str.equals(redisTemplate.opsForValue().get(LOCK_KEY))) {
redisTemplate.delete(LOCK_KEY);
}
}
}