Redis分布式锁实现
分布式锁有三种实现方式:
- 数据库实现
- redis缓存实现
- zookeeper实现
本文主要讲解使用redis如果实现分布式锁
什么是分布式锁
分布式锁是在分布式系统中实现不同线程对资源的同步访问
什么时候用到分布式锁
分布式系统中,避免资源(如商品库存)扣减重复
在什么场景需要用到分布式锁
高并发(如抢购、秒杀)场景下,资源(如商品库存)扣减
如何使用redis实现分布式锁
分布式锁需要实现
- 互斥性。在任何给定时刻,只有一个线程可以持有锁
利用redis的setnx特性:设置redis服务中不存在的key则返回1(true),
如存在则返回0(false)
- 无死锁。即使锁定资源的客户端崩溃,在规定时间会自动释放资源
利用redis的setex特性,超时自动删除key
- 删除锁。用户使用完资源后释放
1、删除key
2、利用redis发布订阅机制,发布通知,让其他线程获取锁
redis锁实现类
package com.dawn.design.distributedRedis.service;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.types.Expiration;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* redis 分布式锁实现
* Created by Dawn 2019-09-13.
*/
public class RedisLockImpl implements Lock {
StringRedisTemplate stringRedisTemplate;
String resourceName; //资源名称
int timeOut;
/**构建一把锁
* @Description:
* @Param: [stringRedisTemplate, resourName, timeOut]
* @return:
* @Author: Dawn
* @Date:
*/
public RedisLockImpl(StringRedisTemplate stringRedisTemplate,String resourName,int timeOut){
this.stringRedisTemplate = stringRedisTemplate;
this.resourceName="lock_"+resourName;//资源
this.timeOut= timeOut;
}
@Override
public boolean tryLock() {//尝试获取锁
//set 命令 往redis存放锁标记
Boolean lockResult = stringRedisTemplate.execute(new RedisCallback<Boolean>() {
@Override
public Boolean doInRedis(RedisConnection redisConnection) throws DataAccessException {
String value="try connect";
//设置成功返回true(资源没有被占用),设置失败返回false(资源已经被占用),利用redis setnx 指令
Boolean result = redisConnection.set(resourceName.getBytes(),value.getBytes(), Expiration.seconds(timeOut), RedisStringCommands.SetOption.SET_IF_ABSENT);
System.out.println(result);
return result;
}
});
return lockResult;
}
Lock lock = new ReentrantLock();
@Override
public void lock() {//一直等待获到锁为止 不死不休
//一个jvm只有一把锁 只有一个线程获得锁
lock.lock();
try {
while (!tryLock()){
// 订阅指定的redis主题,接收锁释放信号
stringRedisTemplate.execute(new RedisCallback<Long>() {
@Override
public Long doInRedis(RedisConnection redisConnection) throws DataAccessException {
try {
CountDownLatch waiter = new CountDownLatch(1);
//subscribe 立马返回,异步请求 是否订阅完毕
redisConnection.subscribe((message,patten)->{
//收到通知 立刻抢锁
waiter.countDown();//计数器 -1
},("release_lock_"+resourceName).getBytes());
//等待有通知 才继续循环 等到计数器为0 再继续执行下面代码;同时等待设置超时时间,防止死锁
waiter.await(timeOut,TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 0L;
}
});
}
}finally {
lock.unlock();
}
}
@Override
public void unlock() {
// 直接删除资源标记
stringRedisTemplate.delete(resourceName);
// 通过redis 发布订阅机制发布一个通知给其他等待请求
stringRedisTemplate.execute(new RedisCallback<Long>() {
@Override
public Long doInRedis(RedisConnection redisConnection) throws DataAccessException {
//发布通知
Long received = redisConnection.publish(("release_lock_"+resourceName).getBytes(),"releaseLock".getBytes());
System.err.println("发布通知"+received);
return received;
}
});
}
@Override
public void lockInterruptibly() throws InterruptedException {
}
@Override
public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
return false;
}
@Override
public Condition newCondition() {
return null;
}
}
redis分布式锁使用
Lock redisLock=null;
@PostConstruct //servlet 构造函数执行后 执行
private void init(){
redisLock = new RedisLockImpl(redisTemplate,"dawn_redis_",10);
rLock=redisson.getLock("anyLock");
}
// redis 分布式锁
public boolean snapped2(long goodId,final String userId){
redisLock.lock();
boolean result = false;
try{
// 扣减库存
result = service.buyGoods(goodId);
System.err.println("抢购结果:"+result);
if(result){
long nums = service.getGoodCount(goodId);
// 模拟线程运行延时 随机睡眠
if(nums % 2==1) {
Thread.sleep(new Random().nextInt(500));
}
//更新缓存
redisTemplate.opsForValue().set(goodId + "", nums + "");
}
}catch (Exception ex){
ex.printStackTrace();
}finally {
redisLock.unlock();
}
return result;
}
redis分布式锁单元测试
@Autowired
RedisLockService lockService;
/**
* @Description: 循环创建N个线程 模拟用户请求
* @Param: []
* @return: void
* @Author: Dawn
* @Date: 2019-09-13
*/
@Rollback(value = false)
@Test
public void benchMark() throws InterruptedException {
//模拟的请求数量
final int threadNum =200;
// 到计算器 用于模拟高并发(信号抢机制)
CountDownLatch countDownLatch = new CountDownLatch(threadNum);
Thread[] threads = new Thread[threadNum];
for (int i = 0; i <threadNum ; i++) {
long goodId = 1;
Thread thread=new Thread(()->{
try {
//等待countDawnLatch值为0 其他线程就绪后再运行后序代码
countDownLatch.await();
//redis 分布式锁实现
lockService.snapped2(goodId,"Dawn");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
threads[i]=thread;
thread.start();
// 到计时器
countDownLatch.countDown();
}
Thread.sleep(50000L);
}