代碼清晰簡潔 廢話很少說直接上demojava
這裏使用的單元測試;歡迎研究討論,下一篇講解分佈式鎖;redis
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 }