使用 redistemplate 實現鎖的方案


springboot + redistemplate 實現鎖的方案

 

  • 1、通過set命令設置鎖
  • 2、判斷返回結果是否是OK
    • 1)Nil,獲取失敗,結束或重試(自旋鎖)
    • 2)OK,獲取鎖成功
      • 執行業務
      • 釋放鎖,DEL 刪除key即可
  • 3、異常情況,服務宕機。超時時間EX結束,會自動釋放鎖

 

代碼清晰簡潔 廢話不多說直接上demo

這里使用的單元測試;歡迎研究討論,下一篇講解分布式鎖;

 1 package com.example.demo.controller;
 2 
 3 import org.junit.Test;
 4 import org.junit.runner.RunWith;
 5 import org.slf4j.Logger;
 6 import org.slf4j.LoggerFactory;
 7 import org.springframework.beans.factory.annotation.Autowired;
 8 import org.springframework.boot.test.context.SpringBootTest;
 9 import org.springframework.data.redis.core.RedisTemplate;
10 import org.springframework.test.context.junit4.SpringRunner;
11 
12 import java.util.concurrent.TimeUnit;
13 
14 /**
15  * Description: demo <br>
16  *
17  * @author Liang lp
18  * Date: 2019/12/13 12:27 <br>
19  */
20 @SpringBootTest
21 @RunWith(SpringRunner.class)
22 public class demo {
23 
24     private static final Logger log = LoggerFactory.getLogger(demo.class);
25 
26     @Autowired
27     RedisTemplate redisTemplate;
28 
29     @Test
30     public void test() {
31         String key = "test";
32         //創建鎖
33         boolean isLock = lock(key, 1, 50);
34         // 判斷是否獲取鎖
35         if (!isLock) {
36             //獲取所失敗
37             log.info("獲取所失敗 ");
38             return;
39         }
40         try {
41             log.info("獲取鎖成功,開始執行邏輯");
42             //模擬程序執行
43             Thread.sleep(2000);
44         } catch (Exception e) {
45             log.error("程序執行異常{}", e);
46         } finally {
47             // 釋放鎖
48             deleteLock(key);
49             log.info("執行完畢。釋放鎖完成;");
50         }
51     }
52 
53     /**
54      * 創建鎖
55      *
56      * @param key         鎖的Key
57      * @param value       值(隨便寫毫無意義)
58      * @param releaseTime 鎖過期時間 防止死鎖
59      * @return
60      */
61     public boolean lock(String key, int value, long releaseTime) {
62         // 嘗試獲取鎖
63         Boolean boo = redisTemplate.opsForValue().setIfAbsent(key, value, releaseTime, TimeUnit.SECONDS);
64         // 判斷結果
65         return boo != null && boo;
66     }
67 
68     /**
69      * 根據key'刪除鎖
70      *
71      * @param key
72      */
73     public void deleteLock(String key) {
74         // 刪除key即可釋放鎖
75         redisTemplate.delete(key);
76     }
77 }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM