com.orbitz.consul.model.ConsulResponse Java Examples

The following examples show how to use com.orbitz.consul.model.ConsulResponse. 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: 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 #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;
}
 
Example #4
Source File: ConsulTests.java    From nano-framework with Apache License 2.0 4 votes vote down vote up
@Test
public void blockingCallTest() throws InterruptedException {
    injects();
    keyValueClient.putValue(KEY, VALUE);
    final StringBuilder builder = new StringBuilder();
    final ConsulResponseCallback<Optional<Value>> callback = new ConsulResponseCallback<Optional<Value>>() {
        final AtomicReference<BigInteger> index = new AtomicReference<BigInteger>(null);

        @Override
        public void onComplete(final ConsulResponse<Optional<Value>> consulResponse) {
            if (consulResponse.getResponse().isPresent()) {
                final Value v = consulResponse.getResponse().get();
                builder.setLength(0);
                builder.append(v.getValueAsString().get());
            }

            index.set(consulResponse.getIndex());
            watch();
        }

        void watch() {
            keyValueClient.getValue(KEY, QueryOptions.blockMinutes(5, index.get()).build(), this);
        }

        @Override
        public void onFailure(final Throwable throwable) {
            LOGGER.error("Error encountered", throwable);
            watch();
        }
    };

    keyValueClient.getValue(KEY, QueryOptions.blockMinutes(5, new BigInteger("0")).build(), callback);

    Thread.sleep(1000);

    keyValueClient.putValue(KEY, NEW_VALUE);

    Thread.sleep(500);

    Assert.assertEquals(builder.toString(), NEW_VALUE);

    keyValueClient.deleteKey(KEY);
    final String delValue = keyValueClient.getValueAsString(KEY).or(DELETED);
    Assert.assertEquals(delValue, DELETED);
}
 
Example #5
Source File: ConsulCoordinatorTest.java    From skywalking with Apache License 2.0 3 votes vote down vote up
@Before
public void setUp() {

    consulConfig.setServiceName(SERVICE_NAME);

    coordinator = new ConsulCoordinator(consulConfig, consul);

    consulResponse = mock(ConsulResponse.class);

    HealthClient healthClient = mock(HealthClient.class);
    when(healthClient.getHealthyServiceInstances(anyString())).thenReturn(consulResponse);

    when(consul.healthClient()).thenReturn(healthClient);
    when(consul.agentClient()).thenReturn(agentClient);
}