public synchronized void passHealthCheck() { if (!shouldPassHealthCheck) { // throwing an exception stops the scheduled task from running again. throw new RuntimeException("Stopping recurring health check task."); } try { consul.agentClient().pass(serviceId, "(" + serviceId + ") OK"); LOGGER.debug("Passed health check."); } catch (Throwable t) { fatalErrorConsumer.accept(new RuntimeException("Failed to tell Consul agent we passed health check.", t)); Throwables.throwIfUnchecked(t); throw new RuntimeException(t); } }
@Override public void run() { AgentClient client = this.agentClientInjector.getValue(); while (true) { this.advertisements .stream() .forEach(e -> { try { client.pass(serviceId(e)); } catch (NotRegisteredException e1) { // ignore? e1.printStackTrace(); } }); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); break; } } }
@Test public void registerServiceForConsul() throws Exception { Consul consul = Consul.builder().withHostAndPort(HostAndPort.fromParts("127.0.0.1", 8500)).build(); AgentClient agentClient = consul.agentClient(); String serviceId = UUID.randomUUID().toString(); String serviceName = "java-consul-service"; String serviceTag = "test"; long ttl = 3l; agentClient.register(9090, ttl, serviceName, serviceId, serviceTag); agentClient.pass(serviceId); System.out.println("succ."); TimeUnit.MINUTES.sleep(2); } }
public synchronized void heartbeat() throws ClusterMembershipException { if (panic) { throw new ClusterMembershipException("Already permanently failed a health check."); } try { consul.agentClient().pass(serviceId, "(" + serviceId + ") OK"); } catch (NotRegisteredException e) { // todo re-register? maybe only if we haven't skipped too many heartbeats since last "pass"? if (hasCause(e, ConnectException.class)) { throw new ClusterMembershipException("Lost connection to Consul agent.", e); } throw new ClusterMembershipException("Consul doesn't think we're registered.", e); } }
@Override public void sendHeartbeat() throws SiteWhereException { if (getConsulClient() != null) { AgentClient agentClient = getConsulClient().agentClient(); try { String serviceId = getMicroservice().getId().toString(); if (agentClient.isRegistered(serviceId)) { agentClient.pass(serviceId); } } catch (NotRegisteredException e) { throw new SiteWhereException("Unable to send heartbeat.", e); } } else { getLogger().info("Skipping heartbeat. Consul client not connected."); } }