public boolean acquireLock(long maxWait, TimeUnit unit) { KeyValueClient kv = consul.keyValueClient(); sessionId = createSession(); Optional<Value> value = kv.getValue(path); if (kv.acquireLock(path, sessionId)) { return true; } BigInteger index = BigInteger.valueOf(value.get().getModifyIndex()); kv.getValue(path, QueryOptions.blockMinutes((int) unit.toMinutes(maxWait), index).build()); if (!kv.acquireLock(path, sessionId)) { destroySession(); return false; } else { return true; } }
/** * Aquire a lock for a given key. * * PUT /v1/kv/{key}?acquire={session} * * @param key The key to acquire the lock. * @param session The session to acquire lock. * @return true if the lock is acquired successfully, false otherwise. */ public boolean acquireLock(final String key, final String session) { return acquireLock(key, "", session); }
private boolean acquireLock() { synchronized (sessionId) { String sid = sessionId.get(); return (sid != null) ? sessionClient.getSessionInfo(sid).map(si -> keyValueClient.acquireLock(path, sid)).orElse(Boolean.FALSE) : false; } }
private void bind() throws InterruptedException, EndpointAlreadyInUseException { while (!closed()) { LOGGER.info("Attempting to binding to RPC endpoint document {}", endpointKey); final boolean acquired = kv.acquireLock(endpointKey, "{}", sessionId); if (acquired) { LOGGER.info("Successfully bound to RPC endpoint document {}", endpointKey); return; } final Optional<ConsulResponse<Value>> existing = kv.getConsulResponseWithValue(endpointKey); if (existing.isPresent()) { // somebody else has acquired the lock final String lockSession = existing.get().getResponse().getSession().orElse(null); throw new EndpointAlreadyInUseException( "Failed to lock RPC endpoint document " + endpointKey + " ; already locked by session " + lockSession); } LOGGER.info("Endpoint lock acquisition failed; will retry after delay."); SECONDS.sleep(1); } } }
@InvokeOnHeader(ConsulKeyValueActions.LOCK) protected void lock(Message message) throws Exception { message.setHeader(ConsulConstants.CONSUL_RESULT, getClient().acquireLock( getMandatoryHeader(message, ConsulConstants.CONSUL_KEY, getConfiguration().getKey(), String.class), message.getBody(String.class), message.getHeader(ConsulConstants.CONSUL_SESSION, "", String.class) ) ); }
@Override public void onComplete(ConsulResponse<Optional<Value>> consulResponse) { if (isRunAllowed()) { Optional<Value> value = consulResponse.getResponse(); if (value.isPresent()) { Optional<String> sid = value.get().getSession(); if (sid.isPresent() && ObjectHelper.isNotEmpty(sid.get())) { // If the key is not held by any session, try acquire a // lock (become leader) LOGGER.debug("Try to take leadership ..."); setLeader(keyValueClient.acquireLock(servicePath, sessionId)); } else if (!sessionId.equals(sid) && leader.get()) { // Looks like I've lost leadership setLeader(false); } } index.set(consulResponse.getIndex()); run(); } }
public Optional<String> electNewLeaderForService(final String serviceName, final String info) { final String key = getServiceKey(serviceName); String sessionId = createSession(serviceName); if(client.keyValueClient().acquireLock(key, info, sessionId)){ return Optional.of(info); }else{ return getLeaderInfoForService(serviceName); } }
while (!closed()) { LOGGER.info("Racing to become new leader."); final boolean acquired = kv.acquireLock(leaderKey, candidateUuid, sessionId);
public void remove(String key) { // create session to avoid conflicts (not sure if that is safe enough) SessionClient sessionClient = consul.sessionClient(); String sessionName = "session_" + UUID.randomUUID().toString(); SessionCreatedResponse response = sessionClient .createSession(ImmutableSession.builder().name(sessionName).build()); String sessionId = response.getId(); kvClient = consul.keyValueClient(); String lockKey = "lock_" + key; kvClient.acquireLock(lockKey, sessionName, sessionId); Object object = lookupByName(key); if (object == null) { String msg = "Bean with key '" + key + "' did not exist in Consul Registry."; throw new NoSuchBeanException(msg); } kvClient.deleteKey(key); kvClient.deleteKey(object.getClass().getName() + "/" + key); kvClient.releaseLock(lockKey, sessionId); }
public void put(String key, Object object) { // Substitute $ character in key key = key.replaceAll("\\$", "/"); // create session to avoid conflicts // (not sure if that is safe enough, again) SessionClient sessionClient = consul.sessionClient(); String sessionName = "session_" + UUID.randomUUID().toString(); SessionCreatedResponse response = sessionClient .createSession(ImmutableSession.builder().name(sessionName).build()); String sessionId = response.getId(); kvClient = consul.keyValueClient(); String lockKey = "lock_" + key; kvClient.acquireLock(lockKey, sessionName, sessionId); // Allow only unique keys, last one wins if (lookupByName(key) != null) { remove(key); } Object clone = ConsulRegistryUtils.clone((Serializable) object); byte[] serializedObject = ConsulRegistryUtils.serialize((Serializable) clone); // pre-encode due native encoding issues String value = ConsulRegistryUtils.encodeBase64(serializedObject); // store the actual class kvClient.putValue(key, value); // store just as a bookmark kvClient.putValue(object.getClass().getName().replaceAll("\\$", "/") + "/" + key, "1"); kvClient.releaseLock(lockKey, sessionId); }
boolean acquired = consul.keyValueClient().acquireLock("couchbase:cbes:" + serviceName + ":vbucket:" + i, sessionId); System.out.println(acquired);
setLeader(keyValueClient.acquireLock(servicePath, sessionId));