1.pom.xml
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.6</version>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>2.5.0</version>
</dependency>
</dependencies>
複製代碼
2.JAVA代碼
package com.xbq.zookeeper.curator;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.RetryNTimes;
public class LockByCurator {
private static String CONNECT_SERVER = "192.168.242.129:2181,192.168.242.129:2182,192.168.242.129:2183";
private static int SESSION_TIMEOUT = 3000;
private static int CONNECTION_TIMEOUT = 3000;
private static final String CURATOR_LOCK = "/curatorLock";
public static void doLock(CuratorFramework cf){
System.out.println(Thread.currentThread().getName() + " 嘗試獲取鎖!");
InterProcessMutex mutex = new InterProcessMutex(cf, CURATOR_LOCK);
try {
if(mutex.acquire(5, TimeUnit.SECONDS)){
System.out.println(Thread.currentThread().getName() + " 獲取到了鎖!-------");
Thread.sleep(5000);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
mutex.release();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
ExecutorService service = Executors.newCachedThreadPool();
final Semaphore semaphore = new Semaphore(10);
for(int i=0; i < 10 ;i++){
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
semaphore.acquire();
CuratorFramework framework = CuratorFrameworkFactory.
newClient(CONNECT_SERVER, SESSION_TIMEOUT, CONNECTION_TIMEOUT, new RetryNTimes(10,5000));
framework.start();
doLock(framework);
semaphore.release();
} catch (Exception e) {
}
}
};
service.execute(runnable);
}
service.shutdown();
}
}
複製代碼
歡迎關注個人公衆號,第一時間接收最新文章~ 搜索公衆號:
碼咖 或者 掃描下方二維碼: