国产激情自拍_国产9色视频_丁香花在线电影小说观看 _久久久久国产精品嫩草影院

首頁 > 開發(fā) > Java > 正文

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

2024-07-14 08:43:42
字體:
供稿:網(wǎng)友

通過zookeeper實現(xiàn)分布式鎖

1、創(chuàng)建zookeeper的client

首先通過CuratorFrameworkFactory創(chuàng)建一個連接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、封裝分布式鎖

根據(jù)CuratorFramework創(chuàng)建InterProcessMutex(分布式可重入排它鎖)對一行數(shù)據(jù)進(jìn)行上鎖

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

使用 acquire方法
1、acquire() :入?yún)榭?,調(diào)用該方法后,會一直堵塞,直到搶奪到鎖資源,或者zookeeper連接中斷后,上拋異常。
2、acquire(long time, TimeUnit unit):入?yún)魅氤瑫r時間、單位,搶奪時,如果出現(xiàn)堵塞,會在超過該時間后,返回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、調(diào)用InterProcessMutex processMutex = dLock.mutex(path);

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

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

推薦 使用:
都是 函數(shù)式編程
在業(yè)務(wù)代碼執(zhí)行完畢后 會釋放鎖和刪除path
1、這個有返回結(jié)果
public T mutex(String path, ZkLockCallback zkLockCallback, long time, TimeUnit timeUnit)
2、這個無返回結(jié)果
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的分布式鎖實現(xiàn)詳解整合,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對VeVb武林網(wǎng)網(wǎng)站的支持!


注:相關(guān)教程知識閱讀請移步到JAVA教程頻道。
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
国产激情自拍_国产9色视频_丁香花在线电影小说观看 _久久久久国产精品嫩草影院
四虎精品成人a在线观看| 国产一级二级在线| 国产原创在线播放| 黄色国产网站在线播放| 牛牛精品视频在线| 成人免费一区二区三区视频网站| 欧美日韩国产亚洲沙发| 在线视频色在线| eeuss影院www在线播放| eeuss影院在线观看| 亚洲精品天堂在线| 18av在线视频| 99在线免费视频| www.国产精| 中文字幕日本三级| av二区三区| 最近中文字幕mv免费高清在线| 国产美女av在线| 国产精品自产拍在线网站| 国产精品入口麻豆免费观看| 国产精品剧情一区二区三区 | 亚洲综合天堂网| 久久国产综合视频| 福利视频网站导航| 亚洲电影先锋| 国产精品久久久高清免费| 日本福利午夜视频在线| 国产美女视频网站| 日本h片在线观看| 精品久久久久一区二区三区| 久久国产热视频| 白浆爆出在线观看| 99福利在线| 伊人免费视频| 18激情网站| 国产精品人人| 国产中文伊人| 奇米影视狠狠狠| 四虎成年永久免费网站| av在线第一页| 国产国语**毛片高清视频| 懂色av一区| 免费影视观看网站入口| 香蕉视频免费在线播放| 91www在线观看| av福利在线观看| 国产黄色免费网| 国产精品爱久久久久久久小说| 国产视频精品久久| 天天操天天操天天色天天要| 久精品在线观看| 另类综合图区| 国产在线视精品麻豆| 激情丁香久久| 国产永久免费高清在线观看视频| 国产在线激情视频| av资源网站在线观看| 青青草原国产在线观看| 四虎久久影院| 日本中文字幕在线播放| 中文字幕在线观看播放| 成人超碰在线| 中文av在线播放| 不卡av免费观看| 久久久久久国产视频| 国产女王在线**视频 | 精品无吗乱吗av国产爱色| 国产精品伦理一区二区三区| 在线激情小视频| 一级二级在线观看| 最近中文字幕mv免费高清视频8| 国产乱子伦三级在线播放| 国产裸舞福利在线视频合集| 国产成人va亚洲电影| 麻豆精品传媒视频观看| 国产69精品久久久久孕妇国产69久久 | 国产高清免费视频| 精品极品三级久久久久| 一本大道久久精品| 免费a级人成a大片在线观看| 国产小视频免费在线网址| 亚洲天堂久久久| 国产三级av在线| 亚洲一道本在线| 国产免费a∨片在线观看不卡| 大香伊人中文字幕精品| 午夜视频在线观看网站午夜视频在线 | 国产不卡视频| 男女羞羞视频在线观看| 久久综合精品视频| 亚洲尤物在线视频| 国产高清在线| 国产无遮挡又黄又爽免费软件| 欧美性猛交xxxx免费看久久| 国产香蕉免费精品视频| 欧美色第一页| 在线视频99| 尤物在线视频| 免费久久网站| 免费国产视频| 久久五月精品| 国产在线激情视频| 开心丁香婷婷深爱五月| 国产成人精品自线拍| 天堂在线亚洲| 久热免费在线视频| 九九热在线免费视频| av一本在线| 国产一级在线| 黄色三级视频在线观看| 亚洲天堂电影在线观看| 亚洲夜夜综合| 国产在线看片| 国产黄色在线播放| 中文天堂av| 国产娇喘精品一区二区三区图片| 国产精品久久久久久久久鸭| 国产美女在线看| 国产黄视频网站| 在线观看中文字幕| 欧美日韩在线资源| 最好2018中文免费视频| 国产卡二和卡三的视频| 中文字幕在线观看播放| 国产黄色一级片| 精品a在线观看| 亚洲视频手机在线观看| 免费a级在线播放| 国产系列电影在线播放网址| 亚洲字幕成人中文在线观看| 国产中文字幕在线看| 91美女在线| 老司机在线视频二区| 国产日本在线| 日本片在线看| 国产欧美日韩专区| 任你操视频在线观看| 国产一二三区精品视频| 国产美女一区视频| 一色桃子av在线| 国产精品久久久久永久免费看| 精品免费视频一卡2卡三卡4卡不卡| 开心婷婷激情| yjizz视频网站在线播放| 最近中文字幕mv免费高清在线| jizz在线视频| 国产精品jvid在线观看| 成人欧美日韩| av在线1区2区| 国产精品秘入口| 福利视频网址导航| 看成年女人免费午夜视频| gogogo影视剧免费观看在线观看| 国产天堂资源| 国产一级黄色| 国产精品久久久久久福利| 人成在线免费视频| free性亚洲| www.狠狠操| a视频在线播放| 亚洲综合色视频在线观看 | 国产aa视频| 国产精品被窝福利一区| 国产精品剧情一区二区三区| 国产青草视频在线观看视频| 1区不卡电影| 国产三级视频| 国产成人午夜精品| 中文字幕在线免费| 国产激情在线| 亚洲精品在线播放视频| av日韩国产| 日本不卡1区2区3区| 日本成人在线播放| 丁香花高清在线观看完整版| 国产一二三区在线观看| 国产人成在线观看| 91免费日韩| 激情亚洲综合网| 国产秀色在线www免费观看| 国产日本在线视频| 亚洲欧美精品日韩欧美| 免费观看一二区视频网站| 午夜在线不卡| 国产秀色在线www免费观看| 国产精品理人伦一区二区三区| 日本精品一区二区三区在线播放| 天天操夜夜摸| 国产三级在线| 蜜桃视频中文字幕| 国产精品白浆流出视频| 欧美日韩视频精品二区| 最新黄网在线观看| 欧美日韩在线精品成人综合网| 国产精品视频一区麻豆| 超碰免费在线播放| av福利在线观看| 国产一卡二卡3卡4卡四卡在线| 国产高清在线看| 四虎久久影院|