//RedisPoolProperties @Data public class RedisPoolProperties { private int maxIdle; private int minIdle; private int maxActive; private int maxWait; private int connTimeout; private int soTimeout; /** * 池大小 */ private int size; }
//RedisProperties @ConfigurationProperties(prefix = "spring.redis", ignoreUnknownFields = false) @Data public class RedisProperties { private int database; /** * 等待节点回复命令的时间。该时间从命令发送成功时开始计时 */ private int timeout; private String password private String mode; /** * 池配置 */ private RedisPoolProperties pool; /** * 单机信息配置 */ private RedisSingleProperties single; }
//RedisSingleProperties @Data public class RedisSingleProperties { private String address1; private String address2; private String address3; }
④. controller代码展示
@RestController @Slf4j public class RedLockController { public static final String CACHE_KEY_REDLOCK = "TANGZHI_REDLOCK"; @Autowired RedissonClient redissonClient1; @Autowired RedissonClient redissonClient2; @Autowired RedissonClient redissonClient3; @GetMapping(value = "/redlock") public void getlock() { //CACHE_KEY_REDLOCK为redis 分布式锁的key RLock lock1 = redissonClient1.getLock(CACHE_KEY_REDLOCK); RLock lock2 = redissonClient2.getLock(CACHE_KEY_REDLOCK); RLock lock3 = redissonClient3.getLock(CACHE_KEY_REDLOCK); RedissonRedLock redLock = new RedissonRedLock(lock1, lock2, lock3); boolean isLockBoolean; try { //waitTime 抢锁的等待时间,正常情况下等3秒 //leaseTime就是redis key的过期时间,正常情况下等5分钟300秒。 isLockBoolean = redLock.tryLock(3, 300, TimeUnit.SECONDS); log.info("线程{},是否拿到锁:{} ",Thread.currentThread().getName(),isLockBoolean); if (isLockBoolean) { System.out.println(Thread.currentThread().getName()+"\t"+"---come in biz"); //业务逻辑,忙10分钟 try { TimeUnit.MINUTES.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } } catch (Exception e) { log.error("redlock exception ",e); } finally { // 无论如何, 最后都要解锁 redLock.unlock(); } } }
⑤. 测试:http://localhost:9090/redlock
[root@TANG2021 ~]# docker exec -it redis-master-1 redis-cli 127.0.0.1:6379> keys * 1) "TANGZHI_REDLOCK" 127.0.0.1:6379> type TANGZHI_REDLOCK hash 127.0.0.1:6379> hgetall TANGZHI_REDLOCK 1) "ca512c4b-f05f-4578-9b8f-45e2e35aa0d7:50" 2) "1"