<dependencies> <dependency> <groupId>org.apache.curator</groupId> <artifactId>curator-recipes</artifactId> <version>4.2.0</version> </dependency> </dependencies> import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.recipes.locks.InterProcessMutex; public class DistributedLockExample { private final InterProcessMutex lock; public DistributedLockExample(CuratorFramework client, String lockPath) { lock = new InterProcessMutex(client, lockPath); } public void doSomething() throws Exception { if (lock.acquire(10, TimeUnit.SECONDS)) { try { } finally { lock.release(); } } else { } } } import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.recipes.cache.PathChildrenCache; import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent; import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener; public class DistributedCacheExample { private final PathChildrenCache cache; public DistributedCacheExample(CuratorFramework client, String path) throws Exception { cache = new PathChildrenCache(client, path, true); cache.start(); } public void listenForChanges() { PathChildrenCacheListener listener = (client, event) -> { if (event.getType() == PathChildrenCacheEvent.Type.CHILD_UPDATED) { String path = event.getData().getPath(); byte[] data = event.getData().getData(); } }; cache.getListenable().addListener(listener); } }


上一篇:
下一篇:
切换中文