SpringBoot 中 使用 Redisson 实现全局锁-实例
一、引入 Redisson 依赖
<dependency> <groupId>org.redisson</groupId> <artifactId>redisson-spring-boot-starter</artifactId> <version>3.13.2</version> </dependency>
二、配置
可以兼容其他redis的配置(如 jedis)
redis: host: **.**.**.** (替换为服务器ip地址) port: 6379 (替换为redis服务的端口号) password: *** (替换为密码) database: ** (替换为实例号) timeout: 10000 testOnBorrow: true testOnReturn: true lettuce: pool: max-active: 10 max-wait: 10000 min-idle: 4 max-idle: 10
三、测试用例:
1 @Test 2 public void redissonTest() throws Exception { 3 // redisson(); // 需要手动停止,和 内容参数调整 4 } 5 6 public void redisson() throws Exception{ 7 Integer countStep = 0; 8 while (true){ 9 Thread.sleep(1000); 10 countStep++; 11 log.info("time:{}", countStep); 12 Thread buildVoucher = new Thread(new Runnable() { 13 @SneakyThrows 14 @Override 15 public void run() { 16 Integer billTypeId = 7; 17 String bussDateInner = "2021-05-25"; 18 String runningBillTypFlag = PublicConstants.RUNNING_VOUCHER_FLAG_BY_BILL_TYPE_STR + billTypeId +"-"+ bussDateInner; 19 RLock rLock = redissonClient.getLock(runningBillTypFlag); 20 try { 21 Integer waitTime = 7 * 1000; 22 boolean flag = rLock.tryLock(0, -1, TimeUnit.SECONDS); 23 if (flag) { 24 log.info("获取到锁,继续执行!"); 25 double floor = Math.floor(Math.random() * 10 + 1); 26 if(floor == 3 || floor == 7) throw new RuntimeException("异常。。"); 27 log.info("working…………"); 28 Thread.sleep(5 * 1000); 29 log.info("working used 5s. finished !"); 30 } else { 31 log.info("未能获取到锁,停止执行!"); 32 } 33 }catch (Exception e){ 34 logger.warn("内部异常:" + e.getMessage()); 35 } finally { 36 try { 37 rLock.unlock(); 38 log.info("It's unlocked."); 39 }catch (Exception e){ 40 log.error("解锁抛异常。。。解锁失败,未能解锁!"); 41 } 42 } 43 } 44 }); 45 buildVoucher.start(); 46 } 47 }