com.orbitz.consul.Consul Java Examples

The following examples show how to use com.orbitz.consul.Consul. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PropertyConfig.java    From kafka-topic-exporter with Apache License 2.0 6 votes vote down vote up
ArrayList<String> getBootStrapServersFromConsul(String consulServer, String consulKafkaServicename) {
    ArrayList<String> bootstrapServers = null;
    LOG.info("CONSUL: Consul server used: [" + consulServer + "]");
    LOG.info("CONSUL: Consul service retrieved: [" + consulKafkaServicename + "]");
    try {
        Consul consul = Consul.builder().withUrl(consulServer).build();
        HealthClient healthClient = consul.healthClient();

        // discover only "passing" nodes
        List<ServiceHealth> nodes = healthClient.getHealthyServiceInstances(consulKafkaServicename).getResponse();
        for (ServiceHealth kafkaNode : nodes) {
            String address = kafkaNode.getService().getAddress();
            String port = kafkaNode.getService().getPort() + "";
            if (bootstrapServers == null) {
                bootstrapServers = new ArrayList<String>();
            }
            bootstrapServers.add(address + ":" + port);
        }
    } catch (Exception e){
        LOG.error("CONSUL: " + e.toString());
    }
    LOG.info("CONSUL: Kafka services found through Consul server: " + (bootstrapServers==null?"None available":bootstrapServers.toString()));
    return bootstrapServers;
}
 
Example #2
Source File: ConsulService.java    From ARCHIVE-wildfly-swarm with Apache License 2.0 6 votes vote down vote up
@Override
public void start(StartContext startContext) throws StartException {

    Consul.Builder builder = Consul.builder();


    // pool because of multiple threads.
    ResteasyClientBuilder clientBuilder = new ResteasyClientBuilder();
    clientBuilder = clientBuilder.connectionPoolSize(20);

    builder.withClientBuilder(clientBuilder);
    builder.withUrl(this.url);

    try {
        this.consul = builder.build();
    } catch (Exception e) {
        throw new StartException("Failed to connect consul at "+url, e);
    }
}
 
Example #3
Source File: ConsulFactory.java    From dropwizard-consul with Apache License 2.0 6 votes vote down vote up
@JsonIgnore
public Consul build() {

  final Consul.Builder builder = Consul.builder().withHostAndPort(endpoint).withPing(servicePing);

  aclToken.ifPresent(
      token -> {
        // setting both acl token here and with header, supplying an auth
        // header. This should cover both use cases: endpoint supports
        // legacy ?token query param and other case in which endpoint
        // requires an X-Consul-Token header.
        // @see https://www.consul.io/api/index.html#acls
        builder.withAclToken(token).withHeaders(ImmutableMap.of(CONSUL_AUTH_HEADER_KEY, token));
      });

  return builder.build();
}
 
Example #4
Source File: ConsulModule.java    From nano-framework with Apache License 2.0 6 votes vote down vote up
@Override
public void configure(final Binder binder) {
    loading();

    cfgs.forEach((id, cfg) -> {
        final Consul consul = build(cfg);
        binder.bind(Consul.class).annotatedWith(Names.named(CONSUL_PREFIX + id)).toInstance(consul);
        binder.bind(AgentClient.class).annotatedWith(Names.named(CONSUL_AGENT_CLIENT_PREFIX + id)).toInstance(consul.agentClient());
        binder.bind(HealthClient.class).annotatedWith(Names.named(CONSUL_HEALTH_CLIENT_PREFIX + id)).toInstance(consul.healthClient());
        binder.bind(KeyValueClient.class).annotatedWith(Names.named(CONSUL_KEY_VALUE_CLIENT_PREFIX + id)).toInstance(consul.keyValueClient());
        binder.bind(CatalogClient.class).annotatedWith(Names.named(CONSUL_CATALOG_CLIENT_PREFIX + id)).toInstance(consul.catalogClient());
        binder.bind(StatusClient.class).annotatedWith(Names.named(CONSUL_STATUS_CLIENT_PREFIX + id)).toInstance(consul.statusClient());
        binder.bind(SessionClient.class).annotatedWith(Names.named(CONSUL_SESSION_CLIENT_PREFIX + id)).toInstance(consul.sessionClient());
        binder.bind(EventClient.class).annotatedWith(Names.named(CONSUL_EVENT_CLIENT_PREFIX + id)).toInstance(consul.eventClient());
        binder.bind(PreparedQueryClient.class).annotatedWith(Names.named(CONSUL_PREPARED_QUERY_CLIENT_PREFIX + id))
                .toInstance(consul.preparedQueryClient());
        binder.bind(CoordinateClient.class).annotatedWith(Names.named(CONSUL_COORDINATE_CLIENT_PREFIX + id))
                .toInstance(consul.coordinateClient());
        binder.bind(OperatorClient.class).annotatedWith(Names.named(CONSUL_OPERATOR_CLIENT + id)).toInstance(consul.operatorClient());
    });

}
 
Example #5
Source File: ClusterModuleConsulProviderTest.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@Test
public void prepareSingle() throws Exception {
    ClusterModuleConsulConfig consulConfig = new ClusterModuleConsulConfig();
    consulConfig.setHostPort("10.0.0.1:1000");
    Whitebox.setInternalState(provider, "config", consulConfig);

    Consul consulClient = mock(Consul.class);
    Consul.Builder builder = mock(Consul.Builder.class);
    when(builder.build()).thenReturn(consulClient);

    PowerMockito.mockStatic(Consul.class);
    when(Consul.builder()).thenReturn(builder);
    when(builder.withConnectTimeoutMillis(anyLong())).thenCallRealMethod();

    when(builder.withHostAndPort(any())).thenReturn(builder);

    provider.prepare();

    ArgumentCaptor<HostAndPort> hostAndPortArgumentCaptor = ArgumentCaptor.forClass(HostAndPort.class);
    verify(builder).withHostAndPort(hostAndPortArgumentCaptor.capture());

    HostAndPort address = hostAndPortArgumentCaptor.getValue();
    assertEquals(HostAndPort.fromParts("10.0.0.1", 1000), address);
}
 
Example #6
Source File: ClusterModuleConsulProviderTest.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void prepare() throws Exception {
    ClusterModuleConsulConfig consulConfig = new ClusterModuleConsulConfig();
    consulConfig.setHostPort("10.0.0.1:1000,10.0.0.2:1001");
    Whitebox.setInternalState(provider, "config", consulConfig);

    Consul consulClient = mock(Consul.class);
    Consul.Builder builder = mock(Consul.Builder.class);
    when(builder.build()).thenReturn(consulClient);

    PowerMockito.mockStatic(Consul.class);
    when(Consul.builder()).thenReturn(builder);
    when(builder.withConnectTimeoutMillis(anyLong())).thenReturn(builder);

    when(builder.withMultipleHostAndPort(anyCollection(), anyLong())).thenReturn(builder);
    provider.prepare();

    ArgumentCaptor<Collection> addressCaptor = ArgumentCaptor.forClass(Collection.class);
    ArgumentCaptor<Long> timeCaptor = ArgumentCaptor.forClass(long.class);
    verify(builder).withMultipleHostAndPort(addressCaptor.capture(), timeCaptor.capture());

    List<HostAndPort> address = (List<HostAndPort>) addressCaptor.getValue();
    assertEquals(2, address.size());
    assertEquals(Lists.newArrayList(HostAndPort.fromParts("10.0.0.1", 1000), HostAndPort.fromParts("10.0.0.2", 1001)), address);
}
 
Example #7
Source File: ConsulBundle.java    From dropwizard-consul with Apache License 2.0 6 votes vote down vote up
protected void setupEnvironment(ConsulFactory consulConfig, Environment environment) {

    final Consul consul = consulConfig.build();
    final String serviceId = consulConfig.getServiceId().orElse(UUID.randomUUID().toString());
    final ConsulAdvertiser advertiser =
        new ConsulAdvertiser(environment, consulConfig, consul, serviceId);

    final Optional<Duration> retryInterval = consulConfig.getRetryInterval();
    final Optional<ScheduledExecutorService> scheduler =
        retryInterval.map(i -> Executors.newScheduledThreadPool(1));

    // Register a Jetty listener to get the listening host and port
    environment
        .lifecycle()
        .addServerLifecycleListener(
            new ConsulServiceListener(advertiser, retryInterval, scheduler));

    // Register a ping healthcheck to the Consul agent
    environment.healthChecks().register("consul", new ConsulHealthCheck(consul));

    // Register a shutdown manager to deregister the service
    environment.lifecycle().manage(new ConsulAdvertiserManager(advertiser, scheduler));

    // Add an administrative task to toggle maintenance mode
    environment.admin().addTask(new MaintenanceTask(consul, serviceId));
  }
 
Example #8
Source File: ITConsulConfigurationTest.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 60000)
public void shouldReadUpdated() {
    assertNull(provider.watcher.value());

    String hostAndPort = System.getProperty("consul.address", "127.0.0.1:8500");
    Consul consul = Consul.builder()
                          .withHostAndPort(HostAndPort.fromString(hostAndPort))
                          .withConnectTimeoutMillis(5000)
                          .build();
    KeyValueClient client = consul.keyValueClient();

    assertTrue(client.putValue("test-module.default.testKey", "1000"));

    for (String v = provider.watcher.value(); v == null; v = provider.watcher.value()) {
    }

    assertEquals("1000", provider.watcher.value());

    client.deleteKey("test-module.default.testKey");

    for (String v = provider.watcher.value(); v != null; v = provider.watcher.value()) {
    }

    assertNull(provider.watcher.value());
}
 
Example #9
Source File: ConsulDiscoveryService.java    From jim-framework with Apache License 2.0 5 votes vote down vote up
@Override
public List<RpcURL> getUrls(String registryHost,int registryPort) {
    List<RpcURL> urls= Lists.newArrayList();
    Consul consul = this.buildConsul(registryHost,registryPort);
    HealthClient client = consul.healthClient();
    String name = CONSUL_NAME;
    ConsulResponse object= client.getAllServiceInstances(name);
    List<ImmutableServiceHealth> serviceHealths=(List<ImmutableServiceHealth>)object.getResponse();
    for(ImmutableServiceHealth serviceHealth:serviceHealths){
        RpcURL url=new RpcURL();
        url.setHost(serviceHealth.getService().getAddress());
        url.setPort(serviceHealth.getService().getPort());
        urls.add(url);
    }

    try {
        ServiceHealthCache serviceHealthCache = ServiceHealthCache.newCache(client, name);
        serviceHealthCache.addListener(new ConsulCache.Listener<ServiceHealthKey, ServiceHealth>() {
            @Override
            public void notify(Map<ServiceHealthKey, ServiceHealth> map) {
                logger.info("serviceHealthCache.addListener notify");
                RpcClientInvokerCache.clear();

            }
        });
        serviceHealthCache.start();
    } catch (Exception e) {
        logger.info("serviceHealthCache.start error:",e);
    }
    return urls;
}
 
Example #10
Source File: ConsulConfigurationSource.java    From cfg4j with Apache License 2.0 5 votes vote down vote up
/**
 * @throws SourceCommunicationException when unable to connect to Consul client
 */
@Override
public void init() {
  try {
    LOG.info("Connecting to Consul client at " + host + ":" + port);

    Consul consul = Consul.builder().withHostAndPort(HostAndPort.fromParts(host, port)).build();

    kvClient = consul.keyValueClient();
  } catch (Exception e) {
    throw new SourceCommunicationException("Can't connect to host " + host + ":" + port, e);
  }

  initialized = true;
}
 
Example #11
Source File: ConsulTopologyConnector.java    From ARCHIVE-wildfly-swarm with Apache License 2.0 5 votes vote down vote up
@Override
public void start(StartContext startContext) throws StartException {
    ServiceTarget target = startContext.getChildTarget();

    ConsulService consul = new ConsulService(this.url);
    target.addService(ConsulService.SERVICE_NAME, consul)
            .install();

    HealthClientService healthClient = new HealthClientService();
    target.addService(HealthClientService.SERIVCE_NAME, healthClient)
            .addDependency(ConsulService.SERVICE_NAME, Consul.class, healthClient.getConsulInjector())
            .install();

    AgentClientService agentClient = new AgentClientService();
    target.addService(AgentClientService.SERVICE_NAME, agentClient)
            .addDependency(ConsulService.SERVICE_NAME, Consul.class, agentClient.getConsulInjector())
            .install();

    CatalogClientService catalogClient = new CatalogClientService();
    target.addService(CatalogClientService.SERVICE_NAME, catalogClient)
            .addDependency(ConsulService.SERVICE_NAME, Consul.class, catalogClient.getConsulInjector())
            .install();


    this.advertiser = new Advertiser();
    target.addService(Advertiser.SERVICE_NAME, advertiser)
            .addDependency(AgentClientService.SERVICE_NAME, AgentClient.class, advertiser.getAgentClientInjector())
            .install();

    CatalogWatcher watcher = new CatalogWatcher();
    target.addService(CatalogWatcher.SERVICE_NAME, watcher)
            .addDependency(CatalogClientService.SERVICE_NAME, CatalogClient.class, watcher.getCatalogClientInjector())
            .addDependency(HealthClientService.SERIVCE_NAME, HealthClient.class, watcher.getHealthClientInjector())
            .addDependency(TopologyManager.SERVICE_NAME, TopologyManager.class, watcher.getTopologyManagerInjector())
            .install();
}
 
Example #12
Source File: ConsulService.java    From thorntail with Apache License 2.0 5 votes vote down vote up
@Override
public void start(StartContext startContext) throws StartException {

    Consul.Builder builder = Consul.builder();

    builder.withUrl(this.url);

    try {
        this.consul = builder.build();
    } catch (Exception e) {
        throw new StartException("Failed to connect consul at " + url, e);
    }
}
 
Example #13
Source File: AgentActivator.java    From thorntail with Apache License 2.0 5 votes vote down vote up
@Override
public void activate(ServiceActivatorContext context) throws ServiceRegistryException {

    ServiceTarget target = context.getServiceTarget();

    ConsulService consul = new ConsulService(this.fraction.url());
    target.addService(ConsulService.SERVICE_NAME, consul)
            .install();

    HealthClientService healthClient = new HealthClientService();
    target.addService(HealthClientService.SERIVCE_NAME, healthClient)
            .addDependency(ConsulService.SERVICE_NAME, Consul.class, healthClient.getConsulInjector())
            .install();


    CatalogClientService catalogClient = new CatalogClientService();
    target.addService(CatalogClientService.SERVICE_NAME, catalogClient)
            .addDependency(ConsulService.SERVICE_NAME, Consul.class, catalogClient.getConsulInjector())
            .install();

    AgentClientService agentClient = new AgentClientService();
    target.addService(AgentClientService.SERVICE_NAME, agentClient)
            .addDependency(ConsulService.SERVICE_NAME, Consul.class, agentClient.getConsulInjector())
            .install();

    Advertiser advertiser = new Advertiser();
    advertiser.setCheckTTL(fraction.ttl());
    target.addService(Advertiser.SERVICE_NAME, advertiser)
            .addDependency(AgentClientService.SERVICE_NAME, AgentClient.class, advertiser.getAgentClientInjector())
            .install();

}
 
Example #14
Source File: DiscoveryAgentActor.java    From docker-nginx-consul with MIT License 5 votes vote down vote up
public DiscoveryAgentActor(AppConfiguration configuration){
  this.configuration = configuration;
  this.SCHEDULED_WORK_DELAY =  new FiniteDuration(configuration.serviceDiscoveryConfiguration.healthCheckTimeout, TimeUnit.SECONDS);

  // todo: terminate system if error occur while connecting to consul
  // get consul connection
  this.consul = Consul
      .builder()
      .withHostAndPort(
          HostAndPort.fromParts(
              configuration.serviceDiscoveryConfiguration.host,
              configuration.serviceDiscoveryConfiguration.port)
      )
      .build();

  // get agent
  agentClient = consul.agentClient();
  // set registration config
  Registration service = ImmutableRegistration.builder()
      .id(configuration.appId)
      .name(configuration.serviceName)
      .port(configuration.port)
      .address(configuration.host)
      .check(Registration.RegCheck.ttl(configuration.serviceDiscoveryConfiguration.healthCheckTimeout))
      .tags(Collections.singletonList("tag1"))
      .meta(Collections.singletonMap("version", "1.0"))
      .build();

  // register service
  agentClient.register(service);
  // check in with Consul, serviceId required only.  client will prepend "service:" for service level checks.
  // Note that you need to continually check in before the TTL expires, otherwise your service's state will be marked as "critical".
}
 
Example #15
Source File: ConsulConfigurationWatcherRegister.java    From skywalking with Apache License 2.0 5 votes vote down vote up
public ConsulConfigurationWatcherRegister(ConsulConfigurationCenterSettings settings) {
    super(settings.getPeriod());

    this.configItemKeyedByName = new ConcurrentHashMap<>();
    this.cachesByKey = new ConcurrentHashMap<>();

    List<HostAndPort> hostAndPorts = Splitter.on(",")
                                             .splitToList(settings.getHostAndPorts())
                                             .parallelStream()
                                             .map(hostAndPort -> HostAndPort.fromString(hostAndPort)
                                                                            .withDefaultPort(DEFAULT_PORT))
                                             .collect(Collectors.toList());

    Consul.Builder builder = Consul.builder().withConnectTimeoutMillis(3000);

    if (hostAndPorts.size() == 1) {
        builder.withHostAndPort(hostAndPorts.get(0));
    } else {
        builder.withMultipleHostAndPort(hostAndPorts, 5000);
    }

    if (StringUtils.isNotEmpty(settings.getAclToken())) {
        builder.withAclToken(settings.getAclToken());
    }

    consul = builder.build().keyValueClient();
}
 
Example #16
Source File: ClusterModuleConsulProvider.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Override
public void prepare() throws ServiceNotProvidedException, ModuleStartException {
    try {
        List<Address> addressList = ConnectUtils.parse(config.getHostPort());

        List<HostAndPort> hostAndPorts = new ArrayList<>();
        for (Address address : addressList) {
            hostAndPorts.add(HostAndPort.fromParts(address.getHost(), address.getPort()));
        }

        Consul.Builder consulBuilder = Consul.builder()
                                             //                    we should set this value or it will be blocked forever
                                             .withConnectTimeoutMillis(3000);

        if (StringUtils.isNotEmpty(config.getAclToken())) {
            consulBuilder.withAclToken(config.getAclToken());
        }

        if (hostAndPorts.size() > 1) {
            client = consulBuilder.withMultipleHostAndPort(hostAndPorts, 5000).build();
        } else {
            client = consulBuilder.withHostAndPort(hostAndPorts.get(0)).build();
        }
    } catch (ConnectStringParseException | ConsulException e) {
        throw new ModuleStartException(e.getMessage(), e);
    }

    ConsulCoordinator coordinator = new ConsulCoordinator(config, client);
    this.registerServiceImplementation(ClusterRegister.class, coordinator);
    this.registerServiceImplementation(ClusterNodesQuery.class, coordinator);
}
 
Example #17
Source File: RibbonJerseyClientBuilder.java    From dropwizard-consul with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor
 *
 * @param environment Dropwizard environment
 * @param consul Consul client
 * @param configuration Load balancer Configuration
 */
public RibbonJerseyClientBuilder(
    final Environment environment,
    final Consul consul,
    final RibbonJerseyClientConfiguration configuration) {
  this.environment = Objects.requireNonNull(environment);
  this.consul = Objects.requireNonNull(consul);
  this.configuration = Objects.requireNonNull(configuration);
}
 
Example #18
Source File: AbstractConsulService.java    From jim-framework with Apache License 2.0 5 votes vote down vote up
protected Consul buildConsul(String registryHost, int registryPort){
    return Consul.builder()
            .withConnectTimeoutMillis(20*1000)
            .withReadTimeoutMillis(20*1000)
            .withHostAndPort(HostAndPort.fromString(registryHost+":"+registryPort))
            .build()
            ;
}
 
Example #19
Source File: ConsulDiscoveryConfigSource.java    From pragmatic-microservices-lab with MIT License 5 votes vote down vote up
@Override
public String getValue(String propertyName) {
    if (propertyName.startsWith(CONFIG_DISCOVERY_SERVICE_PREFIX)) {
        Consul consul = ConsulClient.build();
        String[] serviceNameAndProp = propertyName.split("\\.");
        if (serviceNameAndProp.length == 4) {
            String serviceName = serviceNameAndProp[2];
            String serviceProp = serviceNameAndProp[3];
            if (serviceProp.equals("url")) {
                // propertyName is "discovery.service.NAME.url"
                // result is a url that doesn't end with / and optionally includes context root
                List<ServiceHealth> services = consul.healthClient()
                        .getHealthyServiceInstances(serviceName).getResponse();
                if (!services.isEmpty()) {
                    int randomIndex = new Random().nextInt(services.size());
                    Service selectedService = services.get(randomIndex).getService();
                    String contextRoot = selectedService.getMeta().getOrDefault(ConsulClient.KEY_CTX_ROOT, "");
                    if ( !contextRoot.isEmpty() && !contextRoot.startsWith("/")) {
                        contextRoot = "/" + contextRoot;
                    }
                    StringBuilder resultBuilder = new StringBuilder();
                    resultBuilder = resultBuilder.append("http://").append(selectedService.getAddress())
                            .append(":").append(selectedService.getPort())
                            .append(contextRoot);
                    return resultBuilder.toString();
                }
            }
        }
    }
    return null;
}
 
Example #20
Source File: HelloWorldApplication.java    From dropwizard-consul with Apache License 2.0 5 votes vote down vote up
@Override
public void run(HelloWorldConfiguration configuration, Environment environment) throws Exception {
  final Consul consul = configuration.getConsulFactory().build();
  final RibbonJerseyClient loadBalancingClient =
      new RibbonJerseyClientBuilder(environment, consul, configuration.getClient())
          .build("hello-world");

  final HelloWorldResource resource =
      new HelloWorldResource(
          consul,
          loadBalancingClient,
          configuration.getTemplate(),
          configuration.getDefaultName());
  environment.jersey().register(resource);
}
 
Example #21
Source File: ConsulClient.java    From pragmatic-microservices-lab with MIT License 5 votes vote down vote up
public static Consul build() {
    Consul.Builder consulBuilder = Consul.builder();
    ConfigProvider.getConfig()
            .getOptionalValue(CONFIG_CONSUL_URL, String.class)
            .ifPresent(url -> {
                consulBuilder.withUrl(url);
            });
    return consulBuilder.build();
}
 
Example #22
Source File: ITClusterModuleConsulProviderFunctionalTest.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Test
public void unregisterRemoteOfCluster() throws Exception {
    final String serviceName = "unregister_remote_cluster";
    ModuleProvider providerA = createProvider(serviceName);
    ModuleProvider providerB = createProvider(serviceName);

    Address addressA = new Address("127.0.0.6", 1006, true);
    Address addressB = new Address("127.0.0.7", 1007, true);

    RemoteInstance instanceA = new RemoteInstance(addressA);
    RemoteInstance instanceB = new RemoteInstance(addressB);

    getClusterRegister(providerA).registerRemote(instanceA);
    getClusterRegister(providerB).registerRemote(instanceB);

    List<RemoteInstance> remoteInstancesOfA = queryRemoteNodes(providerA, 2);
    validateServiceInstance(addressA, addressB, remoteInstancesOfA);

    List<RemoteInstance> remoteInstancesOfB = queryRemoteNodes(providerB, 2);
    validateServiceInstance(addressB, addressA, remoteInstancesOfB);

    // unregister A
    Consul client = Whitebox.getInternalState(providerA, "client");
    AgentClient agentClient = client.agentClient();
    agentClient.deregister(instanceA.getAddress().toString());

    // only B
    remoteInstancesOfB = queryRemoteNodes(providerB, 1, 120);
    assertEquals(1, remoteInstancesOfB.size());
    Address address = remoteInstancesOfB.get(0).getAddress();
    assertEquals(address, addressB);
    assertTrue(addressB.isSelf());
}
 
Example #23
Source File: HelloWorldResource.java    From dropwizard-consul with Apache License 2.0 5 votes vote down vote up
public HelloWorldResource(
    Consul consul, RibbonJerseyClient client, String template, String defaultName) {
  this.consul = consul;
  this.client = client;
  this.template = template;
  this.defaultName = defaultName;
  this.counter = new AtomicLong();
}
 
Example #24
Source File: CatalogClientService.java    From ARCHIVE-wildfly-swarm with Apache License 2.0 4 votes vote down vote up
public Injector<Consul> getConsulInjector() {
    return this.consulInjector;
}
 
Example #25
Source File: ConsulClientBuilder.java    From hazelcast-consul-discovery-spi with Apache License 2.0 4 votes vote down vote up
@Override
public Consul buildConsul(
		String consulHost,
		Integer consulPort,
		boolean consulSslEnabled,
		String	consulSslServerCertFilePath,
		String consulSslServerCertBase64,
		boolean consulServerHostnameVerify,
		String consulAclToken
		) throws Exception {
	
	
	try{
		Builder consulBuilder = Consul.builder();
		
		if (consulAclToken != null && !consulAclToken.trim().isEmpty()) {
			consulBuilder.withAclToken(consulAclToken);
		}
		
		//If SSL is enabled via xml configuration, then we use SSL context to build our client
		if (consulSslEnabled) {
			consulBuilder.withUrl("https://"+consulHost+":"+consulPort);
			
			if ( (consulSslServerCertFilePath != null && !consulSslServerCertFilePath.trim().isEmpty()) || 
					(consulSslServerCertBase64 != null && !consulSslServerCertBase64.trim().isEmpty()) ) {
				
				consulBuilder.withSslContext(getSSLContext(consulSslServerCertFilePath, consulSslServerCertBase64));
			}
			
			if (!consulServerHostnameVerify) {

				//We don't want verify host name, so we will mark host name as verified
				consulBuilder.withHostnameVerifier(new HostnameVerifier() {
		            public boolean verify(String s, SSLSession sslSession) {
		                return true;
		            }
		        });
			}
		} else {
			//Normal http without TLS
			consulBuilder.withHostAndPort(
					HostAndPort.fromParts(consulHost, consulPort));
		}
		
		Consul consul = consulBuilder.build();
		
		return consul;
	
	}catch(Exception e) {
		
		logger.severe("Unexpected Error occured while buildConsul() - " + e.getMessage(), e);
		throw(e);
	}
		
}
 
Example #26
Source File: ConsulIntegrationTest.java    From wildfly-camel with Apache License 2.0 4 votes vote down vote up
private Consul getConsul() {
    return Consul.builder().withUrl(consulUrl).build();
}
 
Example #27
Source File: ConsulService.java    From ARCHIVE-wildfly-swarm with Apache License 2.0 4 votes vote down vote up
@Override
public Consul getValue() throws IllegalStateException, IllegalArgumentException {
    return this.consul;
}
 
Example #28
Source File: ConsulServiceRegistryIT.java    From camel-spring-boot with Apache License 2.0 4 votes vote down vote up
@Test
public void testServiceRegistry() {
    final String consulUrl = String.format("http://%s:%d", container.getContainerIpAddress(), container.getMappedPort(Consul.DEFAULT_HTTP_PORT));

    new ApplicationContextRunner()
        .withUserConfiguration(TestConfiguration.class)
        .withPropertyValues(
            "debug=false",
            "spring.main.banner-mode=OFF",
            "spring.application.name=" + UUID.randomUUID().toString(),
            "camel.component.consul.service-registry.enabled=true",
            "camel.component.consul.service-registry.url=" + consulUrl,
            "camel.component.consul.service-registry.id=" + UUID.randomUUID().toString(),
            "camel.component.consul.service-registry.service-host=localhost")
        .run(
            context -> {
                assertThat(context).hasSingleBean(CamelContext.class);
                assertThat(context).hasSingleBean(ServiceRegistry.class);

                final CamelContext camelContext =  context.getBean(CamelContext.class);
                final ServiceRegistry serviceRegistry = camelContext.hasService(ServiceRegistry.class);

                assertThat(serviceRegistry).isNotNull();

                serviceRegistry.register(
                    DefaultServiceDefinition.builder()
                        .withHost(SERVICE_HOST)
                        .withPort(SERVICE_PORT)
                        .withName(SERVICE_NAME)
                        .withId(SERVICE_ID)
                        .build()
                );

                final Consul client = Consul.builder().withUrl(consulUrl).build();
                final List<CatalogService> services = client.catalogClient().getService(SERVICE_NAME).getResponse();

                assertThat(services).hasSize(1);
                assertThat(services).first().hasFieldOrPropertyWithValue("serviceId", SERVICE_ID);
                assertThat(services).first().hasFieldOrPropertyWithValue("serviceName", SERVICE_NAME);
                assertThat(services).first().hasFieldOrPropertyWithValue("serviceAddress", SERVICE_HOST);
                assertThat(services).first().hasFieldOrPropertyWithValue("servicePort", SERVICE_PORT);
            }
        );
}
 
Example #29
Source File: HealthClientService.java    From ARCHIVE-wildfly-swarm with Apache License 2.0 4 votes vote down vote up
public Injector<Consul> getConsulInjector() {
    return this.consulInjector;
}
 
Example #30
Source File: AgentClientService.java    From ARCHIVE-wildfly-swarm with Apache License 2.0 4 votes vote down vote up
public Injector<Consul> getConsulInjector() {
    return this.consulInjector;
}