Skip to content

AnthonyZero/distributed-lock-redis

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

32 Commits
 
 
 
 
 
 
 
 

Repository files navigation

distributed-lock-redis

基于Redis实现的简单分布式锁

项目结构

环境依赖

Redis 2.6.12 版本及以上

Maven

特征

  • 高性能
  • 非阻塞
  • 自动续期

使用

添加maven依赖

<dependency>
    <groupId>com.anthonyzero</groupId>
    <artifactId>distributed-lock-redis-core</artifactId>
    <version>1.0.0</version>
</dependency>

注入IOC

@Configuration
public class DistributedLockConfig {
    @Autowired
    private JedisPool jedisPool;
    /**
     * 默认分布式锁(不开启续期)
     * @return
     */
    @Bean(name = "defaultLock")
    @Primary
    public RedisLock defaultBuild() {
        RedisLock redisLock = new RedisLock.Builder(jedisPool)
                .expireTime(50) //过期时间50秒 不设置默认为60秒
                .build();
        return redisLock;
    }
    /**
     * 分布式锁(开启了续期)
     * @return
     */
    @Bean(name = "renewalLock")
    public RedisLock openRenewalBuild() {
        RedisLock redisLock = new RedisLock.Builder(jedisPool)
                .expireTime(60) //设置过期时间 默认为60秒
                .openRenewal(true) //开启守护线程续期 默认不开启
                .renewalPercentage(0.5) //每次续期的时间占过期时间的比例 0到1的范围(默认为0.6)
                .build();
        return redisLock;
    }
}

使用分布式锁 模拟业务执行

    /**
     * 默认锁(不开启续期)
     */
    @Autowired
    private RedisLock redisLock;
    /**
     * 锁(开启续期)
     */
    @Autowired
    @Qualifier("renewalLock")
    private RedisLock renewalLock;

    @Test
    public void start() {
        String key = "key";
        String request = UUID.randomUUID().toString();
        boolean flag = renewalLock.lock(key, request, 10);
        if (flag) { //获取锁成功
            try {
                //模拟业务执行
                Thread.sleep(10 * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                renewalLock.unlock(key, request);
            }
        }
    }

资料

博客文章说明Redis分布式锁

About

🔒Distributed lock based on redis

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published