<dependency> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> <version>3.4.14</version> </dependency> private CuratorFramework client; public void init() { client = CuratorFrameworkFactory.builder() .connectString("localhost:2181") .sessionTimeoutMs(5000) .retryPolicy(new ExponentialBackoffRetry(1000, 3)) .build(); client.start(); } public void acquireLock(String lockPath) throws Exception { String lockNode = client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath(lockPath); while (true) { List<String> lockNodes = client.getChildren().forPath(lockPath); Collections.sort(lockNodes); if (lockNode.equals(lockPath + "/" + lockNodes.get(0))) { break; } else { client.getChildren().usingWatcher(watcher).forPath(lockPath); synchronized (watcher) { watcher.wait(); } } } } public void releaseLock(String lockPath) throws Exception { client.delete().forPath(lockPath); synchronized (watcher) { watcher.notifyAll(); } } <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>3.6.0</version> </dependency> private Jedis jedis; public void init() { jedis = new Jedis("localhost"); } public boolean acquireLock(String lockKey, String requestId, int expireTime) { String result = jedis.set(lockKey, requestId, "NX", "PX", expireTime); return "OK".equals(result); } public boolean releaseLock(String lockKey, String requestId) { String script = "if redis.call('get', KEYS[1]) == ARGV[1] " + "then " + "return redis.call('del', KEYS[1]) " + "else " + "return 0 " + "end"; Object result = jedis.eval(script, Collections.singletonList(lockKey), Collections.singletonList(requestId)); return result.equals(1L); }


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