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     }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章