使用Netflix的包 curator-recipes
pom文件引入相关依赖
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.6.3</version>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-framework</artifactId>
<version>5.2.0</version>
<exclusions>
<exclusion>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
</exclusion>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>5.2.0</version>
<exclusions>
<exclusion>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
</exclusion>
</exclusions>
</dependency>
使用范例:
import org.apache.curator.RetryPolicy;
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.ExponentialBackoffRetry;
......
private static final String SIT_ZK_IP_PORT = "10.82.232.9xx:2181,10.82.232.9xx:2181,10.82.2329xx68:2181";
public static void main(String[] args) throws Exception {
//创建zookeeper客户端连接
//重试策略, 参数1:等待时间, 参数2:重试次数
RetryPolicy policy = new ExponentialBackoffRetry(2000, 3);
final String ZK_IP_PORT = SIT_ZK_IP_PORT;
CuratorFramework client = CuratorFrameworkFactory.builder().connectString(ZK_IP_PORT).retryPolicy(policy).build();
client.start();
final InterProcessMutex mutex = new InterProcessMutex(client, "/fruit-history-package-lock");
long startTime = 0L;
try {
System.out.println("==== 开始抢锁.... ");
mutex.acquire();
startTime = System.currentTimeMillis();
System.out.println("==== 抢到锁, 开始执行.... ");
// 自己的搬砖逻辑
doXX();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("执行抛异常,请检查", e);
} finally {
try {
mutex.release();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("==== 执行完毕, 释放锁....耗时: " + (System.currentTimeMillis() - startTime)/1000 + "秒");
}
}
会在zk上创建临时节点 fruit-history-package-lock, 并在该节点下创建顺序临时节点用于锁机制的排队