目录
- 1、使用
- 2、加锁解析
- 1、getLock
- 2、tryLock
- 2.1、当ttl为null时为加锁成功,返回true,否则继续往下执行,判断是否超过等待时间,当前时间减去获取锁前时间就是获取锁花费时间。
- 2.2、tryAcquire(leaseTime, unit, threadId)
- 2.3 、renewExpiration
- 3、总结
 
- 3、解锁解析
- 3.1unlockInnerAsync
- 3.2cancelExpirationRenewal
 
1、使用
(1)、添加reddisson的maven依赖
  <dependency>
            <groupId>org.redisson</groupId>
            <artifactId>redisson</artifactId>
            <version>3.11.1</version>
  </dependency>
(2)、添加redisson配置
@Configuration
public class RedissonConfig {
    @Value(value = "${spring.redis.host}")
    private String host;
    @Value(value = "${spring.redis.port}")
    private int port;
//    @Value(value = "${spring.redis.database}")
//    private int database;
    @Value(value = "${spring.redis.password}")
    private String password;
    @Bean(destroyMethod = "shutdown")
    RedissonClient redisson() {
        Config config = new Config();
        //Redis多节点
        // config.useClusterServers()
        //     .addNodeAddress("redis://127.0.0.1:6379", "redis://127.0.0.1:7001");
        //Redis单节点
        SingleServerConfig singleServerConfig = config.useSingleServer();
        //可以用"rediss://"来启用SSL连接
        String address = "redis://" + host + ":" + port;
        singleServerConfig.setAddress(address);
        singleServerConfig.setPingConnectionInterval(30*1000);
        //设置 数据库编号
//        singleServerConfig.setDatabase(database);
        if(!StringUtil.isEmpty(password)){
            singleServerConfig.setPassword(password);
        }
        //连接池大小:默认值:64
        // singleServerConfig.setConnectionPoolSize()
        return Redisson.create(config);
    }
}
(3)、添加加解锁工具类
@Component
@Slf4j
public class LockUtil {
    @Autowired
    private RedissonClient redisson;
    /**
     * @description:看门狗分布式锁,统一获取方法
     * @param lockName 入参
     * @return boolean
     * @author zenglingsheng
     * @date 2024/1/4 16:09
     **/
    public boolean getLock(String lockName){
        boolean lockFlag = true;
        //使用分布式锁,防止重复提交,避免库存数量错误
        RLock rLock = redisson.getLock(lockName);
        try {
            lockFlag = rLock.tryLock(0, TimeUnit.SECONDS);
        } catch (Exception e) {
            log.error("*********Redission分布式锁方法执行异常*********redisKey={}", lockName);
        }
        return lockFlag;
    }
     /**
     * @description TODO 统一解锁方法
     * @param lockKey
     * @return boolean
     * @author zenglingsheng
     * @date 2024/2/2 17:11:25
     */
    public boolean unLock(String lockKey) {
        try {
            RLock lock = redisson.getLock(lockKey);
            //判断锁是否存在,并且判断是否当前线程加的锁
            if (null != lock && lock.isHeldByCurrentThread()) {
                lock.unlock();
                return true;
            }
        } catch (Exception e) {
            log.error(String.format("释放锁%s异常", lockKey));
        }
        return false;
    }
}
(4)、添加测试方法
 @RequestMapping("test111")
    public void doTask(){
        String lockName="locka";
        for(int i=0;i<2;i++){
            int finalI = i;
                long id =Thread.currentThread().getId();
                try{
                    System.out.println(finalI);
                    if(!lockUtil.getLock(lockName)){
                        System.out.println(id+":"+finalI+"未获取锁1");
                        return;
                    };
                    System.out.println(id+":"+finalI+"加锁成功");
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    lockUtil.unLock(lockName);
                    System.out.println(id + ":" + finalI + "释放锁");
                }
        }
    }
2、加锁解析
1、getLock

 getlock时,会新创建RedissonLock对象,其中entryName属性的值为UUID:锁名称。
2、tryLock
   @Override
    public boolean tryLock(long waitTime, TimeUnit unit) throws InterruptedException {
        return tryLock(waitTime, -1, unit);
    }
当不传leaseTime参数时,leaseTime默认为-1.
 
2.1、当ttl为null时为加锁成功,返回true,否则继续往下执行,判断是否超过等待时间,当前时间减去获取锁前时间就是获取锁花费时间。
(1)、time-获取锁花费时间如果小于等于0,说明已经超过等待时间,返回false获取锁失败。
 (2)、time-获取锁花费时间如果大于0,说明等待时间未超时,继续往下执行。从代码中可以看到还是执行获取锁继续判断是否等待超时。
 
2.2、tryAcquire(leaseTime, unit, threadId)

 从代码中可以看出leaseTime!=-1时执行tryLockInnerAsync使用lua脚本添加redis锁。
 
 KEYS[1]是锁名称,也是分布式锁的key,ARGV[1]时key的有效时间,ARGV[2]是UUID:线程id。①、第一个if判断是否存在KEYS[1],如果没有则添加hash类型的对象,hash的key是ARGV[2],value是1,然后重新设置KEYS[1]的过期时间,返回nil(就是key对应的vule为空),在java中为null。②、第二个if判断存在KEYS[1]中hash中的ARGV[2]有值时,会hash的value再加1,重新设置KEYS[1]过期时间,返回nil,这种是重入锁的情况,同一个线程可以多次加锁,每次hash中的value加1。③、如果有KEYS[1]但不是同一个线程,会返回当前KEYS[1]的有效时间。
 
 tryLockInnerAsync中ttlRemaining如果是null时,会进入scheduleExpirationRenewal
 
 EXPIRATION_RENEWAL_MAP是ConcurrentHashMap,其中中key是entryName(uuid:锁名)
 value是ExpirationEntry类型的对象。 如果当前key不存在,会添加当前线程号调用renewExpiration方法,当key存在时,如果线程号已存在会threadIds(LinkedHashMap)的value加1。
2.3 、renewExpiration
  private void renewExpiration() {
        ExpirationEntry ee = EXPIRATION_RENEWAL_MAP.get(getEntryName());
        if (ee == null) {
            return;
        }
        Timeout task = commandExecutor.getConnectionManager().newTimeout(new TimerTask() {
            @Override
            public void run(Timeout timeout) throws Exception {
                ExpirationEntry ent = EXPIRATION_RENEWAL_MAP.get(getEntryName());
                if (ent == null) {
                    return;
                }
                Long threadId = ent.getFirstThreadId();
                if (threadId == null) {
                    return;
                }
                RFuture<Boolean> future = renewExpirationAsync(threadId);
                future.onComplete((res, e) -> {
                    if (e != null) {
                        log.error("Can't update lock " + getName() + " expiration", e);
                        return;
                    }
                    if (res) {
                        // reschedule itself
                        renewExpiration();
                    }
                });
            }
        }, internalLockLeaseTime / 3, TimeUnit.MILLISECONDS);
        ee.setTimeout(task);
    }
HashedWheelTimer延时任务(可以参数这个博客)
 internalLockLeaseTime / 3=301000/3=101000 单位是毫秒,也就是10秒钟后执行执行renewExpirationAsync,lua脚本对key续期。

 如果当前KEYS1,ARGV2存在的话则重新设置有效时间为30s,返回1,否则返回0,说明锁已经释放了。
 
 如果lua返回ture,则嵌套renewExpiration方法,10秒钟后继续判断锁释放存在进而是否继续renewExpiration方法。
3、总结
1、reddison中维护了一个ConcurrentHashMap EXPIRATION_RENEWAL_MAP,key是uuid+锁名。value是ExpirationEntry对象,其中threadIds是Map<Long,Integer>,key是线程号,value是线程获取锁的次数。如果是重入锁value会大于1。会有延迟任务开新线程获取threadIds中线程,判断锁有没有释放,没有释放则重置有效时间,继续调用延迟任务,如果释放了则不会执行延迟任务。所以释放锁的重点就是清空EXPIRATION_RENEWAL_MAP的key。
3、解锁解析

 注意解锁时,判断锁是否当前线程。
3.1unlockInnerAsync

 执行lua脚本。①、如果不存在keys[1]的hash的key ARGV[3],执行返回null。
 ②、如果存在锁会扣减hash中的value。扣减后的value如果大于0则重置有效时间返回false.
 ③、如果扣减后的value不大于0会删除KEYS[1],并且发布KEYS[2]channelName。
 ④、如果解锁失败则返回null
 
3.2cancelExpirationRenewal

 如果ExpirationEntry中的threadId不为null则,只移除当前线程的threadId。
 如果threadId是null或者threadId是空,则移除当前的ExpirationEntry对象,延迟任务不再调用进而不再自动续期,锁被释放。


















