/** * Return a service instance POJO * * @param name name of the service * @param id ID of the instance * @return the instance or <code>null</code> if not found * @throws Exception errors */ @Override public ServiceInstance<T> queryForInstance(String name, String id) throws Exception { String path = pathForInstance(name, id); try { byte[] bytes = client.getData().forPath(path); return serializer.deserialize(bytes); } catch (KeeperException.NoNodeException ignore) { // ignore } return null; }
@Override public void updateService(final ServiceInstance<T> service) throws Exception { Entry<T> entry = services.get(service.getId()); if (entry == null) { throw new Exception("Service not registered: " + service); } synchronized (entry) { entry.service = service; byte[] bytes = serializer.serialize(service); String path = pathForInstance(service.getName(), service.getId()); client.setData().forPath(path, bytes); } }
@VisibleForTesting protected void internalRegisterService(ServiceInstance<T> service) throws Exception { byte[] bytes = serializer.serialize(service); String path = pathForInstance(service.getName(), service.getId()); final int MAX_TRIES = 2; boolean isDone = false; for (int i = 0; !isDone && (i < MAX_TRIES); ++i) { try { CreateMode mode = (service.getServiceType() == ServiceType.DYNAMIC) ? CreateMode.EPHEMERAL : CreateMode.PERSISTENT; client.create().creatingParentsIfNeeded().withMode(mode).forPath(path, bytes); isDone = true; } catch (KeeperException.NodeExistsException e) { client.delete().forPath(path); // must delete then re-create so that watchers fire } } }