自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

基于Consul的分布式信號量實現(xiàn)

開發(fā) 開發(fā)工具 分布式
本文將繼續(xù)討論基于Consul的分布式鎖實現(xiàn)。信號量是我們在實現(xiàn)并發(fā)控制時會經(jīng)常使用的手段,主要用來限制同時并發(fā)線程或進程的數(shù)量。

本文將繼續(xù)討論基于Consul的分布式鎖實現(xiàn)。信號量是我們在實現(xiàn)并發(fā)控制時會經(jīng)常使用的手段,主要用來限制同時并發(fā)線程或進程的數(shù)量,比如:Zuul默認情況下就使用信號量來限制每個路由的并發(fā)數(shù),以實現(xiàn)不同路由間的資源隔離。

[[190924]]

信號量(Semaphore),有時被稱為信號燈,是在多線程環(huán)境下使用的一種設(shè)施,是可以用來保證兩個或多個關(guān)鍵代碼段不被并發(fā)調(diào)用。在進入一個關(guān)鍵代碼段之前,線程必須獲取一個信號量;一旦該關(guān)鍵代碼段完成了,那么該線程必須釋放信號量。其他想進入該關(guān)鍵代碼段的線程必須等待直到***個線程釋放信號量。為了完成這個過程,需要創(chuàng)建一個信號量VI,然后將Acquire Semaphore VI以及Release Semaphore VI分別放置在每個關(guān)鍵代碼段的首末端,確認這些信號量VI引用的是初始創(chuàng)建的信號量。如在這個停車場系統(tǒng)中,車位是公共資源,每輛車好比一個線程,看門人起的就是信號量的作用。

實現(xiàn)思路

  1. 信號量存儲:semaphore/key
  2. acquired操作:
  3. 創(chuàng)建session
  4. 鎖定key競爭者:semaphore/key/session
  5. 查詢信號量:semaphore/key/.lock,可以獲得如下內(nèi)容(如果是***次創(chuàng)建信號量,將獲取不到,這個時候就直接創(chuàng)建)
    1.     "limit": 3, 
    2.     "holders": [ 
    3.         "90c0772a-4bd3-3a3c-8215-3b8937e36027", 
    4.         "93e5611d-5365-a374-8190-f80c4a7280ab" 
    5.     ] 
  6. 如果持有者已達上限,返回false,如果阻塞模式,就繼續(xù)嘗試acquired操作
  7. 如果持有者未達上限,更新semaphore/key/.lock的內(nèi)容,將當前線程的sessionId加入到holders中。注意:更新的時候需要設(shè)置cas,它的值是“查詢信號量”步驟獲得的“ModifyIndex”值,該值用于保證更新操作的基礎(chǔ)沒有被其他競爭者更新。如果更新成功,就開始執(zhí)行具體邏輯。如果沒有更新成功,說明有其他競爭者搶占了資源,返回false,阻塞模式下繼續(xù)嘗試acquired操作
  8. release操作:
  • 從semaphore/key/.lock的holders中移除當前sessionId
  • 刪除semaphore/key/session
  • 刪除當前的session

流程圖

代碼實現(xiàn)

  1. public class Semaphore { 
  2.   
  3.     private Logger logger = Logger.getLogger(getClass()); 
  4.   
  5.     private static final String prefix = "semaphore/";  // 信號量參數(shù)前綴 
  6.   
  7.     private ConsulClient consulClient; 
  8.     private int limit; 
  9.     private String keyPath; 
  10.     private String sessionId = null
  11.     private boolean acquired = false
  12.   
  13.     /** 
  14.      * 
  15.      * @param consulClient consul客戶端實例 
  16.      * @param limit 信號量上限值 
  17.      * @param keyPath 信號量在consul中存儲的參數(shù)路徑 
  18.      */ 
  19.     public Semaphore(ConsulClient consulClient, int limit, String keyPath) { 
  20.         this.consulClient = consulClient; 
  21.         this.limit = limit; 
  22.         this.keyPath = prefix + keyPath; 
  23.     } 
  24.   
  25.     /** 
  26.      * acquired信號量 
  27.      * 
  28.      * @param block 是否阻塞。如果為true,那么一直嘗試,直到獲取到該資源為止。 
  29.      * @return 
  30.      * @throws IOException 
  31.      */ 
  32.     public Boolean acquired(boolean block) throws IOException { 
  33.   
  34.         if(acquired) { 
  35.             logger.error(sessionId + " - Already acquired"); 
  36.             throw new RuntimeException(sessionId + " - Already acquired"); 
  37.         } 
  38.   
  39.         // create session 
  40.         clearSession(); 
  41.         this.sessionId = createSessionId("semaphore"); 
  42.         logger.debug("Create session : " + sessionId); 
  43.   
  44.         // add contender entry 
  45.         String contenderKey = keyPath + "/" + sessionId; 
  46.         logger.debug("contenderKey : " + contenderKey); 
  47.         PutParams putParams = new PutParams(); 
  48.         putParams.setAcquireSession(sessionId); 
  49.         Boolean b = consulClient.setKVValue(contenderKey, "", putParams).getValue(); 
  50.         if(!b) { 
  51.             logger.error("Failed to add contender entry : " + contenderKey + ", " + sessionId); 
  52.             throw new RuntimeException("Failed to add contender entry : " + contenderKey + ", " + sessionId); 
  53.         } 
  54.   
  55.         while(true) { 
  56.             // try to take the semaphore 
  57.             String lockKey = keyPath + "/.lock"; 
  58.             String lockKeyValue; 
  59.   
  60.             GetValue lockKeyContent = consulClient.getKVValue(lockKey).getValue(); 
  61.   
  62.             if (lockKeyContent != null) { 
  63.                 // lock值轉(zhuǎn)換 
  64.                 lockKeyValue = lockKeyContent.getValue(); 
  65.                 BASE64Decoder decoder = new BASE64Decoder(); 
  66.                 byte[] v = decoder.decodeBuffer(lockKeyValue); 
  67.                 String lockKeyValueDecode = new String(v); 
  68.                 logger.debug("lockKey=" + lockKey + "lockKeyValueDecode=" + lockKeyValueDecode); 
  69.   
  70.                 Gson gson = new Gson(); 
  71.                 ContenderValue contenderValue = gson.fromJson(lockKeyValueDecode, ContenderValue.class); 
  72.                 // 當前信號量已滿 
  73.                 if(contenderValue.getLimit() == contenderValue.getHolders().size()) { 
  74.                     logger.debug("Semaphore limited " + contenderValue.getLimit() + ", waiting..."); 
  75.                     if(block) { 
  76.                         // 如果是阻塞模式,再嘗試 
  77.                         try { 
  78.                             Thread.sleep(100L); 
  79.                         } catch (InterruptedException e) { 
  80.                         } 
  81.                         continue; 
  82.                     } 
  83.                     // 非阻塞模式,直接返回沒有獲取到信號量 
  84.                     return false; 
  85.                 } 
  86.                 // 信號量增加 
  87.                 contenderValue.getHolders().add(sessionId); 
  88.                 putParams = new PutParams(); 
  89.                 putParams.setCas(lockKeyContent.getModifyIndex()); 
  90.                 boolean c = consulClient.setKVValue(lockKey, contenderValue.toString(), putParams).getValue(); 
  91.                 if(c) { 
  92.                     acquired = true
  93.                     return true; 
  94.                 } 
  95.                 else 
  96.                     continue; 
  97.             } else { 
  98.                 // 當前信號量還沒有,所以創(chuàng)建一個,并馬上搶占一個資源 
  99.                 ContenderValue contenderValue = new ContenderValue(); 
  100.                 contenderValue.setLimit(limit); 
  101.                 contenderValue.getHolders().add(sessionId); 
  102.   
  103.                 putParams = new PutParams(); 
  104.                 putParams.setCas(0L); 
  105.                 boolean c = consulClient.setKVValue(lockKey, contenderValue.toString(), putParams).getValue(); 
  106.                 if (c) { 
  107.                     acquired = true
  108.                     return true; 
  109.                 } 
  110.                 continue; 
  111.             } 
  112.         } 
  113.     } 
  114.   
  115.     /** 
  116.      * 創(chuàng)建sessionId 
  117.      * @param sessionName 
  118.      * @return 
  119.      */ 
  120.     public String createSessionId(String sessionName) { 
  121.         NewSession newnewSession = new NewSession(); 
  122.         newSession.setName(sessionName); 
  123.         return consulClient.sessionCreate(newSession, null).getValue(); 
  124.     } 
  125.   
  126.     /** 
  127.      * 釋放session、并從lock中移除當前的sessionId 
  128.      * @throws IOException 
  129.      */ 
  130.     public void release() throws IOException { 
  131.         if(this.acquired) { 
  132.             // remove session from lock 
  133.             while(true) { 
  134.                 String contenderKey = keyPath + "/" + sessionId; 
  135.                 String lockKey = keyPath + "/.lock"; 
  136.                 String lockKeyValue; 
  137.   
  138.                 GetValue lockKeyContent = consulClient.getKVValue(lockKey).getValue(); 
  139.                 if (lockKeyContent != null) { 
  140.                     // lock值轉(zhuǎn)換 
  141.                     lockKeyValue = lockKeyContent.getValue(); 
  142.                     BASE64Decoder decoder = new BASE64Decoder(); 
  143.                     byte[] v = decoder.decodeBuffer(lockKeyValue); 
  144.                     String lockKeyValueDecode = new String(v); 
  145.                     Gson gson = new Gson(); 
  146.                     ContenderValue contenderValue = gson.fromJson(lockKeyValueDecode, ContenderValue.class); 
  147.                     contenderValue.getHolders().remove(sessionId); 
  148.                     PutParams putParams = new PutParams(); 
  149.                     putParams.setCas(lockKeyContent.getModifyIndex()); 
  150.                     consulClient.deleteKVValue(contenderKey); 
  151.                     boolean c = consulClient.setKVValue(lockKey, contenderValue.toString(), putParams).getValue(); 
  152.                     if(c) { 
  153.                         break; 
  154.                     } 
  155.                 } 
  156.             } 
  157.             // remove session key 
  158.   
  159.         } 
  160.         this.acquired = false
  161.         clearSession(); 
  162.     } 
  163.   
  164.     public void clearSession() { 
  165.         if(sessionId != null) { 
  166.             consulClient.sessionDestroy(sessionId, null); 
  167.             sessionId = null
  168.         } 
  169.     } 
  170.   
  171.     class ContenderValue implements Serializable { 
  172.   
  173.         private Integer limit; 
  174.         private List<String> holders = new ArrayList<>(); 
  175.   
  176.         public Integer getLimit() { 
  177.             return limit; 
  178.         } 
  179.   
  180.         public void setLimit(Integer limit) { 
  181.             this.limit = limit; 
  182.         } 
  183.   
  184.         public List<String> getHolders() { 
  185.             return holders; 
  186.         } 
  187.   
  188.         public void setHolders(List<String> holders) { 
  189.             this.holders = holders; 
  190.         } 
  191.   
  192.         @Override 
  193.         public String toString() { 
  194.             return new Gson().toJson(this); 
  195.         } 
  196.   
  197.     } 
  198.   

單元測試 

下面單元測試的邏輯:通過線程的方式來模擬不同的分布式服務(wù)來獲取信號量執(zhí)行業(yè)務(wù)邏輯。由于信號量與簡單的分布式互斥鎖有所不同,它不是只限定一個線程可以操作,而是可以控制多個線程的并發(fā),所以通過下面的單元測試,我們設(shè)置信號量為3,然后同時啟動15個線程來競爭的情況,來觀察分布式信號量實現(xiàn)的結(jié)果如何。

  1. INFO  [Thread-6] SemaphoreRunner - Thread 7 start! 
  2. INFO  [Thread-2] SemaphoreRunner - Thread 3 start! 
  3. INFO  [Thread-7] SemaphoreRunner - Thread 8 start! 
  4. INFO  [Thread-2] SemaphoreRunner - Thread 3 end! 
  5. INFO  [Thread-5] SemaphoreRunner - Thread 6 start! 
  6. INFO  [Thread-6] SemaphoreRunner - Thread 7 end! 
  7. INFO  [Thread-9] SemaphoreRunner - Thread 10 start! 
  8. INFO  [Thread-5] SemaphoreRunner - Thread 6 end! 
  9. INFO  [Thread-1] SemaphoreRunner - Thread 2 start! 
  10. INFO  [Thread-7] SemaphoreRunner - Thread 8 end! 
  11. INFO  [Thread-10] SemaphoreRunner - Thread 11 start! 
  12. INFO  [Thread-10] SemaphoreRunner - Thread 11 end! 
  13. INFO  [Thread-12] SemaphoreRunner - Thread 13 start! 
  14. INFO  [Thread-1] SemaphoreRunner - Thread 2 end! 
  15. INFO  [Thread-3] SemaphoreRunner - Thread 4 start! 
  16. INFO  [Thread-9] SemaphoreRunner - Thread 10 end! 
  17. INFO  [Thread-0] SemaphoreRunner - Thread 1 start! 
  18. INFO  [Thread-3] SemaphoreRunner - Thread 4 end! 
  19. INFO  [Thread-14] SemaphoreRunner - Thread 15 start! 
  20. INFO  [Thread-12] SemaphoreRunner - Thread 13 end! 
  21. INFO  [Thread-0] SemaphoreRunner - Thread 1 end! 
  22. INFO  [Thread-13] SemaphoreRunner - Thread 14 start! 
  23. INFO  [Thread-11] SemaphoreRunner - Thread 12 start! 
  24. INFO  [Thread-13] SemaphoreRunner - Thread 14 end! 
  25. INFO  [Thread-4] SemaphoreRunner - Thread 5 start! 
  26. INFO  [Thread-4] SemaphoreRunner - Thread 5 end! 
  27. INFO  [Thread-8] SemaphoreRunner - Thread 9 start! 
  28. INFO  [Thread-11] SemaphoreRunner - Thread 12 end! 
  29. INFO  [Thread-14] SemaphoreRunner - Thread 15 end! 
  30. INFO  [Thread-8] SemaphoreRunner - Thread 9 end! 
  1. public class TestLock { 
  2.   
  3.     private Logger logger = Logger.getLogger(getClass()); 
  4.   
  5.     @Test 
  6.     public void testSemaphore() throws Exception { 
  7.         new Thread(new SemaphoreRunner(1)).start(); 
  8.         new Thread(new SemaphoreRunner(2)).start(); 
  9.         new Thread(new SemaphoreRunner(3)).start(); 
  10.         new Thread(new SemaphoreRunner(4)).start(); 
  11.         new Thread(new SemaphoreRunner(5)).start(); 
  12.         new Thread(new SemaphoreRunner(6)).start(); 
  13.         new Thread(new SemaphoreRunner(7)).start(); 
  14.         new Thread(new SemaphoreRunner(8)).start(); 
  15.         new Thread(new SemaphoreRunner(9)).start(); 
  16.         new Thread(new SemaphoreRunner(10)).start(); 
  17.         Thread.sleep(1000000L); 
  18.     }  
  19.    
  20. public class SemaphoreRunner implements Runnable { 
  21.   
  22.     private Logger logger = Logger.getLogger(getClass()); 
  23.   
  24.     private int flag; 
  25.   
  26.     public SemaphoreRunner(int flag) { 
  27.         this.flag = flag; 
  28.     } 
  29.   
  30.     @Override 
  31.     public void run() { 
  32.         Semaphore semaphore = new Semaphore(new ConsulClient(), 3, "mg-init"); 
  33.         try { 
  34.             if (semaphore.acquired(true)) { 
  35.                 // 獲取到信號量,執(zhí)行業(yè)務(wù)邏輯 
  36.                 logger.info("Thread " + flag + " start!"); 
  37.                 Thread.sleep(new Random().nextInt(10000)); 
  38.                 logger.info("Thread " + flag + " end!"); 
  39.             } 
  40.         } catch (Exception e) { 
  41.             e.printStackTrace(); 
  42.         } finally { 
  43.             try { 
  44.                 // 信號量釋放、Session鎖釋放、Session刪除 
  45.                 semaphore.release(); 
  46.             } catch (IOException e) { 
  47.                 e.printStackTrace(); 
  48.             } 
  49.         } 
  50.     } 

從測試結(jié)果,我們可以發(fā)現(xiàn)當信號量持有者數(shù)量達到信號量上限3的時候,其他競爭者就開始進行等待了,只有當某個持有者釋放信號量之后,才會有新的線程變成持有者,從而開始執(zhí)行自己的業(yè)務(wù)邏輯。所以,分布式信號量可以幫助我們有效的控制同時操作某個共享資源的并發(fā)數(shù)。

優(yōu)化建議

同前文一樣,這里只是做了簡單的實現(xiàn)。線上應(yīng)用還必須加入TTL的session清理以及對.lock資源中的無效holder進行清理的機制。

參考文檔:https://www.consul.io/docs/guides/semaphore.html

實現(xiàn)代碼

【本文為51CTO專欄作者“翟永超”的原創(chuàng)稿件,轉(zhuǎn)載請通過51CTO聯(lián)系作者獲取授權(quán)】

戳這里,看該作者更多好文

責(zé)任編輯:趙寧寧 來源: 51CTO專欄
相關(guān)推薦

2017-04-13 10:51:09

Consul分布式

2010-04-21 16:25:13

Unix信號量

2010-04-21 16:42:48

Unix信號量

2021-04-13 09:20:15

鴻蒙HarmonyOS應(yīng)用開發(fā)

2022-10-27 10:44:14

分布式Zookeeper

2010-04-21 16:50:31

Unix信號量

2020-11-05 09:59:24

Linux內(nèi)核信號量

2009-06-19 14:23:41

RMIJava分布式計算

2023-01-06 09:19:12

Seata分布式事務(wù)

2021-09-07 07:53:42

Semaphore 信號量源碼

2015-04-21 09:39:03

javajava分布式爬蟲

2017-10-24 11:28:23

Zookeeper分布式鎖架構(gòu)

2010-04-21 15:37:38

Unix信號量

2020-09-25 07:34:40

Linux系統(tǒng)編程信號量

2022-11-06 19:28:02

分布式鎖etcd云原生

2009-12-08 12:14:43

2013-08-21 14:06:05

iOS隊列信號

2022-03-08 15:24:23

BitMapRedis數(shù)據(jù)

2024-10-29 15:23:45

Python線程安全

2025-04-01 00:44:04

點贊
收藏

51CTO技術(shù)棧公眾號