Private static Boolean wasAcquired = false; Public void tetsZookeeper(){String serverId = uID.randomuuid ().toString().tolowerCase (); public void tetsZookeeper(){String serverId = uID.randomuuid ().toString().tolowerCase (); AccountLock lock = new AccountLock(“/ACCOUNT/” + serverId,zookeeperConnector); Log.info (” Start getting locks “); wasAcquired = lock.acquire(3); / / lock the info (” acquiring a lock: “+ (wasAcquired?” SUCCESS “:” ERROR “)); Try {System. Out. Println (” 11111111 “); Thread.sleep(2000); return; }catch (Exception e){ log.error(e.getMessage(),e); }finally {log.info(” Start unlocking… “) ); lock.release(); // Release the lock}}

AccountLock class package com. Baibei. Pay. Utils;

import com.baibei.pay.configurer.ZooKeeperConnector; import lombok.extern.slf4j.Slf4j; import org.apache.curator.framework.recipes.locks.InterProcessMutex;

import java.util.concurrent.TimeUnit;

@Slf4j public class AccountLock { InterProcessMutex lock; boolean wasAcquired = false; // Whether the lock is obtained

public AccountLock(String path, ZooKeeperConnector zookeeperConnector) { lock = new InterProcessMutex(zookeeperConnector.getClient(), path); }

/ * *

  • Try locking and wait
  • @param timeOut
  • Timeout time (seconds), -1 unlimited
  • @return True: the lock is successfully obtained. False: the lock fails to be obtained
  • @throws Exception */ public boolean acquire(int timeOut) { try { wasAcquired = lock.acquire(timeOut, TimeUnit.SECONDS); } catch (Exception e) {log.error(‘ get Lock time out error: ‘+ LLDB message ()); wasAcquired = false; } return wasAcquired; }

/ * *

  • Release the lock
  • @throws Exception */ public void release() { if (wasAcquired) { try { lock.release(); } catch (Exception e) {log.error(‘ remove Lock error: ‘+ LLDB message ()); }}}}

The author: frowsty coquettish fox source: CSDN, blog.csdn.net/fox100629/a… Copyright notice: This article is the blogger’s original article, reprint please attach the blog link!