Redisson实现分布式锁案例

Redisson实现分布式锁案例

  1. 引入依赖
<dependency>
    <groupId>org.redissongroupId>
    <artifactId>redisson-spring-boot-starterartifactId>
    <version>3.23.2version>
dependency>
  1. 创建Redisson配置类
@Configuration
public class RedissonConfig {
    @Bean
    public RedissonClient redissonClient() {
        Config config = new Config();
        config.useSingleServer().setAddress("redis://127.0.0.1:6379");
        // 如果有密码需要设置密码
        return Redisson.create(config);
    }
}
  1. 使用分布式锁
@RestController
public class LockController {
    @Resource
    private RedissonClient redissonClient;
 
    @RequestMapping("/lock")
    public String lockResource() throws InterruptedException {
        String lockKey = "myLock";
        // 获取锁
        RLock lock = redissonClient.getLock(lockKey);
        try {
            // 超时时间 20s, [tryLock 获取成功才需要释放锁,获取失败不需要释放锁]
            boolean isLocked = lock.tryLock(20, TimeUnit.SECONDS);
            if(isLocked) {
                // 成功获取到锁
                try {
                    TimeUnit.SECONDS.sleep(5);
                    return "成功获取到锁,并执行业务代码";
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    // 释放锁
                    lock.unlock();
                }
            } else {
                // 获取锁失败
                return "获取锁失败";
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "获取锁成功";
    }
}```

你可能感兴趣的:(Redis学习笔记,Redisson分布式锁)