亚洲香蕉成人av网站在线观看_欧美精品成人91久久久久久久_久久久久久久久久久亚洲_热久久视久久精品18亚洲精品_国产精自产拍久久久久久_亚洲色图国产精品_91精品国产网站_中文字幕欧美日韩精品_国产精品久久久久久亚洲调教_国产精品久久一区_性夜试看影院91社区_97在线观看视频国产_68精品久久久久久欧美_欧美精品在线观看_国产精品一区二区久久精品_欧美老女人bb

首頁 > 開發 > Java > 正文

淺談Java(SpringBoot)基于zookeeper的分布式鎖實現

2024-07-14 08:43:42
字體:
來源:轉載
供稿:網友

通過zookeeper實現分布式鎖

1、創建zookeeper的client

首先通過CuratorFrameworkFactory創建一個連接zookeeper的連接CuratorFramework client

public class CuratorFactoryBean implements FactoryBean<CuratorFramework>, InitializingBean, DisposableBean { private static final Logger LOGGER = LoggerFactory.getLogger(ContractFileInfoController.class); private String connectionString; private int sessionTimeoutMs; private int connectionTimeoutMs; private RetryPolicy retryPolicy; private CuratorFramework client; public CuratorFactoryBean(String connectionString) {  this(connectionString, 500, 500); } public CuratorFactoryBean(String connectionString, int sessionTimeoutMs, int connectionTimeoutMs) {  this.connectionString = connectionString;  this.sessionTimeoutMs = sessionTimeoutMs;  this.connectionTimeoutMs = connectionTimeoutMs; } @Override public void destroy() throws Exception {  LOGGER.info("Closing curator framework...");  this.client.close();  LOGGER.info("Closed curator framework."); } @Override public CuratorFramework getObject() throws Exception {  return this.client; } @Override public Class<?> getObjectType() {   return this.client != null ? this.client.getClass() : CuratorFramework.class; } @Override public boolean isSingleton() {  return true; } @Override public void afterPropertiesSet() throws Exception {  if (StringUtils.isEmpty(this.connectionString)) {   throw new IllegalStateException("connectionString can not be empty.");  } else {   if (this.retryPolicy == null) {    this.retryPolicy = new ExponentialBackoffRetry(1000, 2147483647, 180000);   }   this.client = CuratorFrameworkFactory.newClient(this.connectionString, this.sessionTimeoutMs, this.connectionTimeoutMs, this.retryPolicy);   this.client.start();   this.client.blockUntilConnected(30, TimeUnit.MILLISECONDS);  } } public void setConnectionString(String connectionString) {  this.connectionString = connectionString; } public void setSessionTimeoutMs(int sessionTimeoutMs) {  this.sessionTimeoutMs = sessionTimeoutMs; } public void setConnectionTimeoutMs(int connectionTimeoutMs) {  this.connectionTimeoutMs = connectionTimeoutMs; } public void setRetryPolicy(RetryPolicy retryPolicy) {  this.retryPolicy = retryPolicy; } public void setClient(CuratorFramework client) {  this.client = client; }}

2、封裝分布式鎖

根據CuratorFramework創建InterProcessMutex(分布式可重入排它鎖)對一行數據進行上鎖

 public InterProcessMutex(CuratorFramework client, String path) {  this(client, path, new StandardLockInternalsDriver()); }

使用 acquire方法
1、acquire() :入參為空,調用該方法后,會一直堵塞,直到搶奪到鎖資源,或者zookeeper連接中斷后,上拋異常。
2、acquire(long time, TimeUnit unit):入參傳入超時時間、單位,搶奪時,如果出現堵塞,會在超過該時間后,返回false。

 public void acquire() throws Exception {  if (!this.internalLock(-1L, (TimeUnit)null)) {   throw new IOException("Lost connection while trying to acquire lock: " + this.basePath);  } } public boolean acquire(long time, TimeUnit unit) throws Exception {  return this.internalLock(time, unit); }

釋放鎖 mutex.release();

public void release() throws Exception {  Thread currentThread = Thread.currentThread();  InterProcessMutex.LockData lockData = (InterProcessMutex.LockData)this.threadData.get(currentThread);  if (lockData == null) {   throw new IllegalMonitorStateException("You do not own the lock: " + this.basePath);  } else {   int newLockCount = lockData.lockCount.decrementAndGet();   if (newLockCount <= 0) {    if (newLockCount < 0) {     throw new IllegalMonitorStateException("Lock count has gone negative for lock: " + this.basePath);    } else {     try {      this.internals.releaseLock(lockData.lockPath);     } finally {      this.threadData.remove(currentThread);     }    }   }  } }

封裝后的DLock代碼
1、調用InterProcessMutex processMutex = dLock.mutex(path);

2、手動釋放鎖processMutex.release();

3、需要手動刪除路徑dLock.del(path);

推薦 使用:
都是 函數式編程
在業務代碼執行完畢后 會釋放鎖和刪除path
1、這個有返回結果
public T mutex(String path, ZkLockCallback zkLockCallback, long time, TimeUnit timeUnit)
2、這個無返回結果
public void mutex(String path, ZkVoidCallBack zkLockCallback, long time, TimeUnit timeUnit)

public class DLock { private final Logger logger; private static final long TIMEOUT_D = 100L; private static final String ROOT_PATH_D = "/dLock"; private String lockRootPath; private CuratorFramework client; public DLock(CuratorFramework client) {  this("/dLock", client); } public DLock(String lockRootPath, CuratorFramework client) {  this.logger = LoggerFactory.getLogger(DLock.class);  this.lockRootPath = lockRootPath;  this.client = client; } public InterProcessMutex mutex(String path) {  if (!StringUtils.startsWith(path, "/")) {   path = Constant.keyBuilder(new Object[]{"/", path});  }  return new InterProcessMutex(this.client, Constant.keyBuilder(new Object[]{this.lockRootPath, "", path})); } public <T> T mutex(String path, ZkLockCallback<T> zkLockCallback) throws ZkLockException {  return this.mutex(path, zkLockCallback, 100L, TimeUnit.MILLISECONDS); } public <T> T mutex(String path, ZkLockCallback<T> zkLockCallback, long time, TimeUnit timeUnit) throws ZkLockException {  String finalPath = this.getLockPath(path);  InterProcessMutex mutex = new InterProcessMutex(this.client, finalPath);  try {   if (!mutex.acquire(time, timeUnit)) {    throw new ZkLockException("acquire zk lock return false");   }  } catch (Exception var13) {   throw new ZkLockException("acquire zk lock failed.", var13);  }  T var8;  try {   var8 = zkLockCallback.doInLock();  } finally {   this.releaseLock(finalPath, mutex);  }  return var8; } private void releaseLock(String finalPath, InterProcessMutex mutex) {  try {   mutex.release();   this.logger.info("delete zk node path:{}", finalPath);   this.deleteInternal(finalPath);  } catch (Exception var4) {   this.logger.error("dlock", "release lock failed, path:{}", finalPath, var4);//   LogUtil.error(this.logger, "dlock", "release lock failed, path:{}", new Object[]{finalPath, var4});  } } public void mutex(String path, ZkVoidCallBack zkLockCallback, long time, TimeUnit timeUnit) throws ZkLockException {  String finalPath = this.getLockPath(path);  InterProcessMutex mutex = new InterProcessMutex(this.client, finalPath);  try {   if (!mutex.acquire(time, timeUnit)) {    throw new ZkLockException("acquire zk lock return false");   }  } catch (Exception var13) {   throw new ZkLockException("acquire zk lock failed.", var13);  }  try {   zkLockCallback.response();  } finally {   this.releaseLock(finalPath, mutex);  } } public String getLockPath(String customPath) {  if (!StringUtils.startsWith(customPath, "/")) {   customPath = Constant.keyBuilder(new Object[]{"/", customPath});  }  String finalPath = Constant.keyBuilder(new Object[]{this.lockRootPath, "", customPath});  return finalPath; } private void deleteInternal(String finalPath) {  try {   ((ErrorListenerPathable)this.client.delete().inBackground()).forPath(finalPath);  } catch (Exception var3) {   this.logger.info("delete zk node path:{} failed", finalPath);  } } public void del(String customPath) {  String lockPath = "";  try {   lockPath = this.getLockPath(customPath);   ((ErrorListenerPathable)this.client.delete().inBackground()).forPath(lockPath);  } catch (Exception var4) {   this.logger.info("delete zk node path:{} failed", lockPath);  } }}
@FunctionalInterfacepublic interface ZkLockCallback<T> { T doInLock();}@FunctionalInterfacepublic interface ZkVoidCallBack { void response();}public class ZkLockException extends Exception { public ZkLockException() { } public ZkLockException(String message) {  super(message); } public ZkLockException(String message, Throwable cause) {  super(message, cause); }}

配置CuratorConfig

@Configurationpublic class CuratorConfig { @Value("${zk.connectionString}") private String connectionString; @Value("${zk.sessionTimeoutMs:500}") private int sessionTimeoutMs; @Value("${zk.connectionTimeoutMs:500}") private int connectionTimeoutMs; @Value("${zk.dLockRoot:/dLock}") private String dLockRoot; @Bean public CuratorFactoryBean curatorFactoryBean() {  return new CuratorFactoryBean(connectionString, sessionTimeoutMs, connectionTimeoutMs); } @Bean @Autowired public DLock dLock(CuratorFramework client) {  return new DLock(dLockRoot, client); }}

測試代碼

@RestController@RequestMapping("/dLock")public class LockController { @Autowired private DLock dLock; @RequestMapping("/lock") public Map testDLock(String no){  final String path = Constant.keyBuilder("/test/no/", no);  Long mutex=0l;  try {   System.out.println("在拿鎖:"+path+System.currentTimeMillis());    mutex = dLock.mutex(path, () -> {    try {     System.out.println("拿到鎖了" + System.currentTimeMillis());     Thread.sleep(10000);     System.out.println("操作完成了" + System.currentTimeMillis());    } finally {     return System.currentTimeMillis();    }   }, 1000, TimeUnit.MILLISECONDS);  } catch (ZkLockException e) {   System.out.println("拿不到鎖呀"+System.currentTimeMillis());  }  return Collections.singletonMap("ret",mutex); } @RequestMapping("/dlock") public Map testDLock1(String no){  final String path = Constant.keyBuilder("/test/no/", no);  Long mutex=0l;  try {   System.out.println("在拿鎖:"+path+System.currentTimeMillis());   InterProcessMutex processMutex = dLock.mutex(path);   processMutex.acquire();   System.out.println("拿到鎖了" + System.currentTimeMillis());   Thread.sleep(10000);   processMutex.release();   System.out.println("操作完成了" + System.currentTimeMillis());  } catch (ZkLockException e) {   System.out.println("拿不到鎖呀"+System.currentTimeMillis());   e.printStackTrace();  }catch (Exception e){   e.printStackTrace();  }  return Collections.singletonMap("ret",mutex); } @RequestMapping("/del") public Map delDLock(String no){  final String path = Constant.keyBuilder("/test/no/", no);  dLock.del(path);  return Collections.singletonMap("ret",1); }}

以上所述是小編給大家介紹的Java(SpringBoot)基于zookeeper的分布式鎖實現詳解整合,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對VeVb武林網網站的支持!


注:相關教程知識閱讀請移步到JAVA教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
亚洲香蕉成人av网站在线观看_欧美精品成人91久久久久久久_久久久久久久久久久亚洲_热久久视久久精品18亚洲精品_国产精自产拍久久久久久_亚洲色图国产精品_91精品国产网站_中文字幕欧美日韩精品_国产精品久久久久久亚洲调教_国产精品久久一区_性夜试看影院91社区_97在线观看视频国产_68精品久久久久久欧美_欧美精品在线观看_国产精品一区二区久久精品_欧美老女人bb
国产精品一区二区3区| 国产日韩av高清| 在线成人激情黄色| 亚洲美腿欧美激情另类| 精品久久久久久久久久久久| 亚洲成年人影院在线| 欧美精品午夜视频| 韩国视频理论视频久久| 亚洲视频在线免费观看| 尤物yw午夜国产精品视频明星| 久久精品国产清自在天天线| 中文日韩在线视频| 国模极品一区二区三区| 欧美激情奇米色| 久久久久久久网站| 日韩av电影在线播放| 亚洲欧美激情四射在线日| 美日韩精品免费视频| 精品在线小视频| 亚洲人成网站在线播| 日韩在线播放一区| 国产在线久久久| 久久亚洲精品一区| 国产日韩中文在线| 国内精久久久久久久久久人| 国产精品九九久久久久久久| 中文字幕国产精品久久| 欧美一级bbbbb性bbbb喷潮片| 亚洲视频电影图片偷拍一区| 国产日韩在线免费| 国产日韩在线免费| 九色精品美女在线| 亚洲专区中文字幕| 国产精品香蕉在线观看| 亚洲18私人小影院| 久久国产精品免费视频| 日韩av免费在线观看| 久久视频在线观看免费| 国产成+人+综合+亚洲欧美丁香花| 国产精品第3页| 亚洲精品网址在线观看| 97超视频免费观看| 91久久久久久| 原创国产精品91| 欧美激情在线一区| 成人www视频在线观看| 91在线观看免费高清完整版在线观看| 中文字幕av日韩| 在线色欧美三级视频| 日韩高清av在线| 久久99久久99精品中文字幕| 91久久精品日日躁夜夜躁国产| 久久成人国产精品| 久久久久久久久国产| 欧美日韩国产二区| 日韩视频在线观看免费| 91久久夜色精品国产网站| 亚洲成色999久久网站| 国产精品美乳一区二区免费| 日韩中文字幕亚洲| 国产精品一区二区三区久久| 成人综合网网址| xvideos亚洲人网站| 在线观看久久久久久| 国产精品白嫩美女在线观看| 亚洲伊人久久综合| 欧美成人精品h版在线观看| 久久久久久国产精品三级玉女聊斋| 久久全国免费视频| 国产在线精品成人一区二区三区| 国产精品第一页在线| 欧美日韩国产麻豆| 成人免费网站在线看| 日韩精品中文在线观看| 亚洲有声小说3d| 91精品久久久久久久久久入口| 日韩精品在线免费观看| 性金发美女69hd大尺寸| 国内精品久久久久久| 亚洲欧美视频在线| 17婷婷久久www| 日韩在线观看免费高清| 亚洲欧美日韩一区二区在线| 欧美日韩在线影院| 欧美黑人视频一区| 91沈先生在线观看| 国产精品视频免费在线| 国产精品色午夜在线观看| 国产精品视频最多的网站| 国产精品午夜国产小视频| 久久国产色av| 亚洲国产成人一区| 亚洲视屏在线播放| 亚洲欧美精品在线| 亚洲精品日韩久久久| 国产精品黄色影片导航在线观看| 亚洲国产女人aaa毛片在线| 日韩激情视频在线播放| 狠狠躁夜夜躁人人躁婷婷91| 久久久久久久久久久久久久久久久久av| 51视频国产精品一区二区| 国产欧美精品久久久| 一区二区欧美日韩视频| 九九热这里只有精品6| 国产精品久久久久av| 伊人一区二区三区久久精品| 日韩欧美一区二区在线| 国产欧美一区二区三区久久人妖| 97免费视频在线播放| 成人精品网站在线观看| 国产亚洲一区精品| 高清欧美一区二区三区| 在线观看日韩欧美| 91av视频在线播放| 国内精品视频久久| 亚洲精品一区av在线播放| 欧美激情中文网| 中文字幕久精品免费视频| 97视频在线免费观看| 亚洲欧美国产精品va在线观看| 日韩毛片中文字幕| 欧美第一淫aaasss性| 国产91精品不卡视频| 色青青草原桃花久久综合| 日韩一区二区欧美| 在线观看视频99| 国产精品av在线播放| 亚洲欧美日韩国产成人| 97国产精品久久| 97精品久久久中文字幕免费| 丝袜美腿精品国产二区| 欧美色另类天堂2015| 久久精彩免费视频| 亚洲精品一区av在线播放| 亚洲香蕉在线观看| 亚洲黄色在线观看| 91精品国产乱码久久久久久久久| 中文字幕精品在线视频| 欧美日本精品在线| 91久久久久久久久| 欧美激情免费观看| 欧美激情一区二区三区在线视频观看| 久久99国产精品久久久久久久久| 欧美性猛交xxxx黑人| 久久精品91久久久久久再现| 久久久精品网站| 亚洲欧美制服第一页| 麻豆国产精品va在线观看不卡| 欧美性猛交xxxx乱大交3| 蜜臀久久99精品久久久无需会员| 97视频免费在线看| 国产日韩精品一区二区| 国产一区二区三区在线播放免费观看| 国模视频一区二区| 亚洲电影av在线| 国产不卡av在线| 91最新在线免费观看| 日本中文字幕成人| 国产91精品视频在线观看| 成人激情视频在线观看| 97在线精品视频| 人妖精品videosex性欧美| 国产精品午夜视频| 久久综合亚洲社区|