什么是redis分布式锁?
与分布式锁相对就的是单机锁,我们在写多线程程序时,避免同时操作一个共享变量产生数据问题,通常会使用一把锁来互斥以保证共享变量的正确性,其使用范围是在同一个进程中。如果换做是多个进程,需要同时操作一个共享资源,如何互斥呢?现在的业务应用通常是微服务架构,这也意味着一个应用会部署多个进程,多个进程如果需要修改MySQL中的同一行记录,为了避免操作乱序导致脏数据,此时就需要引入分布式锁了。
Redis做分布式锁时需要注意哪些问题?或者一个靠谱分布式锁需要具备的条件和刚需?
- 独占性:任何时候有且只能有一个线程持有
- 高可用:若redis集群环境下,不能因为某一个节点挂了而出现获取锁和释放锁失败的情况即高并发情况下,性能依旧好使
- 防死锁:杜绝死锁,必须有超时控制机制或者撤销操作,有个兜底终止跳出方案
- 不乱抢:防止张冠李戴,禁止unlock别人的锁,自己加的锁只能自己释放
- 重入性:同一个节点的同一个线程如果获取锁之后,它还可以再次获取这个锁
下面是基于工厂模式、lua脚本自定义实现的redis分布式锁工具类:
package com.atguigu.util;
import cn.hutool.core.util.IdUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import javax.annotation.Resource;
import java.util.concurrent.locks.Lock;
// 引入了工厂类,从工厂获取即可
@Component
public class DistributedLockFactroy {
@Resource
private StringRedisTemplate stringRedisTemplate;
private String lockName;
private String uuid;
private DistributedLockFactroy(){
this.uuid = IdUtil.simpleUUID();
}
public Lock getDistributedLock(String lockType, String lockName){
this.lockName = lockName;
if(StringUtils.equalsIgnoreCase(lockType,"redis")){
return new RedisDistributedLock(redisTemplate,lockName,uuid);
}else if(StringUtils.equalsIgnoreCase(lockType,"zookeeper")){
//TODO 返回一个zookeeper实现的锁
return null;
}else if(StringUtils.equalsIgnoreCase(lockType,"mysql")){
//TODO 返回一个zookeeper实现的锁
return null;
}
return null;
}
}
package com.atguigu.util;
import org.jetbrains.annotations.NotNull;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import java.util.Arrays;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
/**
* 自研的redis分布式锁
*/
public class RedisDistributedLock implements Lock {
private StringRedisTemplate stringRedisTemplate;
private String lockName;
private String value;
private long expireTime;
public RedisDistributedLock(StringRedisTemplate stringRedisTemplate, String lockName,String uuid) {
this.stringRedisTemplate = stringRedisTemplate;
this.lockName = lockName;
this.value = uuid + ":"+Thread.currentThread().getId();
this.expireTime = 30L;
}
@Override
public void lock() {
tryLock();
}
@Override
public boolean tryLock() {
try {tryLock(-1L, TimeUnit.SECONDS);} catch (InterruptedException e) {e.printStackTrace();}
return false;
}
@Override
public boolean tryLock(long time, @NotNull TimeUnit unit) throws InterruptedException{
if(time == -1L){
// 加锁
String script =
"if redis.call('exists',KEYS[1]) == 0 or redis.call('hexists',KEYS[1],ARGV[1]) == 1 then " +
" redis.call('hincrby',KEYS[1],ARGV[1],1) " +
" redis.call('expire',KEYS[1],ARGV[2])" +
" return 1 " +
"else" +
" return 0 " +
"end";
// 自旋加锁
while (!stringRedisTemplate.execute(new DefaultRedisScript<>(script, Boolean.class), Arrays.asList(lockName), value, String.valueOf(expireTime))){
// 加锁失败,睡眠60毫秒然后重试
try { TimeUnit.MICROSECONDS.sleep(60); } catch (InterruptedException e) { e.printStackTrace(); }
};
//新建一个后台扫描程序,来检测key目前的ttl,是否到我们设定的1/2,1/2实现续期
renewExpire(); // 自动续期方法
return true;
}
return false;
}
private void renewExpire() {
//自动续期脚本
String script =
" if redis.call('hexists',KEYS[1],ARGV[1]) == 1 then " +
" return redis.call('expire',KEYS[1],ARGV[2]) " +
" else" +
" return 0 " +
" end ";
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if(stringRedisTemplate.execute(new DefaultRedisScript<>(script,Boolean.class),Arrays.asList(lockName),value,String.valueOf(expireTime))){
renewExpire();
};
}
},(this.expireTime*1000)/3);
}
@Override
public void unlock() {
// lua 脚本是c语言编写的,nil == false 0 == false 1==true
String script =
"if redis.call('hexists',KEYS[1],ARGV[1]) == 0 then " +
"return nil " +
"elseif redis.call('hincrby',KEYS[1],ARGV[1],-1) == 0 then " +
"return redis.call('del',KEYS[1]) " +
"else " +
"return 0 " +
"end";
Long flag = stringRedisTemplate.execute(new DefaultRedisScript<>(script, Long.class), Arrays.asList(lockName),value, String.valueOf(expireTime));
if(null == flag) throw new RuntimeException("this lock doesn't exist");
}
@Override
public void lockInterruptibly() throws InterruptedException {
}
@NotNull
@Override
public Condition newCondition() {
return null;
}
}