基于redis分布式并发锁的实现理论原理:
https://github.com/huangz1990/redis/commit/18dbaee4f40f435970a09da427b8f45bd26b4072#diff-b643df753e12d0d07a872f91487c957dR34
主要概念:
1、如何争锁
2、锁的表达方式
3、避免死锁
4、死锁过期
网上找了一些资料:针对redisTemplate 实现的,但是在试用过的过程中也遇到了一些坑:
public interface DistributionLock {
//加锁成功 返回加锁时间
Long lock(String lockKey, String threadname);
//解锁 需要更加加锁时间判断是否有权限
void unlock(String lockKey, Long lockvalue, String threadname);
}
public class RedisDistributionLock implements DistributionLock{
private static final long LOCK_TIMEOUT = 10 * 1000; //加锁超时时间 单位毫秒 意味着加锁期间内执行完操作 如果未完成会有并发现象
private static final Logger LOG = LoggerFactory.getLogger(RedisDistributionLock.class); //redis锁日志
@Autowired
@Qualifier("redisTemplateSerializable")
private RedisTemplate<Serializable, Serializable> redisTemplate;
//如果遇到多个RedisTemplate可以根据名字进行注入
@Resource(name = "redisTemplateString")
private RedisTemplate<String, String> redisTemplateString;
/**
* 取到锁加锁 取不到锁一直等待直到获得锁
*/
@Override
public synchronized Long lock(final String lockKey, String threadname) {
LOG.info(threadname + "开始执行加锁");
while (true) { //循环获取锁
final Long lock_timeout = System.currentTimeMillis() + LOCK_TIMEOUT + 1; //锁时间
if (redisTemplate.execute(new RedisCallback<Boolean>() {
@Override
public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
JdkSerializationRedisSerializer jdkSerializer = new JdkSerializationRedisSerializer();
byte[] value = jdkSerializer.serialize(lock_timeout);
return connection.setNX(lockKey.getBytes(), value);
}
})) { //如果加锁成功
LOG.info(threadname + "---加锁成功---lockKey:{},lock_timeout:{}",lockKey,lock_timeout);
redisTemplate.expire(lockKey, LOCK_TIMEOUT, TimeUnit.MILLISECONDS); //设置超时时间,释放内存
return lock_timeout;
}else {
Long currt_lock_timeout_Str =
(Long) redisTemplate.opsForValue().get(lockKey); // redis里的时间
if (currt_lock_timeout_Str != null && currt_lock_timeout_Str < System.currentTimeMillis()) { //锁已经失效
// 判断是否为空,不为空的情况下,说明已经失效,如果被其他线程设置了值,则第二个条件判断是无法执行
Long old_lock_timeout_Str = (Long) redisTemplate.opsForValue().getAndSet(lockKey, lock_timeout);
// 获取上一个锁到期时间,并设置现在的锁到期时间
if (old_lock_timeout_Str != null && old_lock_timeout_Str.equals(currt_lock_timeout_Str)) {
// 如过这个时候,多个线程恰好都到了这里,但是只有一个线程的设置值和当前值相同,他才有权利获取锁
LOG.info(threadname + "---加锁成功---lockKey:{},lock_timeout:{}",lockKey,lock_timeout);
redisTemplate.expire(lockKey, LOCK_TIMEOUT, TimeUnit.MILLISECONDS); //设置超时时间,释放内存
return lock_timeout;//返回加锁时间
}
}
}
try {
LOG.info(threadname + "等待加锁,睡眠100毫秒");
TimeUnit.MILLISECONDS.sleep(100);//睡眠100毫秒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
public synchronized void unlock(String lockKey, Long lockvalue, String threadname) {
Long currt_lock_timeout_Str = (Long) redisTemplate.opsForValue().get(lockKey); // redis里的时间
if (currt_lock_timeout_Str != null && currt_lock_timeout_Str .equals( lockvalue)) {//如果是加锁者 则删除锁 如果不是则等待自动过期 重新竞争加锁
redisTemplate.delete(lockKey); //删除键
LOG.info(threadname + "解锁成功:lockKey{},lockValue:{}",lockKey,lockvalue);
}
}
}
关键点:这里的集中序列化方式一定要配置,不然取不到值,调试了很久
@Bean("redisTemplateSerializable")
RedisTemplate<Serializable,Serializable> redisTemplateSerializable(RedisConnectionFactory connectionFactory) {
RedisTemplate<Serializable, Serializable> template = new RedisTemplate<Serializable, Serializable>();
template.setConnectionFactory(connectionFactory);
/**
* 添加属性
*/
StringRedisSerializer stringRedisSerializernew =new StringRedisSerializer();
template.setKeySerializer(stringRedisSerializernew);
template.setHashKeySerializer(stringRedisSerializernew);
JdkSerializationRedisSerializer jdkSerializationRedisSerializer =new JdkSerializationRedisSerializer();
template.setValueSerializer(jdkSerializationRedisSerializer);
template.setHashValueSerializer(jdkSerializationRedisSerializer);
return template;
}
测试代码:要注意的是:最好在外层加同步锁,否则会出现一种奇怪的现象,就是每次都是到锁过期才释放锁,抢先进入任务的线程,会被堵在释放锁的外面:
@RequestMapping(value = {"/redis/dist/test/{lockKey}"},method = RequestMethod.GET)
public void testDistLock(@PathVariable("lockKey") String lockKey1){
AtomicBoolean isFinish = new AtomicBoolean(false);
final ReentrantLock lock = new ReentrantLock();
for(int i=0;i<1;i++){
final String lockKey = lockKey1;
new Thread(new Runnable() {
@Override
public void run() {
try {
lock.lockInterruptibly();
Long lockValue = redisDistributionLock.lock(lockKey,Thread.currentThread().getName());
System.out.println("获得锁:"+lockValue);
System.out.println("执行任务......");
// redisDistributionLock.unlock(lockKey,lockValue,Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
}).start();
}
}