美文网首页
Redission分布式锁

Redission分布式锁

作者: CoderInsight | 来源:发表于2022-07-05 14:22 被阅读0次

    1,基本使用示例

    使用Redission对业务的核心处理方法进行加锁处理;

    (1),引入依赖

    <!--分布式锁-->
    <dependency>
        <groupId>org.redisson</groupId>
        <artifactId>redisson</artifactId>
        <version>3.6.5</version>
    </dependency>
    

    (2),创建配置类

    package com.zz.card.config;
    
    import org.redisson.Redisson;
    import org.redisson.api.RedissonClient;
    import org.redisson.config.Config;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    
    /**
     * @author wangyongqiang
     */
    @Configuration
    public class RedissonConfig {
     
        @Value("${spring.redis.host}")
        private String host;
     
        @Value("${spring.redis.port}")
        private String port;
     
        @Value("${spring.redis.password}")
        private String password;
     
        @Bean
        public RedissonClient getRedisson(){
     
            Config config = new Config();
            config.useSingleServer().setAddress("redis://" + host + ":" + port).setPassword(password);
            /// 添加主从配置(暂时使用的单节点的,未做配置,故未生效)
            // config.useMasterSlaveServers().setMasterAddress("").setPassword("").addSlaveAddress(new String[]{"",""});
            return Redisson.create(config);
        }
    }
    

    (3),给核心方法进行加锁的操作

    因为整个业务是核心,不要管是否很长,重点是他们是一个业务主体,而不是单个独立的业务。

    // 注入依赖
    @Autowired
    private RedissonClient redissonClient;
    // 针对整个方法整体添加,也就是说针对当前整个业务核心添加
    Result<?> result = new Result<>();
    // 指定锁的名字
    RLock rlock = redissonClient.getLock("redisson:lock:total");
    try {
        // lock
        rlock.lock(20, TimeUnit.SECONDS);
        // 核心业务方法
        result = xxxService.doXxx(param01, param02);
    }catch (Exception e){
        log.error("出现锁异常!\n{}", e.getMessage());
    }finally {
        // unlock
        rlock.unlock();
    }
    return result;
    

    2,关于分布式锁的原理剖析

    (1),lock与trylock的区别

    • LOCK.lock(): 此方式会始终处于等待中,即使调用B.interrupt()也不能中断,除非线程A调用LOCK.unlock()释放锁。

    • LOCK.tryLock(): 该处不会等待,获取不到锁并直接返回false,去执行下面的逻辑。

      /*
       * 尝试获取锁
       * waitTimeout 尝试获取锁的最大等待时间,超过这个值,则认为获取锁失败
       * leaseTime   锁的持有时间,超过这个时间锁会自动失效(值应设置为大于业务处理的时间,确保在锁有效期内业务能处理完)
       * 单位:通过TimeUnit指定对应的单位,这里使用的秒
       */
      boolean res = rLock.tryLock(20, 20, TimeUnit.SECONDS);
      

    相关文章

      网友评论

          本文标题:Redission分布式锁

          本文链接:https://www.haomeiwen.com/subject/fjrybrtx.html