maven依赖
<curator.version>2.8.0</curator.version> <dependency> <groupId>org.apache.curator</groupId> <artifactId>curator-framework</artifactId> <version>${curator.version}</version> </dependency> <dependency> <groupId>org.apache.curator</groupId> <artifactId>curator-recipes</artifactId> <version>${curator.version}</version> </dependency> <dependency> <groupId>org.apache.curator</groupId> <artifactId>curator-x-discovery</artifactId> <version>${curator.version}</version> </dependency>
获取连接
CuratorFramework client = CuratorFrameworkFactory.builder() .connectString("127.0.0.1:2181") .sessionTimeoutMs(5000) .connectionTimeoutMs(3000) .retryPolicy(new ExponentialBackoffRetry(1000, 3)) .build();
InterProcessMutex的使用
获取进程锁
CuratorFramework client = CuratorFrameworkFactory.builder() .connectString("127.0.0.1:2181") .sessionTimeoutMs(5000) .connectionTimeoutMs(3000) .retryPolicy(new ExponentialBackoffRetry(1000, 3)) .build(); client.start(); String lockName = "/head"; InterProcessLock lock1 = new InterProcessMutex(client, lockName); InterProcessLock lock2 = new InterProcessMutex(client, lockName); lock1.acquire(); boolean result = lock2.acquire(1, TimeUnit.SECONDS); System.out.println(result); lock1.release(); result = lock2.acquire(1, TimeUnit.SECONDS); System.out.println(result); client.close();