Java 實現基於Redis的分佈式可重入鎖

如何實現可重入?

 

首先鎖信息(指redis中lockKey關聯的value值) 必須得設計的能負載更多信息,之前non-reentrant時value直接就是一個超時時間,但是要實現可重入單超時時間是不夠的,必須要標識鎖是被誰持有的,也就是說要標識分佈式環境中的線程,還要記錄鎖被入了多少次。

 

 

如何在分佈式線程中標識唯一線程?

 

MAC地址 +jvm進程 + 線程ID(或者線程地址都行),三者結合即可唯一分佈式環境中的線程。下載

 

 

實現

 

鎖的信息採用json存儲,格式如下:

 

 

 

 代碼框架還是和之前實現的非重入的差不多,重點是lock方法,代碼已有非常詳細的註釋

 

Java代碼 下載

  1. package cc.lixiaohui.lock.redis;  

  2.   

  3. import java.io.IOException;  

  4. import java.net.SocketAddress;  

  5. import java.util.concurrent.TimeUnit;  

  6.   

  7. import org.slf4j.Logger;  

  8. import org.slf4j.LoggerFactory;  

  9.   

  10. import redis.clients.jedis.Jedis;  

  11. import cc.lixiaohui.lock.AbstractLock;  

  12. import cc.lixiaohui.lock.Lock;  

  13. import cc.lixiaohui.lock.time.nio.client.TimeClient;  

  14. import cc.lixiaohui.lock.util.LockInfo;  

  15.   

  16. /** 

  17.  * 基於Redis的SETNX操作實現的分佈式鎖, 獲取鎖時最好用tryLock(long time, TimeUnit unit), 以免網路問題而導致線程一直阻塞. 

  18.  * <a href="http://redis.io/commands/setnx">SETNC操作參考資料.</a> 

  19.  *  

  20.  * <p><b>可重入實現關鍵:</b> 

  21.  * <ul> 

  22.  * <li>在分佈式環境中如何確定一個線程? <i><b>mac地址 + jvm pid + threadId</b></i> (mac地址唯一, jvm 

  23.  * pid在單機內唯一, threadId在單jvm內唯一)</li> 

  24.  * <li>任何一個線程從redis拿到value值後都需要能確定 該鎖是否被自己持有, 因此value值要有以下特性: 保存持有鎖的主機(mac), jvm 

  25.  * pid, 持有鎖的線程ID, 重複持有鎖的次數</li> 

  26.  * </ul></p> 

  27.  * <p> 

  28.  * redis中value設計如下(in json): 

  29.  * <pre> 

  30.  * { 

  31.  *  expires : expire time in long 

  32.  *  mac : mac address of lock holder's machine 

  33.  *  pid : jvm process id 

  34.  *  threadId : lock holder thread id 

  35.  *  count : hold count(for use of reentrancy) 

  36.  * } 

  37.  * 由{@link LockInfo LockInfo}表示. 

  38.  * </pre> 

  39.  *  

  40.  * <b>Usage Example:</b> 

  41.  * <pre> 

  42.  *  {@link Lock} lock = new {@link ReentrantLock}(jedis, "lockKey", lockExpires, timeServerAddr); 

  43.  *  if (lock.tryLock(3, TimeUnit.SECONDS)) { 

  44.  *      try { 

  45.  *          // do something 

  46.  *      } catch (Exception e) { 

  47.  *          lock.unlock(); 

  48.  *      } 

  49.  *  } 

  50.  * </pre> 

  51.  * </p> 

  52.  *  

  53.  * @author lixiaohui 

  54.  * @date 2016年9月15日 下午2:52:38 

  55.  * 

  56.  */  

  57. public class ReentrantLock extends AbstractLock {  

  58.   

  59.     private Jedis jedis;  

  60.   

  61.     private TimeClient timeClient;  

  62.   

  63.     // 鎖的名字  

  64.     protected String lockKey;  

  65.   

  66.     // 鎖的有效時長(毫秒)  

  67.     protected long lockExpires;  

  68.   

  69.     private static final Logger logger = LoggerFactory.getLogger(ReentrantLock.class);  

  70.   

  71.     public ReentrantLock(Jedis jedis, String lockKey, long lockExpires, SocketAddress timeServerAddr) throws IOException {  

  72.         this.jedis = jedis;  

  73.         this.lockKey = lockKey;  

  74.         this.lockExpires = lockExpires;  

  75.         timeClient = new TimeClient(timeServerAddr);  

  76.     }  

  77.   

  78.     // 阻塞式獲取鎖的實現  

  79.     protected boolean lock(boolean useTimeout, long time, TimeUnit unit, boolean interrupt) throws InterruptedException {  

  80.         if (interrupt) {  

  81.             checkInterruption();  

  82.         }  

  83.   

  84.         // 超時控制 的時間可以從本地獲取, 因爲這個和鎖超時沒有關係, 只是一段時間區間的控制  

  85.         long start = localTimeMillis();  

  86.         long timeout = unit.toMillis(time); // if !useTimeout, then it's useless  

  87.   

  88.         // walkthrough  

  89.         // 1. lockKey未關聯value, 直接設置lockKey, 成功獲取到鎖, return true  

  90.         // 2. lock 已過期, 用getset設置lockKey, 判斷返回的舊的LockInfo  

  91.         // 2.1 若仍是超時的, 則成功獲取到鎖, return true  

  92.         // 2.2 若不是超時的, 則進入下一次循環重新開始 步驟1  

  93.         // 3. lock沒過期, 判斷是否是當前線程持有  

  94.         // 3.1 是, 則計數加 1, return true  

  95.         // 3.2 否, 則進入下一次循環重新開始 步驟1  

  96.         // note: 每次進入循環都檢查 : 1.是否超時, 若是則return false; 2.是否檢查中斷(interrupt)被中斷,  

  97.         // 若需檢查中斷且被中斷, 則拋InterruptedException  

  98.         while (useTimeout ? !isTimeout(start, timeout) : true) {  

  99.             if (interrupt) {  

  100.                 checkInterruption();  

  101.             }  

  102.   

  103.             long lockExpireTime = serverTimeMillis() + lockExpires + 1;// 鎖超時時間  

  104.             String newLockInfoJson = LockInfo.newForCurrThread(lockExpireTime).toString();  

  105.             if (jedis.setnx(lockKey, newLockInfoJson) == 1) { // 條件能成立的唯一情況就是redis中lockKey還未關聯value  

  106.                 // TODO 成功獲取到鎖, 設置相關標識  

  107.                 logger.debug("{} get lock(new), lockInfo: {}", Thread.currentThread().getName(), newLockInfoJson);  

  108.                 locked = true;  

  109.                 return true;  

  110.             }  

  111.   

  112.             // value已有值, 但不能說明鎖被持有, 因爲鎖可能expired了  

  113.             String currLockInfoJson = jedis.get(lockKey);  

  114.             // 若這瞬間鎖被delete了  

  115.             if (currLockInfoJson == null) {  

  116.                 continue;  

  117.             }  

  118.   

  119.             LockInfo currLockInfo = LockInfo.fromString(currLockInfoJson);  

  120.             // 競爭條件只可能出現在鎖超時的情況, 因爲如果沒有超時, 線程發現鎖並不是被自己持有, 線程就不會去動value  

  121.             if (isTimeExpired(currLockInfo.getExpires())) {  

  122.                 // 鎖超時了  

  123.                 LockInfo oldLockInfo = LockInfo.fromString(jedis.getSet(lockKey, newLockInfoJson));  

  124.                 if (oldLockInfo != null && isTimeExpired(oldLockInfo.getExpires())) {  

  125.                     // TODO 成功獲取到鎖, 設置相關標識  

  126.                     logger.debug("{} get lock(new), lockInfo: {}", Thread.currentThread().getName(), newLockInfoJson);  

  127.                     locked = true;  

  128.                     return true;  

  129.                 }  

  130.             } else {  

  131.                 // 鎖未超時, 不會有競爭情況  

  132.                 if (isHeldByCurrentThread(currLockInfo)) { // 當前線程持有  

  133.                     // TODO 成功獲取到鎖, 設置相關標識  

  134.                     currLockInfo.setExpires(serverTimeMillis() + lockExpires + 1); // 設置新的鎖超時時間  

  135.                     currLockInfo.incCount();  

  136.                     jedis.set(lockKey, currLockInfo.toString());  

  137.                     logger.debug("{} get lock(inc), lockInfo: {}", Thread.currentThread().getName(), currLockInfo);  

  138.                     locked = true;  

  139.                     return true;  

  140.                 }  

  141.             }  

  142.         }  

  143.         locked = false;  

  144.         return false;  

  145.     }  

  146.   

  147.     public boolean tryLock() {  

  148.         long lockExpireTime = serverTimeMillis() + lockExpires + 1;  

  149.         String newLockInfo = LockInfo.newForCurrThread(lockExpireTime).toString();  

  150.   

  151.         if (jedis.setnx(lockKey, newLockInfo) == 1) {  

  152.             locked = true;  

  153.             return true;  

  154.         }  

  155.   

  156.         String currLockInfoJson = jedis.get(lockKey);  

  157.         if (currLockInfoJson == null) {  

  158.             // 再一次嘗試獲取  

  159.             if (jedis.setnx(lockKey, newLockInfo) == 1) {  

  160.                 locked = true;  

  161.                 return true;  

  162.             } else {  

  163.                 locked = false;  

  164.                 return false;  

  165.             }  

  166.         }  

  167.           

  168.         LockInfo currLockInfo = LockInfo.fromString(currLockInfoJson);  

  169.           

  170.         if (isTimeExpired(currLockInfo.getExpires())) {  

  171.             LockInfo oldLockInfo = LockInfo.fromString(jedis.getSet(lockKey, newLockInfo));  

  172.             if (oldLockInfo != null && isTimeExpired(oldLockInfo.getExpires())) {  

  173.                 locked = true;  

  174.                 return true;  

  175.             }  

  176.         } else {  

  177.             if (isHeldByCurrentThread(currLockInfo)) {  

  178.                 currLockInfo.setExpires(serverTimeMillis() + lockExpires + 1);   

  179.                 currLockInfo.incCount();  

  180.                 jedis.set(lockKey, currLockInfo.toString());  

  181.                 locked = true;  

  182.                 return true;  

  183.             }  

  184.         }  

  185.         locked = false;  

  186.         return false;  

  187.     }  

  188.   

  189.     /** 

  190.      * Queries if this lock is held by any thread. 

  191.      *  

  192.      * @return {@code true} if any thread holds this lock and {@code false} 

  193.      *         otherwise 

  194.      */  

  195.     public boolean isLocked() {  

  196.         // walkthrough  

  197.         // 1. lockKey未關聯value, return false  

  198.         // 2. 若 lock 已過期, return false, 否則 return true  

  199.         if (!locked) { // 本地locked爲false, 肯定沒加鎖  

  200.             return false;  

  201.         }  

  202.         String json = jedis.get(lockKey);  

  203.         if (json == null) {  

  204.             return false;  

  205.         }  

  206.         if (isTimeExpired(LockInfo.fromString(json).getExpires())) {  

  207.             return false;  

  208.         }  

  209.         return true;  

  210.     }  

  211.   

  212.     @Override  

  213.     protected void unlock0() {  

  214.         // walkthrough  

  215.         // 1. 若鎖過期, return  

  216.         // 2. 判斷自己是否是鎖的owner  

  217.         // 2.1 是, 若 count = 1, 則刪除lockKey; 若 count > 1, 則計數減 1, return  

  218.         // 2.2 否, 則拋異常 IllegalMonitorStateException, reutrn  

  219.         // done, return  

  220.         LockInfo currLockInfo = LockInfo.fromString(jedis.get(lockKey));  

  221.         if (isTimeExpired(currLockInfo.getExpires())) {  

  222.             return;  

  223.         }  

  224.   

  225.         if (isHeldByCurrentThread(currLockInfo)) {  

  226.             if (currLockInfo.getCount() == 1) {  

  227.                 jedis.del(lockKey);  

  228.                 logger.debug("{} unlock(del), lockInfo: null", Thread.currentThread().getName());  

  229.             } else {  

  230.                 currLockInfo.decCount(); // 持有鎖計數減1  

  231.                 String json = currLockInfo.toString();  

  232.                 jedis.set(lockKey, json);  

  233.                 logger.debug("{} unlock(dec), lockInfo: {}", Thread.currentThread().getName(), json);  

  234.             }  

  235.         } else {  

  236.             throw new IllegalMonitorStateException(String.format("current thread[%s] does not holds the lock", Thread.currentThread().toString()));  

  237.         }  

  238.   

  239.     }  

  240.   

  241.     public void release() {  

  242.         jedis.close();  

  243.         timeClient.close();  

  244.     }  

  245.       

  246.     public boolean isHeldByCurrentThread() {  

  247.         return isHeldByCurrentThread(LockInfo.fromString(jedis.get(lockKey)));  

  248.     }  

  249.   

  250.     // ------------------- utility methods ------------------------  

  251.   

  252.     private boolean isHeldByCurrentThread(LockInfo lockInfo) {  

  253.         return lockInfo.isCurrentThread();  

  254.     }  

  255.   

  256.     private void checkInterruption() throws InterruptedException {  

  257.         if (Thread.currentThread().isInterrupted()) {  

  258.             throw new InterruptedException();  

  259.         }  

  260.     }  

  261.   

  262.     private boolean isTimeExpired(long time) {  

  263.         return time < serverTimeMillis();  

  264.     }  

  265.   

  266.     private boolean isTimeout(long start, long timeout) {  

  267.         // 這裏拿本地的時間來比較  

  268.         return start + timeout < System.currentTimeMillis();  

  269.     }  

  270.   

  271.     private long serverTimeMillis() {  

  272.         return timeClient.currentTimeMillis();  

  273.     }  

  274.   

  275.     private long localTimeMillis() {  

  276.         return System.currentTimeMillis();  

  277.     }  

  278.   

  279. }  

 

 測試

 

5個線程,每個線程都是不同的jedis連接,模擬分佈式環境,線程的任務就是不斷的去嘗試重入地獲取鎖,重入的次數爲隨機但在0-5之間。

 

代碼

 

Java代碼   下載

  1. package cc.lixiaohui.DistributedLock.DistributedLock;  

  2.   

  3. import java.io.IOException;  

  4. import java.net.InetSocketAddress;  

  5. import java.net.SocketAddress;  

  6. import java.util.ArrayList;  

  7. import java.util.List;  

  8. import java.util.Random;  

  9. import java.util.concurrent.TimeUnit;  

  10.   

  11. import org.junit.Test;  

  12.   

  13. import redis.clients.jedis.Jedis;  

  14. import cc.lixiaohui.lock.redis.ReentrantLock;  

  15.   

  16. /** 

  17.  * @author lixiaohui 

  18.  * @date 2016年9月28日 下午8:41:36 

  19.  *  

  20.  */  

  21. public class ReentrantTest {  

  22.       

  23.     final int EXPIRES = 10 * 1000;  

  24.       

  25.     final String LOCK_KEY = "lock.lock";  

  26.       

  27.     final SocketAddress TIME_SERVER_ADDR = new InetSocketAddress("localhost"9999);  

  28.       

  29.     @Test  

  30.     public void test() throws Exception {  

  31.         // 創建5個線程不停地去重入(隨機次數n, 0 <= n <=5)獲取鎖  

  32.         List<Thread> threads = createThreads(5);  

  33.         //開始任務  

  34.         for (Thread t : threads) {  

  35.             t.start();  

  36.         }  

  37.         // 執行60秒  

  38.         Thread.sleep(60 * 1000);  

  39.         //停止所有線程  

  40.         Task.alive = false;  

  41.         // 等待所有線程終止  

  42.         for (Thread t : threads) {  

  43.             t.join();  

  44.         }  

  45.           

  46.     }  

  47.     // 創建count個線程,每個線程都是不同的jedis連接以及不同的與時間服務器的連接  

  48.     private List<Thread> createThreads(int count) throws IOException {  

  49.         List<Thread> threads = new ArrayList<Thread>();  

  50.         for (int i = 0; i < count; i++) {  

  51.             Jedis jedis = new Jedis("localhost"6379);  

  52.             ReentrantLock lock = new ReentrantLock(jedis, LOCK_KEY, EXPIRES, TIME_SERVER_ADDR);  

  53.             Task task = new Task(lock);  

  54.             Thread t = new Thread(task);  

  55.             threads.add(t);  

  56.         }  

  57.         return threads;  

  58.     }  

  59.       

  60.     private static class Task implements Runnable {  

  61.           

  62.         private ReentrantLock lock;  

  63.           

  64.         private final int MAX_ENTRANT = 5;  

  65.           

  66.         private final Random random = new Random();  

  67.           

  68.         private static boolean alive = true;  

  69.           

  70.         Task(ReentrantLock lock) {  

  71.             this.lock = lock;  

  72.         }  

  73.           

  74.         public void run() {  

  75.             while (alive) {  

  76.                 int times = random.nextInt(MAX_ENTRANT);  

  77.                 doLock(times);  

  78.             }  

  79.         }  

  80.           

  81.         private void doLock(int times) {  

  82.             if (lock.tryLock(5, TimeUnit.SECONDS)) {  

  83.                 try {  

  84.                     if (times > 0) {  

  85.                         doLock(--times);  

  86.                     }  

  87.                 } finally {  

  88.                     if (lock != null) {  

  89.                         lock.unlock();  

  90.                     }  

  91.                 }  

  92.             }  

  93.               

  94.         }  

  95.           

  96.           

  97.           

  98.     }  

  99.       

  100. }  

 


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