作者:Nan,气冲天.


前言

在Java并发编程中,我们通常使用到synchronized 、Lock这两个线程锁,Java中的锁,只能保证对同一个JVM中的线程有效。而在分布式集群环境,这个时候我们就需要使用到分布式锁。

实现分布式锁的方案

  • 基于数据库实现分布式锁
  • 基于缓存Redis实现分布式锁
  • 基于Zookeeper的临时序列化节点实现分布式锁

Redis实现分布式锁

场景:在高并发的情况下,可能有大量请求来到数据库查询三级分类数据,而这种数据不会经常改变,可以引入缓存来存储第一次从数据库查询出来的数据,其他线程就可以去缓存中获取数据,来减少数据库的查询压力。

在集群的环境下,就可以使用分布式锁来控制去查询数据库的次数。

阶段一

redis 自旋多把锁 php redis 自旋锁加锁_List

private  Map<String, List>  getCatalogJsonDBWithRedisLock() {// 去Redis中抢占位置
        Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent("lock", "1111");if (lock){// 抢到锁了 执行业务Map<String, List> dataFromDb = getDataFromDb();// 删除锁
            stringRedisTemplate.delete("lock");return dataFromDb;
        }else {// 自旋获取锁// 休眠100mstry {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }return getCatalogJsonDBWithRedisLock();
        }
    }

得到锁以后,我们应该再去缓存中确定一次,如果没有才需要继续查询,从数据库查到数据以后,应该先把数据放入缓存中,再将数据返回。

private Map<String, List> getDataFromDb() {// 得到锁以后,我们应该再去缓存中确定一次,如果没有才需要继续查询String catalogJson = stringRedisTemplate.opsForValue().get("catalogJson");if (!StringUtils.isEmpty(catalogJson)) {// 反序列化 转换为指定对象Map<String, List> result = JSON.parseObject(catalogJson, new 
            TypeReference<Map<String, List>>() {});return result;
        }
        System.out.println("查询数据库了......");// 查询所有分类数据在进行刷选List categoryEntityList = baseMapper.selectList(null);// 查询一级分类List leave1Categorys = getParent_cid(categoryEntityList, 0L);Map<String, List> listMap = leave1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), l1 -> {List categoryL2List = getParent_cid(categoryEntityList, l1.getCatId());List catelog2Vos = null;if (categoryL2List != null) {
                catelog2Vos = categoryL2List.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(l2.getParentCid().toString(), null, l2.getCatId().toString(), l2.getName());List categoryL3List = getParent_cid(categoryEntityList, 
                                                                        l2.getCatId());if (categoryL3List != null) {List catelog3Vos =  
                            categoryL3List.stream().map(l3 -> {
                            Catelog2Vo.Catelog3Vo catelog3Vo = new 
                               Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), 
                                                      l3.getCatId().toString(), 
                                                      l3.getName());return catelog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(catelog3Vos);
                    }return catelog2Vo;
                }).collect(Collectors.toList());
            }return catelog2Vos;
        }));// 最后需将数据加入的缓存中String jsonString = JSON.toJSONString(listMap);
        stringRedisTemplate.opsForValue().set("catalogJson", jsonString, 1L, 
                                              TimeUnit.DAYS);return listMap;
    }
阶段二

redis 自旋多把锁 php redis 自旋锁加锁_redis_02

private  Map<String, List>  getCatalogJsonDBWithRedisLock() {// 去Redis中抢占位置
        Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent("lock", "1111");if (lock){// 抢到锁了 执行业务// 设置过期时间
            stringRedisTemplate.expire("lock",3,TimeUnit.SECONDS);Map<String, List> dataFromDb = getDataFromDb();// 删除锁
            stringRedisTemplate.delete("lock");return dataFromDb;
        }else {// 自旋获取锁// 休眠100mstry {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }return getCatalogJsonDBWithRedisLock();
        }
    }
阶段三

redis 自旋多把锁 php redis 自旋锁加锁_redis 自旋多把锁_03

private  Map<String, List>  getCatalogJsonDBWithRedisLock() {// 去Redis中抢占位置  保证原子性
      Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent("lock", "1111",300,TimeUnit.SECONDS);if (lock){// 抢到锁了 执行业务Map<String, List> dataFromDb = getDataFromDb();// 删除锁
            stringRedisTemplate.delete("lock");return dataFromDb;
        }else {// 自旋获取锁// 休眠100mstry {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }return getCatalogJsonDBWithRedisLock();
        }
    }
阶段四

redis 自旋多把锁 php redis 自旋锁加锁_redis_04

private  Map<String, List>  getCatalogJsonDBWithRedisLock() {String uuid = UUID.randomUUID().toString();// 去Redis中抢占位置  保证原子性
        Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent("lock", uuid,300,TimeUnit.SECONDS);if (lock){// 抢到锁了 执行业务Map<String, List> dataFromDb = getDataFromDb();String s = stringRedisTemplate.opsForValue().get("lock");if (uuid.equals(s)){// 删除锁
                stringRedisTemplate.delete("lock");
            }return dataFromDb;
        }else {// 自旋获取锁// 休眠100mstry {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }return getCatalogJsonDBWithRedisLock();
        }
    }
阶段五

redis 自旋多把锁 php redis 自旋锁加锁_关抢占 自旋锁_05

private  Map<String, List>  getCatalogJsonDBWithRedisLock() {String uuid = UUID.randomUUID().toString();// 去Redis中抢占位置  保证原子性
        Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent("lock", uuid,300,TimeUnit.SECONDS);if (lock){// 抢到锁了 执行业务Map<String, List> dataFromDb = getDataFromDb();String s = stringRedisTemplate.opsForValue().get("lock");// 获取值对比+对比成功删除=原子操作 Lua脚本解锁String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1] then\n" +"    return redis.call(\"del\",KEYS[1])\n" +"else\n" +"    return 0\n" +"end";
            Long lock1 = stringRedisTemplate.execute(new DefaultRedisScript(script, Long.class) , Arrays.asList("lock"), uuid);return dataFromDb;
        }else {// 自旋获取锁// 休眠100mstry {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }return getCatalogJsonDBWithRedisLock();
        }
    }
小总结
  1. stringRedisTemplate.opsForValue().setIfAbsent(“lock”, uuid,300,TimeUnit.SECONDS);
  2. stringRedisTemplate.execute(new DefaultRedisScript(script, Long.class) , Arrays.asList(“lock”), uuid);
  3. 使用Redis来实现分布式锁需保证加锁【占位+过期时间】和删除锁【判断+删除】操作的原子性。
  4. Redis锁的过期时间小于业务的执行时间该如何自动续期?
  • 设置一个比业务耗时更长的过期时间
  • Redisson的看门狗机制

Redisson实现分布式锁

Redisson 简介

Redisson是一个在Redis的基础上实现的Java驻内存数据网格(In-Memory Data Grid)。它不仅提供了一系列的分布式的Java常用对象,还提供了许多分布式服务。其中包括(BitSetSetMultimapSortedSetMapListQueueBlockingQueueDequeBlockingDequeSemaphoreLockAtomicLongCountDownLatchPublish / SubscribeBloom filterRemote serviceSpring cacheExecutor serviceLive Object serviceScheduler service) Redisson提供了使用Redis的最简单和最便捷的方法。Redisson的宗旨是促进使用者对Redis的关注分离(Separation of Concern),从而让使用者能够将精力更集中地放在处理业务逻辑上。

原理机制

redis 自旋多把锁 php redis 自旋锁加锁_redis_06

集成Spring Boot 项目

  1. 引入依赖 【可引入Spring Boot 封装好的starter】
org.redisson
redisson
3.12.0
  1. 添加配置类
@Configuration
public class MyRedissonConfig {

@Bean(destroyMethod = "shutdown")
public RedissonClient redissonClient(){
// 创建配置  记得加redis://
        Config config = new Config();
        config.useSingleServer().setAddress("redis://192.168.26.104:6379");
// 根据配置创建RedissClient客户端
        RedissonClient redissonClient = Redisson.create(config);
return redissonClient;
    }
}
可重入锁 Reentrant Lock
  1. 获取一把锁 redissonClient.getLock(“my-lock”);
  2. 给业务代码加锁 lock.lock();
  3. 解锁 lock.unlock();
  4. 看门狗机制 锁会自动续期
@ResponseBody
    @GetMapping("/hello")
public String hello(){
// 1、获取一把锁,只要锁的名字一样,就是同一把锁
        RLock lock = redissonClient.getLock("my-lock");
// 加锁
// 阻塞式等待,默认加的锁都是【看门狗时间】30s时间
//1)、锁的自动续期,如果业务超长,运行期间自动给锁续上新的30s,不用担心业务时间长,锁自动过期被删掉
//2)、加锁的业务只要运行完成,就不会给当前锁续期,即使不手动解锁,锁默认在30s以后自动删除
lock.lock();
try {
            System.out.println("加锁成功......."+Thread.currentThread().getId());
            Thread.sleep(30000);
        } catch (InterruptedException e) {

        }finally {
// 释放锁   不会出现死锁状态 如果没有执行解锁,锁有过期时间,过期了会将锁删除
lock.unlock();
            System.out.println("解锁成功......"+Thread.currentThread().getId());
        }
return "hello";
    }

lock方法有一个重载方法 lock(long leaseTime, TimeUnit unit)

public void lock(long leaseTime, TimeUnit unit) {
try {
this.lock(leaseTime, unit, false);
        } catch (InterruptedException var5) {
throw new IllegalStateException();
        }
    }

注意:指定了过期时间后,不会进行自动续期,此时如果有多个线程,即便业务还然在执行,过期时间到了之后,锁就会被释放,其他线程就会争抢到锁。

二个方法对比

  1. 如果设置了过期时间,就会发生执行脚本给Redis,进行占锁,设置过期时间为我们指定的时间。
  2. 未设置过期时间,就会使用看门狗的默认时间LockWatchdogTimeout 30*1000
  3. redis 自旋多把锁 php redis 自旋锁加锁_redis_07

  4. 只有没有指定过期的时间的方法才有自动续期功能
  5. 自动续期实现机制 :只要占锁成功,就会自动启动一个定时任务【重新给锁设置过期时间,新的过期时间就是看门狗的默认时间】,每隔10s【( internalLockLeasTime)/3】都会自动续期。
  6. redis 自旋多把锁 php redis 自旋锁加锁_Redis_08

  7. 持有锁的机器宕机问题,因为来不及续期,所以锁自动被释放,当该机再次恢复时,因为其后台守护线程是ScheduleTask,所以恢复后会马上执行一次watchDog续期逻辑,执行过程中,它会感知到自己已经丢失了锁,所以不存在共同持有的问题。
读写锁 ReadWriteLock

保证一定能读到最新数据,修改期间,写锁是一个互斥锁,读锁是一个共享锁。

  1. 写+读 写锁没有释放,读锁就得等待
  2. 写+写 阻塞方式
  3. 读+写 写锁等待读锁释放才能加锁
  4. 读+读 相当于无锁,并发读
@ResponseBody
    @GetMapping("/write")
public String writeLock(){
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("rw-lock");
        RLock rLock = readWriteLock.writeLock();
        String s = "";
try {
            rLock.lock();
            System.out.println("写锁加锁成功......"+Thread.currentThread().getId());
            s = UUID.randomUUID().toString();
            stringRedisTemplate.opsForValue().set("writeLock",s);
            Thread.sleep(30000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            rLock.unlock();
            System.out.println("写锁释放成功......"+Thread.currentThread().getId());
        }
return s;
    }

    @ResponseBody
    @GetMapping("/read")
public String readLock(){
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("rw-lock");
        RLock rLock = readWriteLock.readLock();
        rLock.lock();
        String s = "";
try{
            System.out.println("读锁加锁成功......"+Thread.currentThread().getId());
            s = stringRedisTemplate.opsForValue().get("writeLock");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            System.out.println("读锁释放成功......"+Thread.currentThread().getId());
            rLock.unlock();
        }
return s;
    }
信号量 Semaphore

使用信号量来做分布式限流

@ResponseBody
@GetMapping("/park")
public String park() throws InterruptedException {
        RSemaphore park = redissonClient.getSemaphore("park");
// 抢占一个车位
boolean b = park.tryAcquire();
// 如果还可以抢占到 就执行业务代码
if (b){
// 执行业务代码
        }else {
return "error";
        }
return "ok=>"+b;
    }

@ResponseBody
@GetMapping("/go")
public String go() {
        RSemaphore park = redissonClient.getSemaphore("park");
//  释放一个车位
        park.release();
return "ok";
    }
闭锁 CountDownLatch

模拟场景:等待班级放学走了,保安关校门。

@ResponseBody
@GetMapping("/lockdoor")
public String lockDoor() throws InterruptedException {
        RCountDownLatch door = redissonClient.getCountDownLatch("door");
        door.trySetCount(5);
// 等待闭锁完成
        door.await();
return "放假了.....";
    }

@GetMapping("/gogogo/{id}")
@ResponseBody
public String gogogo(@PathVariable("id")Long id){
        RCountDownLatch door = redissonClient.getCountDownLatch("door");
// 计数减一
        door.countDown();
return id+"班级走了....";
    }
Redisson解决上面Redis查询问题
/**
     * 使用Redisson分布式锁来实现多个服务共享同一缓存中的数据
     * @return
     */
    private Map<String, List> getCatalogJsonDBWithRedissonLock() {
        RLock lock = redissonClient.getLock("catalogJson-lock");// 该方法会阻塞其他线程向下执行,只有释放锁之后才会接着向下执行
        lock.lock();Map<String, List> dataFromDb = null;try {
            dataFromDb = getDataFromDb();
        }finally {
            lock.unlock();
        }return dataFromDb;
    }