com.orbitz.consul.model.catalog.CatalogService Java Examples

The following examples show how to use com.orbitz.consul.model.catalog.CatalogService. 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: 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 #2
Source File: ServiceNameStrategyBase.java    From docker-discovery-registrator-consul with Apache License 2.0 4 votes vote down vote up
protected Collection<ServiceInfo> _discover(CatalogClient catalogClient, 
                                            String serviceName, 
                                            Collection<Integer> ports,
                                            Collection<String> mustMatchTags) throws Exception {
    
    List<ServiceInfo> discoveredServices = new ArrayList<ServiceInfo>();
    
    ConsulResponse<List<CatalogService>> resp = catalogClient.getService(serviceName);
    List<CatalogService> serviceList = resp.getResponse();
    
    logger.trace("_discover() catalogClient.getService("+serviceName+") returned " + serviceList.size() + " results..");
    
    for (CatalogService srv : serviceList) {
    	
    	logger.trace("_discover() evaluating consul service: name:" + srv.getServiceName() + 
    				" serviceId:" + srv.getServiceId() + 
    				" servicePort:" + srv.getServicePort() +
    				" tags: " + Arrays.toString(srv.getServiceTags().toArray()));
        
        if (matchesTags(srv.getServiceTags(),mustMatchTags)) {
            
            try {
                // we parse mapped port from serviceId format "xx:yy:port"
                // registrator sets the serviceId = to this format above for each
                // unique port
                int mappedPort = Integer.valueOf(srv.getServiceId().split(":")[2]);

                // if we care about this mapped port... capture the service 
                if (ports.contains(mappedPort)) {
                    
                	InetAddress exposedAddress = null;
                	if (srv.getServiceAddress() != null) {
                		exposedAddress = InetAddress.getByName(srv.getServiceAddress());
                	} else {
                		// https://www.consul.io/docs/agent/http/catalog.html#ServiceAddress
                		logger.trace("_discover() CatalogService.serviceAddress is null... "
                				+ "falling back to address["+srv.getAddress()+"]");
                		exposedAddress = InetAddress.getByName(srv.getAddress());
                	}
                	
                    ServiceInfo info = new ServiceInfo(srv.getServiceName(),
                                                        srv.getServiceId(),
                                                        exposedAddress,
                                                        srv.getServicePort(),
                                                        mappedPort,
                                                        srv.getServiceTags());
                    discoveredServices.add(info);
                    
                    logger.debug("_discover() Discovered ServiceInfo: " + info);
                    
                } else {
                	logger.trace("_discover() serviceNameToFind=" + serviceName + 
                			", skipping consul service: " + srv.getServiceName() + 
                			" as its mappedPort[" + mappedPort + "] is not in list of "
                					+ "ports we care about: " + Arrays.toString(ports.toArray()) );;
                }
                
            } catch(Exception e) {
                throw new Exception("discover() Unexpected error processing "
                		+ "service: " + srv.getServiceName() + " " + e.getMessage(),e);
            }
            
        } else {
        	logger.trace("_discover() serviceNameToFind=" + serviceName + 
        			" skipping consul service: " + srv.getServiceName() + 
        			" with tags: " + (srv.getServiceTags() != null ? Arrays.toString(srv.getServiceTags().toArray()) : "[no tags]") + 
        			" as they don't contain mustMatchTags: " + Arrays.toString(mustMatchTags.toArray()));
        }
        
    }
    
    return discoveredServices;
}
 
Example #3
Source File: ConsulDiscoveryStrategy.java    From hazelcast-consul-discovery-spi with Apache License 2.0 4 votes vote down vote up
@Override
public Iterable<DiscoveryNode> discoverNodes() {
	
	List<DiscoveryNode> toReturn = new ArrayList<DiscoveryNode>();
	
	try {
		// discover healthy nodes only? (and its NOT the first invocation...)
		if (this.consulHealthyOnly && discoverNodesInvoked) {
			
			List<ServiceHealth> nodes = consulHealthClient.getHealthyServiceInstances(consulServiceName, ConsulUtility.getAclToken(this.consulAclToken)).getResponse();
			
			for (ServiceHealth node : nodes) {
				toReturn.add(new SimpleDiscoveryNode(
								new Address(node.getService().getAddress(),node.getService().getPort())));
				getLogger().info("Discovered healthy node: " + node.getService().getAddress()+":"+node.getService().getPort());
			}
			
		// discover all services, regardless of health or this is the first invocation
		} else {
			
			ConsulResponse<List<CatalogService>> response = this.consulCatalogClient.getService(consulServiceName, ConsulUtility.getAclToken(this.consulAclToken));
			
			for (CatalogService service : response.getResponse()) {
				
				String discoveredAddress = null;
				String rawServiceAddress = service.getServiceAddress();
				String rawAddress = service.getAddress();
				
				if (rawServiceAddress != null && !rawServiceAddress.trim().isEmpty()) {
				    discoveredAddress = rawServiceAddress;
					
				} else if (rawAddress != null && !rawAddress.trim().isEmpty()) {
				    getLogger().warning("discoverNodes() ServiceAddress was null/blank! " +
						     "for service: " + service.getServiceName() + 
						     " falling back to Address value");
				    discoveredAddress = rawAddress;
					
				} else {
				    getLogger().warning("discoverNodes() could not discover an address, " +
						     "both ServiceAddress and Address were null/blank! " +
						     "for service: " + service.getServiceName());
				}
				
				toReturn.add(new SimpleDiscoveryNode(
						new Address(discoveredAddress, service.getServicePort())));
				getLogger().info("Discovered healthy node: " + discoveredAddress+":"+service.getServicePort());
			}
		}
		
	} catch(Exception e) {
		getLogger().severe("discoverNodes() unexpected error: " + e.getMessage(),e);
	}

	// flag we were invoked
	discoverNodesInvoked = true;
	
	return toReturn;
}