Added checkstyle rules

This commit is contained in:
Marcin Grzejszczak
2019-02-07 15:03:44 +01:00
parent ddd9961120
commit 999fb6c9e8
157 changed files with 6633 additions and 3477 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2015 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -40,20 +40,35 @@ import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
/**
* @author Spencer Gibb
*/
public class ConsulCatalogWatch implements ApplicationEventPublisherAware, SmartLifecycle {
public class ConsulCatalogWatch
implements ApplicationEventPublisherAware, SmartLifecycle {
private static final Log log = LogFactory.getLog(ConsulDiscoveryClient.class);
private final ConsulDiscoveryProperties properties;
private final ConsulClient consul;
private final TaskScheduler taskScheduler;
private final AtomicReference<BigInteger> catalogServicesIndex = new AtomicReference<>();
private final AtomicBoolean running = new AtomicBoolean(false);
private ApplicationEventPublisher publisher;
private ScheduledFuture<?> watchFuture;
public ConsulCatalogWatch(ConsulDiscoveryProperties properties, ConsulClient consul) {
this(properties, consul, getTaskScheduler());
}
}
public ConsulCatalogWatch(ConsulDiscoveryProperties properties, ConsulClient consul,
TaskScheduler taskScheduler) {
this.properties = properties;
this.consul = consul;
this.taskScheduler = taskScheduler;
}
private static ThreadPoolTaskScheduler getTaskScheduler() {
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
@@ -61,12 +76,6 @@ public class ConsulCatalogWatch implements ApplicationEventPublisherAware, Smart
return taskScheduler;
}
public ConsulCatalogWatch(ConsulDiscoveryProperties properties, ConsulClient consul, TaskScheduler taskScheduler) {
this.properties = properties;
this.consul = consul;
this.taskScheduler = taskScheduler;
}
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher publisher) {
this.publisher = publisher;
@@ -86,7 +95,8 @@ public class ConsulCatalogWatch implements ApplicationEventPublisherAware, Smart
@Override
public void start() {
if (this.running.compareAndSet(false, true)) {
this.watchFuture = this.taskScheduler.scheduleWithFixedDelay(this::catalogServicesWatch,
this.watchFuture = this.taskScheduler.scheduleWithFixedDelay(
this::catalogServicesWatch,
this.properties.getCatalogServicesWatchDelay());
}
}
@@ -108,30 +118,32 @@ public class ConsulCatalogWatch implements ApplicationEventPublisherAware, Smart
return 0;
}
@Timed(value ="consul.watch-catalog-services")
@Timed("consul.watch-catalog-services")
public void catalogServicesWatch() {
try {
long index = -1;
if (catalogServicesIndex.get() != null) {
index = catalogServicesIndex.get().longValue();
if (this.catalogServicesIndex.get() != null) {
index = this.catalogServicesIndex.get().longValue();
}
Response<Map<String, List<String>>> response = consul
.getCatalogServices(new QueryParams(properties
.getCatalogServicesWatchTimeout(), index), properties.getAclToken());
Response<Map<String, List<String>>> response = this.consul.getCatalogServices(
new QueryParams(this.properties.getCatalogServicesWatchTimeout(),
index),
this.properties.getAclToken());
Long consulIndex = response.getConsulIndex();
if (consulIndex != null) {
catalogServicesIndex.set(BigInteger.valueOf(consulIndex));
this.catalogServicesIndex.set(BigInteger.valueOf(consulIndex));
}
if (log.isTraceEnabled()) {
log.trace("Received services update from consul: "+response.getValue()
+", index: "+ consulIndex);
log.trace("Received services update from consul: " + response.getValue()
+ ", index: " + consulIndex);
}
publisher.publishEvent(new HeartbeatEvent(this, consulIndex));
this.publisher.publishEvent(new HeartbeatEvent(this, consulIndex));
}
catch (Exception e) {
log.error("Error watching Consul CatalogServices", e);
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2018 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -44,16 +44,12 @@ public class ConsulDiscoveryClient implements DiscoveryClient {
private static final Log log = LogFactory.getLog(ConsulDiscoveryClient.class);
@Deprecated
public interface LocalResolver {
String getInstanceId();
Integer getPort();
}
private final ConsulClient client;
private final ConsulDiscoveryProperties properties;
public ConsulDiscoveryClient(ConsulClient client, ConsulDiscoveryProperties properties) {
public ConsulDiscoveryClient(ConsulClient client,
ConsulDiscoveryProperties properties) {
this.client = client;
this.properties = properties;
}
@@ -80,15 +76,15 @@ public class ConsulDiscoveryClient implements DiscoveryClient {
private void addInstancesToList(List<ServiceInstance> instances, String serviceId,
QueryParams queryParams) {
String aclToken = properties.getAclToken();
String aclToken = this.properties.getAclToken();
Response<List<HealthService>> services;
if (StringUtils.hasText(aclToken)) {
services = client.getHealthServices(serviceId,
services = this.client.getHealthServices(serviceId,
this.properties.getDefaultQueryTag(),
this.properties.isQueryPassing(), queryParams, aclToken);
}
else {
services = client.getHealthServices(serviceId,
services = this.client.getHealthServices(serviceId,
this.properties.getDefaultQueryTag(),
this.properties.isQueryPassing(), queryParams);
}
@@ -100,15 +96,15 @@ public class ConsulDiscoveryClient implements DiscoveryClient {
if (metadata.containsKey("secure")) {
secure = Boolean.parseBoolean(metadata.get("secure"));
}
instances.add(new DefaultServiceInstance(service.getService().getId(), serviceId, host, service
.getService().getPort(), secure, metadata));
instances.add(new DefaultServiceInstance(service.getService().getId(),
serviceId, host, service.getService().getPort(), secure, metadata));
}
}
public List<ServiceInstance> getAllInstances() {
List<ServiceInstance> instances = new ArrayList<>();
Response<Map<String, List<String>>> services = client
Response<Map<String, List<String>>> services = this.client
.getCatalogServices(QueryParams.DEFAULT);
for (String serviceId : services.getValue().keySet()) {
addInstancesToList(instances, serviceId, QueryParams.DEFAULT);
@@ -118,14 +114,16 @@ public class ConsulDiscoveryClient implements DiscoveryClient {
@Override
public List<String> getServices() {
String aclToken = properties.getAclToken();
String aclToken = this.properties.getAclToken();
if (StringUtils.hasText(aclToken)) {
return new ArrayList<>(client.getCatalogServices(QueryParams.DEFAULT, aclToken).getValue()
.keySet());
} else {
return new ArrayList<>(client.getCatalogServices(QueryParams.DEFAULT).getValue()
.keySet());
return new ArrayList<>(
this.client.getCatalogServices(QueryParams.DEFAULT, aclToken)
.getValue().keySet());
}
else {
return new ArrayList<>(this.client.getCatalogServices(QueryParams.DEFAULT)
.getValue().keySet());
}
}
@@ -133,4 +131,17 @@ public class ConsulDiscoveryClient implements DiscoveryClient {
public int getOrder() {
return this.properties.getOrder();
}
/**
* Depreacted local resolver.
*/
@Deprecated
public interface LocalResolver {
String getInstanceId();
Integer getPort();
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2018 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -45,6 +45,9 @@ import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
CommonsClientAutoConfiguration.class })
public class ConsulDiscoveryClientConfiguration {
/**
* Name of the catalog watch task scheduler bean.
*/
public static final String CATALOG_WATCH_TASK_SCHEDULER_NAME = "catalogWatchTaskScheduler";
@Autowired
@@ -53,29 +56,30 @@ public class ConsulDiscoveryClientConfiguration {
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty("spring.cloud.consul.discovery.heartbeat.enabled")
//TODO: move to service-registry for Edgware
// TODO: move to service-registry for Edgware
public TtlScheduler ttlScheduler(HeartbeatProperties heartbeatProperties) {
return new TtlScheduler(heartbeatProperties, consulClient);
return new TtlScheduler(heartbeatProperties, this.consulClient);
}
@Bean
@ConditionalOnMissingBean
//TODO: move to service-registry for Edgware
// TODO: move to service-registry for Edgware
public HeartbeatProperties heartbeatProperties() {
return new HeartbeatProperties();
}
@Bean
@ConditionalOnMissingBean
//TODO: Split appropriate values to service-registry for Edgware
// TODO: Split appropriate values to service-registry for Edgware
public ConsulDiscoveryProperties consulDiscoveryProperties(InetUtils inetUtils) {
return new ConsulDiscoveryProperties(inetUtils);
}
@Bean
@ConditionalOnMissingBean
public ConsulDiscoveryClient consulDiscoveryClient(ConsulDiscoveryProperties discoveryProperties) {
return new ConsulDiscoveryClient(consulClient, discoveryProperties);
public ConsulDiscoveryClient consulDiscoveryClient(
ConsulDiscoveryProperties discoveryProperties) {
return new ConsulDiscoveryClient(this.consulClient, discoveryProperties);
}
@Bean
@@ -84,7 +88,8 @@ public class ConsulDiscoveryClientConfiguration {
public ConsulCatalogWatch consulCatalogWatch(
ConsulDiscoveryProperties discoveryProperties,
@Qualifier(CATALOG_WATCH_TASK_SCHEDULER_NAME) TaskScheduler taskScheduler) {
return new ConsulCatalogWatch(discoveryProperties, consulClient, taskScheduler);
return new ConsulCatalogWatch(discoveryProperties, this.consulClient,
taskScheduler);
}
@Bean(name = CATALOG_WATCH_TASK_SCHEDULER_NAME)
@@ -92,4 +97,5 @@ public class ConsulDiscoveryClientConfiguration {
public TaskScheduler catalogWatchTaskScheduler() {
return new ThreadPoolTaskScheduler();
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2016 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,17 +16,17 @@
package org.springframework.cloud.consul.discovery;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.commons.util.InetUtils;
import org.springframework.cloud.commons.util.InetUtils.HostInfo;
import org.springframework.core.style.ToStringCreator;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Defines configuration for service discovery and registration.
*
@@ -45,22 +45,22 @@ public class ConsulDiscoveryProperties {
@Value("${consul.token:${CONSUL_TOKEN:${spring.cloud.consul.token:${SPRING_CLOUD_CONSUL_TOKEN:}}}}")
private String aclToken;
/** Tags to use when registering service */
/** Tags to use when registering service. */
private List<String> tags = new ArrayList<>();
/** Is service discovery enabled? */
private boolean enabled = true;
/** Tags to use when registering management service */
/** Tags to use when registering management service. */
private List<String> managementTags = new ArrayList<>();
/** Alternate server path to invoke for health checking */
/** Alternate server path to invoke for health checking. */
private String healthCheckPath = "/actuator/health";
/** Custom health check url to override default */
/** Custom health check url to override default. */
private String healthCheckUrl;
/** Headers to be applied to the Health Check calls */
/** Headers to be applied to the Health Check calls. */
private Map<String, List<String>> healthCheckHeaders = new HashMap<>();
/** How often to perform the health check (e.g. 10s), defaults to 10s. */
@@ -75,24 +75,26 @@ public class ConsulDiscoveryProperties {
*/
private String healthCheckCriticalTimeout;
/** IP address to use when accessing service (must also set preferIpAddress to use) */
/**
* IP address to use when accessing service (must also set preferIpAddress to use).
*/
private String ipAddress;
/** Hostname to use when accessing server */
/** Hostname to use when accessing server. */
private String hostname;
/** Port to register the service under (defaults to listening port) */
/** Port to register the service under (defaults to listening port). */
private Integer port;
/** Port to register the management service under (defaults to management port) */
/** Port to register the management service under (defaults to management port). */
private Integer managementPort;
private Lifecycle lifecycle = new Lifecycle();
/** Use ip address rather than hostname during registration */
/** Use ip address rather than hostname during registration. */
private boolean preferIpAddress = false;
/** Source of how we will determine the address to use */
/** Source of how we will determine the address to use. */
private boolean preferAgentAddress = false;
/** The delay between calls to watch consul catalog in millis, default is 1000. */
@@ -101,40 +103,39 @@ public class ConsulDiscoveryProperties {
/** The number of seconds to block while watching consul catalog, default is 2. */
private int catalogServicesWatchTimeout = 2;
/** Service name */
/** Service name. */
private String serviceName;
/** Unique service instance id */
/** Unique service instance id. */
private String instanceId;
/** Service instance zone */
/** Service instance zone. */
private String instanceZone;
/** Service instance group*/
/** Service instance group. */
private String instanceGroup;
/**
* Service instance zone comes from metadata.
* This allows changing the metadata tag name.
* Service instance zone comes from metadata. This allows changing the metadata tag
* name.
*/
private String defaultZoneMetadataName = "zone";
/** Whether to register an http or https service */
/** Whether to register an http or https service. */
private String scheme = "http";
/** Suffix to use when registering management service */
/** Suffix to use when registering management service. */
private String managementSuffix = MANAGEMENT;
/**
* Map of serviceId's -> tag to query for in server list.
* This allows filtering services by a single tag.
* Map of serviceId's -> tag to query for in server list. This allows filtering
* services by a single tag.
*/
private Map<String, String> serverListQueryTags = new HashMap<>();
/**
* Map of serviceId's -> datacenter to query for in server list.
* This allows looking up services in another datacenters.
* Map of serviceId's -> datacenter to query for in server list. This allows looking
* up services in another datacenters.
*/
private Map<String, String> datacenters = new HashMap<>();
@@ -142,8 +143,8 @@ public class ConsulDiscoveryProperties {
private String defaultQueryTag;
/**
* Add the 'passing` parameter to /v1/health/service/serviceName.
* This pushes health check passing to the server.
* Add the 'passing` parameter to /v1/health/service/serviceName. This pushes health
* check passing to the server.
*/
private boolean queryPassing = false;
@@ -157,19 +158,20 @@ public class ConsulDiscoveryProperties {
private boolean registerHealthCheck = true;
/**
* Throw exceptions during service registration if true, otherwise, log
* warnings (defaults to true).
* Throw exceptions during service registration if true, otherwise, log warnings
* (defaults to true).
*/
private boolean failFast = true;
/**
* Skips certificate verification during service checks if true, otherwise
* runs certificate verification.
* Skips certificate verification during service checks if true, otherwise runs
* certificate verification.
*/
private Boolean healthCheckTlsSkipVerify;
/**
* Order of the discovery client used by `CompositeDiscoveryClient` for sorting available clients.
* Order of the discovery client used by `CompositeDiscoveryClient` for sorting
* available clients.
*/
private int order = 0;
@@ -189,9 +191,9 @@ public class ConsulDiscoveryProperties {
* @param serviceId The service who's filtering tag is being looked up
* @return The tag the given service id should be filtered by, or null.
*/
public String getQueryTagForService(String serviceId){
String tag = serverListQueryTags.get(serviceId);
return tag != null ? tag : defaultQueryTag;
public String getQueryTagForService(String serviceId) {
String tag = this.serverListQueryTags.get(serviceId);
return tag != null ? tag : this.defaultQueryTag;
}
public String getHostname() {
@@ -203,13 +205,8 @@ public class ConsulDiscoveryProperties {
this.hostInfo.override = true;
}
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
this.hostInfo.override = true;
}
private HostInfo getHostInfo() {
return hostInfo;
return this.hostInfo;
}
private void setHostInfo(HostInfo hostInfo) {
@@ -217,7 +214,7 @@ public class ConsulDiscoveryProperties {
}
public String getAclToken() {
return aclToken;
return this.aclToken;
}
public void setAclToken(String aclToken) {
@@ -225,7 +222,7 @@ public class ConsulDiscoveryProperties {
}
public List<String> getTags() {
return tags;
return this.tags;
}
public void setTags(List<String> tags) {
@@ -233,7 +230,7 @@ public class ConsulDiscoveryProperties {
}
public boolean isEnabled() {
return enabled;
return this.enabled;
}
public void setEnabled(boolean enabled) {
@@ -241,7 +238,7 @@ public class ConsulDiscoveryProperties {
}
public List<String> getManagementTags() {
return managementTags;
return this.managementTags;
}
public void setManagementTags(List<String> managementTags) {
@@ -249,7 +246,7 @@ public class ConsulDiscoveryProperties {
}
public String getHealthCheckPath() {
return healthCheckPath;
return this.healthCheckPath;
}
public void setHealthCheckPath(String healthCheckPath) {
@@ -257,7 +254,7 @@ public class ConsulDiscoveryProperties {
}
public String getHealthCheckUrl() {
return healthCheckUrl;
return this.healthCheckUrl;
}
public void setHealthCheckUrl(String healthCheckUrl) {
@@ -265,7 +262,7 @@ public class ConsulDiscoveryProperties {
}
public Map<String, List<String>> getHealthCheckHeaders() {
return healthCheckHeaders;
return this.healthCheckHeaders;
}
public void setHealthCheckHeaders(Map<String, List<String>> healthCheckHeaders) {
@@ -273,7 +270,7 @@ public class ConsulDiscoveryProperties {
}
public String getHealthCheckInterval() {
return healthCheckInterval;
return this.healthCheckInterval;
}
public void setHealthCheckInterval(String healthCheckInterval) {
@@ -281,7 +278,7 @@ public class ConsulDiscoveryProperties {
}
public String getHealthCheckTimeout() {
return healthCheckTimeout;
return this.healthCheckTimeout;
}
public void setHealthCheckTimeout(String healthCheckTimeout) {
@@ -289,7 +286,7 @@ public class ConsulDiscoveryProperties {
}
public String getHealthCheckCriticalTimeout() {
return healthCheckCriticalTimeout;
return this.healthCheckCriticalTimeout;
}
public void setHealthCheckCriticalTimeout(String healthCheckCriticalTimeout) {
@@ -297,11 +294,16 @@ public class ConsulDiscoveryProperties {
}
public String getIpAddress() {
return ipAddress;
return this.ipAddress;
}
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
this.hostInfo.override = true;
}
public Integer getPort() {
return port;
return this.port;
}
public void setPort(Integer port) {
@@ -309,7 +311,7 @@ public class ConsulDiscoveryProperties {
}
public Integer getManagementPort() {
return managementPort;
return this.managementPort;
}
public void setManagementPort(Integer managementPort) {
@@ -317,7 +319,7 @@ public class ConsulDiscoveryProperties {
}
public Lifecycle getLifecycle() {
return lifecycle;
return this.lifecycle;
}
public void setLifecycle(Lifecycle lifecycle) {
@@ -325,7 +327,7 @@ public class ConsulDiscoveryProperties {
}
public boolean isPreferIpAddress() {
return preferIpAddress;
return this.preferIpAddress;
}
public void setPreferIpAddress(boolean preferIpAddress) {
@@ -333,7 +335,7 @@ public class ConsulDiscoveryProperties {
}
public boolean isPreferAgentAddress() {
return preferAgentAddress;
return this.preferAgentAddress;
}
public void setPreferAgentAddress(boolean preferAgentAddress) {
@@ -341,7 +343,7 @@ public class ConsulDiscoveryProperties {
}
public int getCatalogServicesWatchDelay() {
return catalogServicesWatchDelay;
return this.catalogServicesWatchDelay;
}
public void setCatalogServicesWatchDelay(int catalogServicesWatchDelay) {
@@ -349,7 +351,7 @@ public class ConsulDiscoveryProperties {
}
public int getCatalogServicesWatchTimeout() {
return catalogServicesWatchTimeout;
return this.catalogServicesWatchTimeout;
}
public void setCatalogServicesWatchTimeout(int catalogServicesWatchTimeout) {
@@ -357,7 +359,7 @@ public class ConsulDiscoveryProperties {
}
public String getServiceName() {
return serviceName;
return this.serviceName;
}
public void setServiceName(String serviceName) {
@@ -365,7 +367,7 @@ public class ConsulDiscoveryProperties {
}
public String getInstanceId() {
return instanceId;
return this.instanceId;
}
public void setInstanceId(String instanceId) {
@@ -373,7 +375,7 @@ public class ConsulDiscoveryProperties {
}
public String getInstanceZone() {
return instanceZone;
return this.instanceZone;
}
public void setInstanceZone(String instanceZone) {
@@ -381,7 +383,7 @@ public class ConsulDiscoveryProperties {
}
public String getInstanceGroup() {
return instanceGroup;
return this.instanceGroup;
}
public void setInstanceGroup(String instanceGroup) {
@@ -389,7 +391,7 @@ public class ConsulDiscoveryProperties {
}
public String getDefaultZoneMetadataName() {
return defaultZoneMetadataName;
return this.defaultZoneMetadataName;
}
public void setDefaultZoneMetadataName(String defaultZoneMetadataName) {
@@ -397,7 +399,7 @@ public class ConsulDiscoveryProperties {
}
public String getScheme() {
return scheme;
return this.scheme;
}
public void setScheme(String scheme) {
@@ -405,7 +407,7 @@ public class ConsulDiscoveryProperties {
}
public String getManagementSuffix() {
return managementSuffix;
return this.managementSuffix;
}
public void setManagementSuffix(String managementSuffix) {
@@ -413,7 +415,7 @@ public class ConsulDiscoveryProperties {
}
public Map<String, String> getServerListQueryTags() {
return serverListQueryTags;
return this.serverListQueryTags;
}
public void setServerListQueryTags(Map<String, String> serverListQueryTags) {
@@ -421,7 +423,7 @@ public class ConsulDiscoveryProperties {
}
public Map<String, String> getDatacenters() {
return datacenters;
return this.datacenters;
}
public void setDatacenters(Map<String, String> datacenters) {
@@ -429,7 +431,7 @@ public class ConsulDiscoveryProperties {
}
public String getDefaultQueryTag() {
return defaultQueryTag;
return this.defaultQueryTag;
}
public void setDefaultQueryTag(String defaultQueryTag) {
@@ -437,7 +439,7 @@ public class ConsulDiscoveryProperties {
}
public boolean isQueryPassing() {
return queryPassing;
return this.queryPassing;
}
public void setQueryPassing(boolean queryPassing) {
@@ -445,7 +447,7 @@ public class ConsulDiscoveryProperties {
}
public boolean isRegister() {
return register;
return this.register;
}
public void setRegister(boolean register) {
@@ -453,7 +455,7 @@ public class ConsulDiscoveryProperties {
}
public boolean isDeregister() {
return deregister;
return this.deregister;
}
public void setDeregister(boolean deregister) {
@@ -461,7 +463,7 @@ public class ConsulDiscoveryProperties {
}
public boolean isRegisterHealthCheck() {
return registerHealthCheck;
return this.registerHealthCheck;
}
public void setRegisterHealthCheck(boolean registerHealthCheck) {
@@ -469,7 +471,7 @@ public class ConsulDiscoveryProperties {
}
public boolean isFailFast() {
return failFast;
return this.failFast;
}
public void setFailFast(boolean failFast) {
@@ -477,7 +479,7 @@ public class ConsulDiscoveryProperties {
}
public Boolean getHealthCheckTlsSkipVerify() {
return healthCheckTlsSkipVerify;
return this.healthCheckTlsSkipVerify;
}
public void setHealthCheckTlsSkipVerify(Boolean healthCheckTlsSkipVerify) {
@@ -485,7 +487,7 @@ public class ConsulDiscoveryProperties {
}
public int getOrder() {
return order;
return this.order;
}
public void setOrder(int order) {
@@ -494,52 +496,50 @@ public class ConsulDiscoveryProperties {
@Override
public String toString() {
return new ToStringCreator(this)
.append("hostInfo", hostInfo)
.append("aclToken", aclToken)
.append("tags", tags)
.append("enabled", enabled)
.append("managementTags", managementTags)
.append("healthCheckPath", healthCheckPath)
.append("healthCheckUrl", healthCheckUrl)
.append("healthCheckHeaders", healthCheckHeaders)
.append("healthCheckInterval", healthCheckInterval)
.append("healthCheckTimeout", healthCheckTimeout)
.append("healthCheckCriticalTimeout", healthCheckCriticalTimeout)
.append("ipAddress", ipAddress)
.append("hostname", hostname)
.append("port", port)
.append("managementPort", managementPort)
.append("lifecycle", lifecycle)
.append("preferIpAddress", preferIpAddress)
.append("preferAgentAddress", preferAgentAddress)
.append("catalogServicesWatchDelay", catalogServicesWatchDelay)
.append("catalogServicesWatchTimeout", catalogServicesWatchTimeout)
.append("serviceName", serviceName)
.append("instanceId", instanceId)
.append("instanceZone", instanceZone)
.append("instanceGroup", instanceGroup)
.append("defaultZoneMetadataName", defaultZoneMetadataName)
.append("scheme", scheme)
.append("managementSuffix", managementSuffix)
.append("serverListQueryTags", serverListQueryTags)
.append("datacenters", datacenters)
.append("defaultQueryTag", defaultQueryTag)
.append("queryPassing", queryPassing)
.append("register", register)
.append("deregister", deregister)
.append("registerHealthCheck", registerHealthCheck)
.append("failFast", failFast)
.append("healthCheckTlsSkipVerify", healthCheckTlsSkipVerify)
.append("order", order)
.toString();
return new ToStringCreator(this).append("hostInfo", this.hostInfo)
.append("aclToken", this.aclToken).append("tags", this.tags)
.append("enabled", this.enabled)
.append("managementTags", this.managementTags)
.append("healthCheckPath", this.healthCheckPath)
.append("healthCheckUrl", this.healthCheckUrl)
.append("healthCheckHeaders", this.healthCheckHeaders)
.append("healthCheckInterval", this.healthCheckInterval)
.append("healthCheckTimeout", this.healthCheckTimeout)
.append("healthCheckCriticalTimeout", this.healthCheckCriticalTimeout)
.append("ipAddress", this.ipAddress).append("hostname", this.hostname)
.append("port", this.port).append("managementPort", this.managementPort)
.append("lifecycle", this.lifecycle)
.append("preferIpAddress", this.preferIpAddress)
.append("preferAgentAddress", this.preferAgentAddress)
.append("catalogServicesWatchDelay", this.catalogServicesWatchDelay)
.append("catalogServicesWatchTimeout", this.catalogServicesWatchTimeout)
.append("serviceName", this.serviceName)
.append("instanceId", this.instanceId)
.append("instanceZone", this.instanceZone)
.append("instanceGroup", this.instanceGroup)
.append("defaultZoneMetadataName", this.defaultZoneMetadataName)
.append("scheme", this.scheme)
.append("managementSuffix", this.managementSuffix)
.append("serverListQueryTags", this.serverListQueryTags)
.append("datacenters", this.datacenters)
.append("defaultQueryTag", this.defaultQueryTag)
.append("queryPassing", this.queryPassing)
.append("register", this.register).append("deregister", this.deregister)
.append("registerHealthCheck", this.registerHealthCheck)
.append("failFast", this.failFast)
.append("healthCheckTlsSkipVerify", this.healthCheckTlsSkipVerify)
.append("order", this.order).toString();
}
/**
* Properties releated to the lifecycle.
*/
public static class Lifecycle {
private boolean enabled = true;
public boolean isEnabled() {
return enabled;
return this.enabled;
}
public void setEnabled(boolean enabled) {
@@ -548,9 +548,9 @@ public class ConsulDiscoveryProperties {
@Override
public String toString() {
return "Lifecycle{" +
"enabled=" + enabled +
'}';
return "Lifecycle{" + "enabled=" + this.enabled + '}';
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2016 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,11 +20,13 @@ import com.netflix.loadbalancer.IPing;
import com.netflix.loadbalancer.Server;
/**
* "Ping" Consul
* i.e. we dont do a real "ping". We just assume that the server is up if Consul says so
* "Ping" Consul i.e. we dont do a real "ping". We just assume that the server is up if
* Consul says so
*
* @author Spencer Gibb
*/
public class ConsulPing implements IPing {
@Override
public boolean isAlive(Server server) {
boolean isAlive = true;
@@ -36,4 +38,5 @@ public class ConsulPing implements IPing {
return isAlive;
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2015 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -47,16 +47,17 @@ import static com.netflix.client.config.CommonClientConfigKey.EnableZoneAffinity
*/
@Configuration
public class ConsulRibbonClientConfiguration {
protected static final String VALUE_NOT_SET = "__not__set__";
protected static final String DEFAULT_NAMESPACE = "ribbon";
@Autowired
private ConsulClient client;
@Value("${ribbon.client.name}")
private String serviceId = "client";
protected static final String VALUE_NOT_SET = "__not__set__";
protected static final String DEFAULT_NAMESPACE = "ribbon";
public ConsulRibbonClientConfiguration() {
}
@@ -66,8 +67,9 @@ public class ConsulRibbonClientConfiguration {
@Bean
@ConditionalOnMissingBean
public ServerList<?> ribbonServerList(IClientConfig config, ConsulDiscoveryProperties properties) {
ConsulServerList serverList = new ConsulServerList(client, properties);
public ServerList<?> ribbonServerList(IClientConfig config,
ConsulDiscoveryProperties properties) {
ConsulServerList serverList = new ConsulServerList(this.client, properties);
serverList.initWithNiwsConfig(config);
return serverList;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2015 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -30,17 +30,19 @@ import static org.springframework.cloud.consul.discovery.ConsulServerUtils.findH
public class ConsulServer extends Server {
private final MetaInfo metaInfo;
private final HealthService service;
private final Map<String, String> metadata;
public ConsulServer(final HealthService healthService) {
super(findHost(healthService), healthService.getService().getPort());
this.service = healthService;
this.metadata = ConsulServerUtils.getMetadata(this.service);
metaInfo = new MetaInfo() {
this.metaInfo = new MetaInfo() {
@Override
public String getAppName() {
return service.getService().getService();
return ConsulServer.this.service.getService().getService();
}
@Override
@@ -55,7 +57,7 @@ public class ConsulServer extends Server {
@Override
public String getInstanceId() {
return service.getService().getId();
return ConsulServer.this.service.getService().getId();
}
};
@@ -64,7 +66,7 @@ public class ConsulServer extends Server {
@Override
public MetaInfo getMetaInfo() {
return metaInfo;
return this.metaInfo;
}
public HealthService getHealthService() {
@@ -72,7 +74,7 @@ public class ConsulServer extends Server {
}
public Map<String, String> getMetadata() {
return metadata;
return this.metadata;
}
public boolean isPassingChecks() {
@@ -83,4 +85,5 @@ public class ConsulServer extends Server {
}
return true;
}
}

View File

@@ -1,10 +1,30 @@
package org.springframework.cloud.consul.discovery;
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import com.netflix.loadbalancer.Server;
import org.springframework.cloud.netflix.ribbon.DefaultServerIntrospector;
package org.springframework.cloud.consul.discovery;
import java.util.Map;
import com.netflix.loadbalancer.Server;
import org.springframework.cloud.netflix.ribbon.DefaultServerIntrospector;
/**
* @author Spencer Gibb
*/
public class ConsulServerIntrospector extends DefaultServerIntrospector {
@Override
@@ -24,4 +44,5 @@ public class ConsulServerIntrospector extends DefaultServerIntrospector {
}
return super.getMetadata(server);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2015 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -34,6 +34,7 @@ import com.netflix.loadbalancer.AbstractServerList;
public class ConsulServerList extends AbstractServerList<ConsulServer> {
private final ConsulClient client;
private final ConsulDiscoveryProperties properties;
private String serviceId;
@@ -44,15 +45,15 @@ public class ConsulServerList extends AbstractServerList<ConsulServer> {
}
protected ConsulClient getClient() {
return client;
return this.client;
}
protected ConsulDiscoveryProperties getProperties() {
return properties;
return this.properties;
}
protected String getServiceId() {
return serviceId;
return this.serviceId;
}
@Override
@@ -86,8 +87,8 @@ public class ConsulServerList extends AbstractServerList<ConsulServer> {
/**
* Transforms the response from Consul in to a list of usable {@link ConsulServer}s.
*
* @param healthServices the initial list of servers from Consul. Guaranteed to be non-empty list
* @param healthServices the initial list of servers from Consul. Guaranteed to be
* non-empty list
* @return ConsulServer instances
* @see ConsulServer#ConsulServer(HealthService)
*/
@@ -95,8 +96,10 @@ public class ConsulServerList extends AbstractServerList<ConsulServer> {
List<ConsulServer> servers = new ArrayList<>();
for (HealthService service : healthServices) {
ConsulServer server = new ConsulServer(service);
if (server.getMetadata().containsKey(this.properties.getDefaultZoneMetadataName())) {
server.setZone(server.getMetadata().get(this.properties.getDefaultZoneMetadataName()));
if (server.getMetadata()
.containsKey(this.properties.getDefaultZoneMetadataName())) {
server.setZone(server.getMetadata()
.get(this.properties.getDefaultZoneMetadataName()));
}
servers.add(server);
}
@@ -104,9 +107,9 @@ public class ConsulServerList extends AbstractServerList<ConsulServer> {
}
/**
* This method will create the {@link QueryParams} to use when retrieving the
* services from Consul. By default {@link QueryParams#DEFAULT} is used. In case
* a datacenter is specified for the current serviceId {@link QueryParams#datacenter} is set.
* This method will create the {@link QueryParams} to use when retrieving the services
* from Consul. By default {@link QueryParams#DEFAULT} is used. In case a datacenter
* is specified for the current serviceId {@link QueryParams#datacenter} is set.
* @return an instance of {@link QueryParams}
*/
protected QueryParams createQueryParamsForClientRequest() {
@@ -128,9 +131,10 @@ public class ConsulServerList extends AbstractServerList<ConsulServer> {
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("ConsulServerList{");
sb.append("serviceId='").append(serviceId).append('\'');
sb.append("serviceId='").append(this.serviceId).append('\'');
sb.append(", tag=").append(getTag());
sb.append('}');
return sb.toString();
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2015 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -34,17 +34,22 @@ import org.springframework.util.StringUtils;
* @author Spencer Gibb
* @author Semenkov Alexey
*/
public class ConsulServerUtils {
public final class ConsulServerUtils {
private static final Log log = LogFactory.getLog(ConsulServerUtils.class);
private ConsulServerUtils() {
throw new IllegalStateException("Can't instantiate a utility class");
}
public static String findHost(HealthService healthService) {
HealthService.Service service = healthService.getService();
HealthService.Node node = healthService.getNode();
if (StringUtils.hasText(service.getAddress())) {
return fixIPv6Address(service.getAddress());
} else if (StringUtils.hasText(node.getAddress())) {
}
else if (StringUtils.hasText(node.getAddress())) {
return fixIPv6Address(node.getAddress());
}
return node.getNode();
@@ -57,13 +62,13 @@ public class ConsulServerUtils {
return "[" + inetAdr.getHostName() + "]";
}
return address;
} catch (UnknownHostException e) {
}
catch (UnknownHostException e) {
log.debug("Not InetAddress: " + address + " , resolved as is.");
return address;
}
}
public static Map<String, String> getMetadata(HealthService healthService) {
return getMetadata(healthService.getService().getTags());
}
@@ -74,18 +79,18 @@ public class ConsulServerUtils {
for (String tag : tags) {
String[] parts = StringUtils.delimitedListToStringArray(tag, "=");
switch (parts.length) {
case 0:
break;
case 1:
metadata.put(parts[0], parts[0]);
break;
case 2:
metadata.put(parts[0], parts[1]);
break;
default:
String[] end = Arrays.copyOfRange(parts, 1, parts.length);
metadata.put(parts[0], StringUtils.arrayToDelimitedString(end, "="));
break;
case 0:
break;
case 1:
metadata.put(parts[0], parts[0]);
break;
case 2:
metadata.put(parts[0], parts[1]);
break;
default:
String[] end = Arrays.copyOfRange(parts, 1, parts.length);
metadata.put(parts[0], StringUtils.arrayToDelimitedString(end, "="));
break;
}
}
@@ -93,4 +98,5 @@ public class ConsulServerUtils {
return metadata;
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2016 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -25,10 +25,13 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* ServerList implementation that filters ConsulServers based on if all their Health Checks are PASSING.
* ServerList implementation that filters ConsulServers based on if all their Health
* Checks are PASSING.
*
* @author Spencer Gibb
*/
public class HealthServiceServerListFilter implements ServerListFilter<Server> {
private static final Log log = LogFactory.getLog(HealthServiceServerListFilter.class);
@Override
@@ -43,9 +46,11 @@ public class HealthServiceServerListFilter implements ServerListFilter<Server> {
filtered.add(server);
}
} else {
if (log.isDebugEnabled()) {
log.debug("Unable to determine aliveness of server type " + server.getClass() + ", " + server);
}
else {
if (log.isDebugEnabled()) {
log.debug("Unable to determine aliveness of server type "
+ server.getClass() + ", " + server);
}
filtered.add(server);
}
@@ -53,4 +58,5 @@ public class HealthServiceServerListFilter implements ServerListFilter<Server> {
return filtered;
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2015 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -28,11 +28,18 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.core.style.ToStringCreator;
import org.springframework.validation.annotation.Validated;
/**
* Properties related to hearbeat verification.
*
* @author Spencer Gibb
*/
@ConfigurationProperties(prefix = "spring.cloud.consul.discovery.heartbeat")
@Validated
public class HeartbeatProperties {
private static final Log log = org.apache.commons.logging.LogFactory.getLog(HeartbeatProperties.class);
private static final Log log = org.apache.commons.logging.LogFactory
.getLog(HeartbeatProperties.class);
// TODO: change enabled to default to true when I stop seeing messages like
// [WARN] agent: Check 'service:testConsulApp:xtest:8080' missed TTL, is now critical
boolean enabled = false;
@@ -47,63 +54,62 @@ public class HeartbeatProperties {
@DecimalMax("0.9")
private double intervalRatio = 2.0 / 3.0;
//TODO: did heartbeatInterval need to be a field?
// TODO: did heartbeatInterval need to be a field?
protected Period computeHearbeatInterval() {
// heartbeat rate at ratio * ttl, but no later than ttl -1s and, (under lesser
// priority), no sooner than 1s from now
double interval = ttlValue * intervalRatio;
double max = Math.max(interval, 1);
int ttlMinus1 = ttlValue - 1;
double min = Math.min(ttlMinus1, max);
protected Period computeHearbeatInterval() {
// heartbeat rate at ratio * ttl, but no later than ttl -1s and, (under lesser
// priority), no sooner than 1s from now
double interval = this.ttlValue * this.intervalRatio;
double max = Math.max(interval, 1);
int ttlMinus1 = this.ttlValue - 1;
double min = Math.min(ttlMinus1, max);
Period heartbeatInterval = new Period(Math.round(1000 * min));
log.debug("Computed heartbeatInterval: " + heartbeatInterval);
return heartbeatInterval;
}
}
public String getTtl() {
return ttlValue + ttlUnit;
public String getTtl() {
return this.ttlValue + this.ttlUnit;
}
public boolean isEnabled() {
return this.enabled;
}
public @Min(1) int getTtlValue() {
return this.ttlValue;
}
public @NotNull String getTtlUnit() {
return this.ttlUnit;
}
public @DecimalMin("0.1") @DecimalMax("0.9") double getIntervalRatio() {
return this.intervalRatio;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public @Min(1) int getTtlValue() {
return this.ttlValue;
}
public void setTtlValue(@Min(1) int ttlValue) {
this.ttlValue = ttlValue;
}
public @NotNull String getTtlUnit() {
return this.ttlUnit;
}
public void setTtlUnit(@NotNull String ttlUnit) {
this.ttlUnit = ttlUnit;
}
public void setIntervalRatio(@DecimalMin("0.1") @DecimalMax("0.9") double intervalRatio) {
public @DecimalMin("0.1") @DecimalMax("0.9") double getIntervalRatio() {
return this.intervalRatio;
}
public void setIntervalRatio(
@DecimalMin("0.1") @DecimalMax("0.9") double intervalRatio) {
this.intervalRatio = intervalRatio;
}
@Override
public String toString() {
return new ToStringCreator(this)
.append("enabled", enabled)
.append("ttlValue", ttlValue)
.append("ttlUnit", ttlUnit)
.append("intervalRatio", intervalRatio)
.toString();
return new ToStringCreator(this).append("enabled", this.enabled)
.append("ttlValue", this.ttlValue).append("ttlUnit", this.ttlUnit)
.append("intervalRatio", this.intervalRatio).toString();
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2014 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2015 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -31,9 +31,11 @@ import org.springframework.scheduling.concurrent.ConcurrentTaskScheduler;
/**
* Created by nicu on 11.03.2015.
*
* @author Stéphane LEROY
*/
public class TtlScheduler {
private static final Log log = LogFactory.getLog(ConsulDiscoveryClient.class);
private final Map<String, ScheduledFuture> serviceHeartbeats = new ConcurrentHashMap<>();
@@ -57,41 +59,45 @@ public class TtlScheduler {
/**
* Add a service to the checks loop.
* @param instanceId instance id
*/
public void add(String instanceId) {
ScheduledFuture task = scheduler.scheduleAtFixedRate(new ConsulHeartbeatTask(
instanceId), configuration.computeHearbeatInterval()
.toStandardDuration().getMillis());
ScheduledFuture previousTask = serviceHeartbeats.put(instanceId, task);
ScheduledFuture task = this.scheduler.scheduleAtFixedRate(
new ConsulHeartbeatTask(instanceId), this.configuration
.computeHearbeatInterval().toStandardDuration().getMillis());
ScheduledFuture previousTask = this.serviceHeartbeats.put(instanceId, task);
if (previousTask != null) {
previousTask.cancel(true);
}
}
public void remove(String instanceId) {
ScheduledFuture task = serviceHeartbeats.get(instanceId);
ScheduledFuture task = this.serviceHeartbeats.get(instanceId);
if (task != null) {
task.cancel(true);
}
serviceHeartbeats.remove(instanceId);
this.serviceHeartbeats.remove(instanceId);
}
private class ConsulHeartbeatTask implements Runnable {
private String checkId;
ConsulHeartbeatTask(String serviceId) {
this.checkId = serviceId;
if (!checkId.startsWith("service:")) {
checkId = "service:" + checkId;
if (!this.checkId.startsWith("service:")) {
this.checkId = "service:" + this.checkId;
}
}
@Override
public void run() {
client.agentCheckPass(checkId);
TtlScheduler.this.client.agentCheckPass(this.checkId);
if (log.isDebugEnabled()) {
log.debug("Sending consul heartbeat for: " + checkId);
log.debug("Sending consul heartbeat for: " + this.checkId);
}
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2016 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,6 +18,8 @@ package org.springframework.cloud.consul.discovery.configclient;
import javax.annotation.PostConstruct;
import com.ecwid.consul.v1.ConsulClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
@@ -26,8 +28,6 @@ import org.springframework.cloud.consul.discovery.ConsulDiscoveryProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import com.ecwid.consul.v1.ConsulClient;
/**
* Extra configuration for config server if it happens to be registered with Consul.
*
@@ -52,7 +52,7 @@ public class ConsulConfigServerAutoConfiguration {
}
String prefix = this.server.getPrefix();
if (StringUtils.hasText(prefix)) {
this.properties.getTags().add("configPath="+prefix);
this.properties.getTags().add("configPath=" + prefix);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2018 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -32,7 +32,8 @@ import org.springframework.context.annotation.Configuration;
@ConditionalOnClass(ConfigServicePropertySourceLocator.class)
@ConditionalOnProperty(value = "spring.cloud.config.discovery.enabled", matchIfMissing = false)
@Configuration
@ImportAutoConfiguration({ ConsulAutoConfiguration.class, ConsulDiscoveryClientConfiguration.class})
@ImportAutoConfiguration({ ConsulAutoConfiguration.class,
ConsulDiscoveryClientConfiguration.class })
public class ConsulDiscoveryClientConfigServiceBootstrapConfiguration {
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2015 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,21 +20,23 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.springframework.cloud.consul.discovery.ConsulServer;
import com.netflix.loadbalancer.Server;
import com.netflix.loadbalancer.ServerListFilter;
import org.springframework.cloud.consul.discovery.ConsulServer;
/**
* Server filter: returns only alive servers. Each consul agent runs a serf agent which is
* a member of the serf gossip pool. The serf status (alive/failed/etc) is reflected in 2
* consul APIs: in the agent API and in the catalog API. We prefer the agent API because
* it is most up to date (or perhaps we should intersect them and pick members that are
* live in both).
*
* @author nicu marasoiu on 10.03.2015.
*/
@Deprecated
public class AliveServerListFilter implements ServerListFilter<Server> {
private FilteringAgentClient filteringAgentClient;
public AliveServerListFilter(FilteringAgentClient filteringAgentClient) {
@@ -43,14 +45,16 @@ public class AliveServerListFilter implements ServerListFilter<Server> {
@Override
public List<Server> getFilteredListOfServers(List<Server> servers) {
Set<String> liveNodes = filteringAgentClient.getAliveAgentsAddresses();
Set<String> liveNodes = this.filteringAgentClient.getAliveAgentsAddresses();
List<Server> filteredServers = new ArrayList<>();
for (Server server : servers) {
ConsulServer consulServer = ConsulServer.class.cast(server);
if (liveNodes.contains(consulServer.getHealthService().getService().getAddress())) {
if (liveNodes.contains(
consulServer.getHealthService().getService().getAddress())) {
filteredServers.add(server);
}
}
return filteredServers;
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2015 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,11 +21,14 @@ import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.springframework.cloud.consul.model.SerfStatusEnum;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.agent.model.Member;
import org.springframework.cloud.consul.model.SerfStatusEnum;
/**
* @author Nicu Marasoiu
*/
@Deprecated
public class FilteringAgentClient {
@@ -38,7 +41,7 @@ public class FilteringAgentClient {
}
public List<Member> getAliveAgents() {
List<Member> members = client.getAgentMembers().getValue();
List<Member> members = this.client.getAgentMembers().getValue();
List<Member> liveMembers = new ArrayList<>(members.size());
for (Member peer : members) {
if (peer.getStatus() == ALIVE_STATUS) {
@@ -55,4 +58,5 @@ public class FilteringAgentClient {
}
return addresses;
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2015 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -27,6 +27,8 @@ import com.netflix.loadbalancer.ServerListFilter;
/**
* Created by nicu on 12.03.2015.
*
* @author Nicu Marasoiu
*/
@Deprecated
public class ServiceCheckServerListFilter implements ServerListFilter<Server> {
@@ -44,9 +46,9 @@ public class ServiceCheckServerListFilter implements ServerListFilter<Server> {
for (Server server : servers) {
String appName = server.getMetaInfo().getAppName();
String instanceId = server.getMetaInfo().getInstanceId();
//TODO: cache getHealthChecks? this is hit often
List<Check> serviceChecks = client.getHealthChecksForService(appName,
QueryParams.DEFAULT).getValue();
// TODO: cache getHealthChecks? this is hit often
List<Check> serviceChecks = this.client
.getHealthChecksForService(appName, QueryParams.DEFAULT).getValue();
boolean serviceOk = true;
for (Check check : serviceChecks) {
if (check.getServiceId().equals(instanceId)

View File

@@ -20,6 +20,8 @@ import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import com.ecwid.consul.v1.agent.model.NewService;
import org.springframework.cloud.client.discovery.ManagementServerPortUtils;
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationProperties;
import org.springframework.cloud.client.serviceregistry.ServiceRegistry;
@@ -31,29 +33,38 @@ import org.springframework.core.env.Environment;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import com.ecwid.consul.v1.agent.model.NewService;
/**
* @author Spencer Gibb
*/
public class ConsulAutoRegistration extends ConsulRegistration {
/**
* Instance ID separator.
*/
public static final char SEPARATOR = '-';
private final AutoServiceRegistrationProperties autoServiceRegistrationProperties;
private final ApplicationContext context;
private final HeartbeatProperties heartbeatProperties;
private final List<ConsulManagementRegistrationCustomizer> managementRegistrationCustomizers;
@Deprecated
public ConsulAutoRegistration(NewService service, AutoServiceRegistrationProperties autoServiceRegistrationProperties,
ConsulDiscoveryProperties properties, ApplicationContext context, HeartbeatProperties heartbeatProperties) {
this(service, autoServiceRegistrationProperties, properties, context, heartbeatProperties, Collections.emptyList());
public ConsulAutoRegistration(NewService service,
AutoServiceRegistrationProperties autoServiceRegistrationProperties,
ConsulDiscoveryProperties properties, ApplicationContext context,
HeartbeatProperties heartbeatProperties) {
this(service, autoServiceRegistrationProperties, properties, context,
heartbeatProperties, Collections.emptyList());
}
public ConsulAutoRegistration(NewService service, AutoServiceRegistrationProperties autoServiceRegistrationProperties,
ConsulDiscoveryProperties properties, ApplicationContext context, HeartbeatProperties heartbeatProperties,
List<ConsulManagementRegistrationCustomizer> managementRegistrationCustomizers) {
public ConsulAutoRegistration(NewService service,
AutoServiceRegistrationProperties autoServiceRegistrationProperties,
ConsulDiscoveryProperties properties, ApplicationContext context,
HeartbeatProperties heartbeatProperties,
List<ConsulManagementRegistrationCustomizer> managementRegistrationCustomizers) {
super(service, properties);
this.autoServiceRegistrationProperties = autoServiceRegistrationProperties;
this.context = context;
@@ -61,24 +72,8 @@ public class ConsulAutoRegistration extends ConsulRegistration {
this.managementRegistrationCustomizers = managementRegistrationCustomizers;
}
public void initializePort(int knownPort) {
if (getService().getPort() == null) {
// not set by properties
getService().setPort(knownPort);
}
// we might not have a port until now, so this is the earliest we
// can create a check
setCheck(getService(), this.autoServiceRegistrationProperties, getProperties(),
this.context, this.heartbeatProperties);
}
public ConsulAutoRegistration managementRegistration() {
return managementRegistration(this.autoServiceRegistrationProperties, getProperties(),
this.context, this.managementRegistrationCustomizers, this.heartbeatProperties);
}
public static ConsulAutoRegistration registration(AutoServiceRegistrationProperties autoServiceRegistrationProperties,
public static ConsulAutoRegistration registration(
AutoServiceRegistrationProperties autoServiceRegistrationProperties,
ConsulDiscoveryProperties properties, ApplicationContext context,
List<ConsulRegistrationCustomizer> registrationCustomizers,
List<ConsulManagementRegistrationCustomizer> managementRegistrationCustomizers,
@@ -87,7 +82,7 @@ public class ConsulAutoRegistration extends ConsulRegistration {
NewService service = new NewService();
String appName = getAppName(properties, context.getEnvironment());
service.setId(getInstanceId(properties, context));
if(!properties.isPreferAgentAddress()) {
if (!properties.isPreferAgentAddress()) {
service.setAddress(properties.getHostname());
}
service.setName(normalizeForDns(appName));
@@ -96,16 +91,20 @@ public class ConsulAutoRegistration extends ConsulRegistration {
if (properties.getPort() != null) {
service.setPort(properties.getPort());
// we know the port and can set the check
setCheck(service, autoServiceRegistrationProperties, properties, context, heartbeatProperties);
setCheck(service, autoServiceRegistrationProperties, properties, context,
heartbeatProperties);
}
ConsulAutoRegistration registration = new ConsulAutoRegistration(service, autoServiceRegistrationProperties,
properties, context, heartbeatProperties, managementRegistrationCustomizers);
ConsulAutoRegistration registration = new ConsulAutoRegistration(service,
autoServiceRegistrationProperties, properties, context,
heartbeatProperties, managementRegistrationCustomizers);
customize(registrationCustomizers, registration);
return registration;
}
public static void customize(List<ConsulRegistrationCustomizer> registrationCustomizers, ConsulAutoRegistration registration) {
public static void customize(
List<ConsulRegistrationCustomizer> registrationCustomizers,
ConsulAutoRegistration registration) {
if (registrationCustomizers != null) {
for (ConsulRegistrationCustomizer customizer : registrationCustomizers) {
customizer.customize(registration);
@@ -119,9 +118,11 @@ public class ConsulAutoRegistration extends ConsulRegistration {
HeartbeatProperties heartbeatProperties) {
if (properties.isRegisterHealthCheck() && service.getCheck() == null) {
Integer checkPort;
if (shouldRegisterManagement(autoServiceRegistrationProperties, properties, context)) {
if (shouldRegisterManagement(autoServiceRegistrationProperties, properties,
context)) {
checkPort = getManagementPort(properties, context);
} else {
}
else {
checkPort = service.getPort();
}
Assert.notNull(checkPort, "checkPort may not be null");
@@ -137,18 +138,24 @@ public class ConsulAutoRegistration extends ConsulRegistration {
NewService management = new NewService();
management.setId(getManagementServiceId(properties, context));
management.setAddress(properties.getHostname());
management.setName(getManagementServiceName(properties, context.getEnvironment()));
management
.setName(getManagementServiceName(properties, context.getEnvironment()));
management.setPort(getManagementPort(properties, context));
management.setTags(properties.getManagementTags());
if (properties.isRegisterHealthCheck()) {
management.setCheck(createCheck(getManagementPort(properties, context), heartbeatProperties, properties));
management.setCheck(createCheck(getManagementPort(properties, context),
heartbeatProperties, properties));
}
ConsulAutoRegistration registration = new ConsulAutoRegistration(management, autoServiceRegistrationProperties, properties, context, heartbeatProperties, managementRegistrationCustomizers);
ConsulAutoRegistration registration = new ConsulAutoRegistration(management,
autoServiceRegistrationProperties, properties, context,
heartbeatProperties, managementRegistrationCustomizers);
managementCustomize(managementRegistrationCustomizers, registration);
return registration;
}
public static void managementCustomize(List<ConsulManagementRegistrationCustomizer> registrationCustomizers, ConsulAutoRegistration registration) {
public static void managementCustomize(
List<ConsulManagementRegistrationCustomizer> registrationCustomizers,
ConsulAutoRegistration registration) {
if (registrationCustomizers != null) {
for (ConsulManagementRegistrationCustomizer customizer : registrationCustomizers) {
customizer.customize(registration);
@@ -156,17 +163,23 @@ public class ConsulAutoRegistration extends ConsulRegistration {
}
}
public static String getInstanceId(ConsulDiscoveryProperties properties, ApplicationContext context) {
public static String getInstanceId(ConsulDiscoveryProperties properties,
ApplicationContext context) {
if (!StringUtils.hasText(properties.getInstanceId())) {
return normalizeForDns(IdUtils.getDefaultInstanceId(context.getEnvironment(), false));
return normalizeForDns(
IdUtils.getDefaultInstanceId(context.getEnvironment(), false));
}
return normalizeForDns(properties.getInstanceId());
}
public static String normalizeForDns(String s) {
if (s == null || !Character.isLetter(s.charAt(0))
|| !Character.isLetterOrDigit(s.charAt(s.length()-1))) {
throw new IllegalArgumentException("Consul service ids must not be empty, must start with a letter, end with a letter or digit, and have as interior characters only letters, digits, and hyphen: "+s);
|| !Character.isLetterOrDigit(s.charAt(s.length() - 1))) {
throw new IllegalArgumentException(
"Consul service ids must not be empty, must start "
+ "with a letter, end with a letter or digit, "
+ "and have as interior characters only letters, "
+ "digits, and hyphen: " + s);
}
StringBuilder normalized = new StringBuilder();
@@ -175,7 +188,8 @@ public class ConsulAutoRegistration extends ConsulRegistration {
Character toAppend = null;
if (Character.isLetterOrDigit(curr)) {
toAppend = curr;
} else if (prev == null || !(prev == SEPARATOR)) {
}
else if (prev == null || !(prev == SEPARATOR)) {
toAppend = SEPARATOR;
}
if (toAppend != null) {
@@ -191,20 +205,23 @@ public class ConsulAutoRegistration extends ConsulRegistration {
List<String> tags = new LinkedList<>(properties.getTags());
if (!StringUtils.isEmpty(properties.getInstanceZone())) {
tags.add(properties.getDefaultZoneMetadataName() + "=" + properties.getInstanceZone());
tags.add(properties.getDefaultZoneMetadataName() + "="
+ properties.getInstanceZone());
}
if (!StringUtils.isEmpty(properties.getInstanceGroup())) {
tags.add("group=" + properties.getInstanceGroup());
}
//store the secure flag in the tags so that clients will be able to figure out whether to use http or https automatically
tags.add("secure=" + Boolean.toString(properties.getScheme().equalsIgnoreCase("https")));
// store the secure flag in the tags so that clients will be able to figure out
// whether to use http or https automatically
tags.add("secure="
+ Boolean.toString(properties.getScheme().equalsIgnoreCase("https")));
return tags;
}
public static NewService.Check createCheck(Integer port, HeartbeatProperties ttlConfig,
ConsulDiscoveryProperties properties) {
public static NewService.Check createCheck(Integer port,
HeartbeatProperties ttlConfig, ConsulDiscoveryProperties properties) {
NewService.Check check = new NewService.Check();
if (ttlConfig.isEnabled()) {
check.setTtl(ttlConfig.getTtl());
@@ -216,25 +233,29 @@ public class ConsulAutoRegistration extends ConsulRegistration {
if (properties.getHealthCheckUrl() != null) {
check.setHttp(properties.getHealthCheckUrl());
} else {
}
else {
check.setHttp(String.format("%s://%s:%s%s", properties.getScheme(),
properties.getHostname(), port,
properties.getHealthCheckPath()));
properties.getHostname(), port, properties.getHealthCheckPath()));
}
check.setHeader(properties.getHealthCheckHeaders());
check.setInterval(properties.getHealthCheckInterval());
check.setTimeout(properties.getHealthCheckTimeout());
if (StringUtils.hasText(properties.getHealthCheckCriticalTimeout())) {
check.setDeregisterCriticalServiceAfter(properties.getHealthCheckCriticalTimeout());
check.setDeregisterCriticalServiceAfter(
properties.getHealthCheckCriticalTimeout());
}
check.setTlsSkipVerify(properties.getHealthCheckTlsSkipVerify());
return check;
}
/**
* @param properties consul discovery properties
* @param env Spring environment
* @return the app name, currently the spring.application.name property
*/
public static String getAppName(ConsulDiscoveryProperties properties, Environment env) {
public static String getAppName(ConsulDiscoveryProperties properties,
Environment env) {
final String appName = properties.getServiceName();
if (StringUtils.hasText(appName)) {
return appName;
@@ -243,44 +264,83 @@ public class ConsulAutoRegistration extends ConsulRegistration {
}
/**
* @return if the management service should be registered with the {@link ServiceRegistry}
* @param autoServiceRegistrationProperties registration properties
* @param properties discovery properties
* @param context Spring application context
* @return if the management service should be registered with the
* {@link ServiceRegistry}
*/
public static boolean shouldRegisterManagement(AutoServiceRegistrationProperties autoServiceRegistrationProperties, ConsulDiscoveryProperties properties, ApplicationContext context) {
public static boolean shouldRegisterManagement(
AutoServiceRegistrationProperties autoServiceRegistrationProperties,
ConsulDiscoveryProperties properties, ApplicationContext context) {
return autoServiceRegistrationProperties.isRegisterManagement()
&& getManagementPort(properties, context) != null
&& ManagementServerPortUtils.isDifferent(context);
}
/**
* @param properties discovery properties
* @param context Spring application context
* @return the serviceId of the Management Service
*/
public static String getManagementServiceId(ConsulDiscoveryProperties properties, ApplicationContext context) {
public static String getManagementServiceId(ConsulDiscoveryProperties properties,
ApplicationContext context) {
final String instanceId = properties.getInstanceId();
if (StringUtils.hasText(instanceId)) {
return normalizeForDns(instanceId + SEPARATOR + properties.getManagementSuffix());
return normalizeForDns(
instanceId + SEPARATOR + properties.getManagementSuffix());
}
return normalizeForDns(IdUtils.getDefaultInstanceId(context.getEnvironment(), false)) + SEPARATOR + properties.getManagementSuffix();
return normalizeForDns(
IdUtils.getDefaultInstanceId(context.getEnvironment(), false)) + SEPARATOR
+ properties.getManagementSuffix();
}
/**
* @param properties discovery properties
* @param env Spring environment
* @return the service name of the Management Service
*/
public static String getManagementServiceName(ConsulDiscoveryProperties properties, Environment env) {
public static String getManagementServiceName(ConsulDiscoveryProperties properties,
Environment env) {
final String appName = properties.getServiceName();
if (StringUtils.hasText(appName)) {
return normalizeForDns(appName + SEPARATOR + properties.getManagementSuffix());
return normalizeForDns(
appName + SEPARATOR + properties.getManagementSuffix());
}
return normalizeForDns(getAppName(properties, env)) + SEPARATOR + properties.getManagementSuffix();
return normalizeForDns(getAppName(properties, env)) + SEPARATOR
+ properties.getManagementSuffix();
}
/**
* @param properties discovery properties
* @param context Spring application context
* @return the port of the Management Service
*/
public static Integer getManagementPort(ConsulDiscoveryProperties properties, ApplicationContext context) {
public static Integer getManagementPort(ConsulDiscoveryProperties properties,
ApplicationContext context) {
// If an alternate external port is specified, use it instead
if (properties.getManagementPort() != null) {
return properties.getManagementPort();
}
return ManagementServerPortUtils.getPort(context);
}
public void initializePort(int knownPort) {
if (getService().getPort() == null) {
// not set by properties
getService().setPort(knownPort);
}
// we might not have a port until now, so this is the earliest we
// can create a check
setCheck(getService(), this.autoServiceRegistrationProperties, getProperties(),
this.context, this.heartbeatProperties);
}
public ConsulAutoRegistration managementRegistration() {
return managementRegistration(this.autoServiceRegistrationProperties,
getProperties(), this.context, this.managementRegistrationCustomizers,
this.heartbeatProperties);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2016 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,6 +18,7 @@ package org.springframework.cloud.consul.serviceregistry;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.cloud.client.serviceregistry.AbstractAutoServiceRegistration;
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationProperties;
@@ -29,11 +30,13 @@ import org.springframework.util.StringUtils;
/**
* @author Spencer Gibb
*/
public class ConsulAutoServiceRegistration extends AbstractAutoServiceRegistration<ConsulRegistration> {
public class ConsulAutoServiceRegistration
extends AbstractAutoServiceRegistration<ConsulRegistration> {
private static Log log = LogFactory.getLog(ConsulAutoServiceRegistration.class);
private ConsulDiscoveryProperties properties;
private ConsulAutoRegistration registration;
public ConsulAutoServiceRegistration(ConsulServiceRegistry serviceRegistry,
@@ -50,10 +53,12 @@ public class ConsulAutoServiceRegistration extends AbstractAutoServiceRegistrati
@Override
protected ConsulAutoRegistration getRegistration() {
if (this.registration.getService().getPort() == null && this.getPort().get() > 0) {
if (this.registration.getService().getPort() == null
&& this.getPort().get() > 0) {
this.registration.initializePort(this.getPort().get());
}
Assert.notNull(this.registration.getService().getPort(), "service.port has not been set");
Assert.notNull(this.registration.getService().getPort(),
"service.port has not been set");
return this.registration;
}
@@ -89,7 +94,7 @@ public class ConsulAutoServiceRegistration extends AbstractAutoServiceRegistrati
@Override
protected Object getConfiguration() {
return properties;
return this.properties;
}
@Override
@@ -116,7 +121,7 @@ public class ConsulAutoServiceRegistration extends AbstractAutoServiceRegistrati
@Override
@SuppressWarnings("deprecation")
protected String getAppName() {
String appName = properties.getServiceName();
String appName = this.properties.getServiceName();
return StringUtils.isEmpty(appName) ? super.getAppName() : appName;
}
@@ -125,4 +130,5 @@ public class ConsulAutoServiceRegistration extends AbstractAutoServiceRegistrati
// do nothing so we can listen for this event in a different class
// this ensures start() can be retried if spring-retry is available
}
}

View File

@@ -44,7 +44,8 @@ import org.springframework.context.annotation.Configuration;
@ConditionalOnMissingBean(type = "org.springframework.cloud.consul.discovery.ConsulLifecycle")
@ConditionalOnConsulEnabled
@ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true)
@AutoConfigureAfter({AutoServiceRegistrationConfiguration.class, ConsulServiceRegistryAutoConfiguration.class})
@AutoConfigureAfter({ AutoServiceRegistrationConfiguration.class,
ConsulServiceRegistryAutoConfiguration.class })
public class ConsulAutoServiceRegistrationAutoConfiguration {
@Autowired
@@ -62,31 +63,34 @@ public class ConsulAutoServiceRegistrationAutoConfiguration {
}
@Bean
public ConsulAutoServiceRegistrationListener consulAutoServiceRegistrationListener(ConsulAutoServiceRegistration registration) {
public ConsulAutoServiceRegistrationListener consulAutoServiceRegistrationListener(
ConsulAutoServiceRegistration registration) {
return new ConsulAutoServiceRegistrationListener(registration);
}
@Bean
@ConditionalOnMissingBean
public ConsulAutoRegistration consulRegistration(AutoServiceRegistrationProperties autoServiceRegistrationProperties,
public ConsulAutoRegistration consulRegistration(
AutoServiceRegistrationProperties autoServiceRegistrationProperties,
ConsulDiscoveryProperties properties, ApplicationContext applicationContext,
ObjectProvider<List<ConsulRegistrationCustomizer>> registrationCustomizers,
ObjectProvider<List<ConsulManagementRegistrationCustomizer>> managementRegistrationCustomizers,
HeartbeatProperties heartbeatProperties) {
return ConsulAutoRegistration.registration(autoServiceRegistrationProperties, properties,
applicationContext, registrationCustomizers.getIfAvailable(),
managementRegistrationCustomizers.getIfAvailable(),
heartbeatProperties);
return ConsulAutoRegistration.registration(autoServiceRegistrationProperties,
properties, applicationContext, registrationCustomizers.getIfAvailable(),
managementRegistrationCustomizers.getIfAvailable(), heartbeatProperties);
}
@Configuration
@ConditionalOnClass(ServletContext.class)
protected static class ConsulServletConfiguration {
@Bean
public ConsulRegistrationCustomizer servletConsulCustomizer(ObjectProvider<ServletContext> servletContext) {
public ConsulRegistrationCustomizer servletConsulCustomizer(
ObjectProvider<ServletContext> servletContext) {
return new ConsulServletRegistrationCustomizer(servletContext);
}
}
}

View File

@@ -1,3 +1,19 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.consul.serviceregistry;
import org.springframework.boot.web.context.ConfigurableWebServerApplicationContext;
@@ -6,10 +22,17 @@ import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.SmartApplicationListener;
/**
* Auto registers service upon web server initialization.
*
* @author Spencer Gibb
*/
public class ConsulAutoServiceRegistrationListener implements SmartApplicationListener {
private final ConsulAutoServiceRegistration autoServiceRegistration;
public ConsulAutoServiceRegistrationListener(ConsulAutoServiceRegistration autoServiceRegistration) {
public ConsulAutoServiceRegistrationListener(
ConsulAutoServiceRegistration autoServiceRegistration) {
this.autoServiceRegistration = autoServiceRegistration;
}
@@ -30,8 +53,9 @@ public class ConsulAutoServiceRegistrationListener implements SmartApplicationLi
ApplicationContext context = event.getApplicationContext();
if (context instanceof ConfigurableWebServerApplicationContext) {
if ("management".equals(
((ConfigurableWebServerApplicationContext) context).getServerNamespace())) {
if ("management"
.equals(((ConfigurableWebServerApplicationContext) context)
.getServerNamespace())) {
return;
}
}
@@ -44,4 +68,5 @@ public class ConsulAutoServiceRegistrationListener implements SmartApplicationLi
public int getOrder() {
return 0;
}
}

View File

@@ -20,5 +20,11 @@ package org.springframework.cloud.consul.serviceregistry;
* @author Alexey Savchuk (devpreview)
*/
public interface ConsulManagementRegistrationCustomizer {
/**
* Customizes a registration.
* @param managementRegistration registration to customize
*/
void customize(ConsulRegistration managementRegistration);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2016 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,22 +16,23 @@
package org.springframework.cloud.consul.serviceregistry;
import org.springframework.cloud.client.DefaultServiceInstance;
import org.springframework.cloud.client.serviceregistry.Registration;
import com.ecwid.consul.v1.agent.model.NewService;
import org.springframework.cloud.consul.discovery.ConsulDiscoveryProperties;
import org.springframework.cloud.consul.discovery.ConsulServerUtils;
import java.net.URI;
import java.util.Map;
import com.ecwid.consul.v1.agent.model.NewService;
import org.springframework.cloud.client.DefaultServiceInstance;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.cloud.consul.discovery.ConsulDiscoveryProperties;
import org.springframework.cloud.consul.discovery.ConsulServerUtils;
/**
* @author Spencer Gibb
*/
public class ConsulRegistration implements Registration {
private final NewService service;
private ConsulDiscoveryProperties properties;
public ConsulRegistration(NewService service, ConsulDiscoveryProperties properties) {
@@ -40,11 +41,11 @@ public class ConsulRegistration implements Registration {
}
public NewService getService() {
return service;
return this.service;
}
protected ConsulDiscoveryProperties getProperties() {
return properties;
return this.properties;
}
public String getInstanceId() {
@@ -79,4 +80,5 @@ public class ConsulRegistration implements Registration {
public Map<String, String> getMetadata() {
return ConsulServerUtils.getMetadata(getService().getTags());
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2016 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,5 +20,7 @@ package org.springframework.cloud.consul.serviceregistry;
* @author Piotr Wielgolaski
*/
public interface ConsulRegistrationCustomizer {
void customize(ConsulRegistration registration);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2016 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,21 +18,21 @@ package org.springframework.cloud.consul.serviceregistry;
import java.util.List;
import com.ecwid.consul.ConsulException;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.QueryParams;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.agent.model.NewService;
import com.ecwid.consul.v1.health.model.Check;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cloud.client.serviceregistry.ServiceRegistry;
import org.springframework.cloud.consul.discovery.ConsulDiscoveryProperties;
import org.springframework.cloud.consul.discovery.HeartbeatProperties;
import org.springframework.cloud.consul.discovery.TtlScheduler;
import org.springframework.util.ReflectionUtils;
import com.ecwid.consul.ConsulException;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.QueryParams;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.health.model.Check;
import com.ecwid.consul.v1.agent.model.NewService;
import static org.springframework.boot.actuate.health.Status.OUT_OF_SERVICE;
import static org.springframework.boot.actuate.health.Status.UP;
@@ -51,7 +51,9 @@ public class ConsulServiceRegistry implements ServiceRegistry<ConsulRegistration
private final HeartbeatProperties heartbeatProperties;
public ConsulServiceRegistry(ConsulClient client, ConsulDiscoveryProperties properties, TtlScheduler ttlScheduler, HeartbeatProperties heartbeatProperties) {
public ConsulServiceRegistry(ConsulClient client,
ConsulDiscoveryProperties properties, TtlScheduler ttlScheduler,
HeartbeatProperties heartbeatProperties) {
this.client = client;
this.properties = properties;
this.ttlScheduler = ttlScheduler;
@@ -62,30 +64,36 @@ public class ConsulServiceRegistry implements ServiceRegistry<ConsulRegistration
public void register(ConsulRegistration reg) {
log.info("Registering service with consul: " + reg.getService());
try {
client.agentServiceRegister(reg.getService(), properties.getAclToken());
this.client.agentServiceRegister(reg.getService(),
this.properties.getAclToken());
NewService service = reg.getService();
if (heartbeatProperties.isEnabled() && ttlScheduler != null && service.getCheck() != null && service.getCheck().getTtl() != null) {
ttlScheduler.add(reg.getInstanceId());
if (this.heartbeatProperties.isEnabled() && this.ttlScheduler != null
&& service.getCheck() != null
&& service.getCheck().getTtl() != null) {
this.ttlScheduler.add(reg.getInstanceId());
}
}
catch (ConsulException e) {
if (this.properties.isFailFast()) {
log.error("Error registering service with consul: " + reg.getService(), e);
log.error("Error registering service with consul: " + reg.getService(),
e);
ReflectionUtils.rethrowRuntimeException(e);
}
log.warn("Failfast is false. Error registering service with consul: " + reg.getService(), e);
log.warn("Failfast is false. Error registering service with consul: "
+ reg.getService(), e);
}
}
@Override
public void deregister(ConsulRegistration reg) {
if (ttlScheduler != null) {
ttlScheduler.remove(reg.getInstanceId());
if (this.ttlScheduler != null) {
this.ttlScheduler.remove(reg.getInstanceId());
}
if (log.isInfoEnabled()) {
log.info("Deregistering service with consul: " + reg.getInstanceId());
}
client.agentServiceDeregister(reg.getInstanceId(), properties.getAclToken());
this.client.agentServiceDeregister(reg.getInstanceId(),
this.properties.getAclToken());
}
@Override
@@ -96,11 +104,13 @@ public class ConsulServiceRegistry implements ServiceRegistry<ConsulRegistration
@Override
public void setStatus(ConsulRegistration registration, String status) {
if (status.equalsIgnoreCase(OUT_OF_SERVICE.getCode())) {
client.agentServiceSetMaintenance(registration.getInstanceId(), true);
} else if (status.equalsIgnoreCase(UP.getCode())) {
client.agentServiceSetMaintenance(registration.getInstanceId(), false);
} else {
throw new IllegalArgumentException("Unknown status: "+status);
this.client.agentServiceSetMaintenance(registration.getInstanceId(), true);
}
else if (status.equalsIgnoreCase(UP.getCode())) {
this.client.agentServiceSetMaintenance(registration.getInstanceId(), false);
}
else {
throw new IllegalArgumentException("Unknown status: " + status);
}
}
@@ -108,7 +118,8 @@ public class ConsulServiceRegistry implements ServiceRegistry<ConsulRegistration
@Override
public Object getStatus(ConsulRegistration registration) {
String serviceId = registration.getServiceId();
Response<List<Check>> response = client.getHealthChecksForService(serviceId, QueryParams.DEFAULT);
Response<List<Check>> response = this.client.getHealthChecksForService(serviceId,
QueryParams.DEFAULT);
List<Check> checks = response.getValue();
for (Check check : checks) {
@@ -121,4 +132,5 @@ public class ConsulServiceRegistry implements ServiceRegistry<ConsulRegistration
return UP.getCode();
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2016 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,6 +16,8 @@
package org.springframework.cloud.consul.serviceregistry;
import com.ecwid.consul.v1.ConsulClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
@@ -29,8 +31,6 @@ import org.springframework.cloud.consul.discovery.TtlScheduler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.ecwid.consul.v1.ConsulClient;
/**
* @author Spencer Gibb
*/
@@ -45,15 +45,18 @@ public class ConsulServiceRegistryAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public ConsulServiceRegistry consulServiceRegistry(ConsulClient consulClient, ConsulDiscoveryProperties properties,
HeartbeatProperties heartbeatProperties) {
return new ConsulServiceRegistry(consulClient, properties, ttlScheduler, heartbeatProperties);
public ConsulServiceRegistry consulServiceRegistry(ConsulClient consulClient,
ConsulDiscoveryProperties properties,
HeartbeatProperties heartbeatProperties) {
return new ConsulServiceRegistry(consulClient, properties, this.ttlScheduler,
heartbeatProperties);
}
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty("spring.cloud.consul.discovery.heartbeat.enabled")
public TtlScheduler ttlScheduler(ConsulClient consulClient, HeartbeatProperties heartbeatProperties) {
public TtlScheduler ttlScheduler(ConsulClient consulClient,
HeartbeatProperties heartbeatProperties) {
return new TtlScheduler(heartbeatProperties, consulClient);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2016 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,10 +16,11 @@
package org.springframework.cloud.consul.serviceregistry;
import javax.servlet.ServletContext;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletContext;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.util.StringUtils;
@@ -27,20 +28,21 @@ import org.springframework.util.StringUtils;
* @author Piotr Wielgolaski
*/
public class ConsulServletRegistrationCustomizer implements ConsulRegistrationCustomizer {
private ObjectProvider<ServletContext> servletContext;
public ConsulServletRegistrationCustomizer(ObjectProvider<ServletContext> servletContext) {
public ConsulServletRegistrationCustomizer(
ObjectProvider<ServletContext> servletContext) {
this.servletContext = servletContext;
}
@Override
public void customize(ConsulRegistration registration) {
if (servletContext == null) {
if (this.servletContext == null) {
return;
}
ServletContext sc = servletContext.getIfAvailable();
if(sc != null
&& StringUtils.hasText(sc.getContextPath())
ServletContext sc = this.servletContext.getIfAvailable();
if (sc != null && StringUtils.hasText(sc.getContextPath())
&& StringUtils.hasText(sc.getContextPath().replaceAll("/", ""))) {
List<String> tags = registration.getService().getTags();
if (tags == null) {
@@ -50,4 +52,5 @@ public class ConsulServletRegistrationCustomizer implements ConsulRegistrationCu
registration.getService().setTags(tags);
}
}
}

View File

@@ -4,8 +4,6 @@ org.springframework.cloud.consul.discovery.configclient.ConsulConfigServerAutoCo
org.springframework.cloud.consul.serviceregistry.ConsulAutoServiceRegistrationAutoConfiguration,\
org.springframework.cloud.consul.serviceregistry.ConsulServiceRegistryAutoConfiguration,\
org.springframework.cloud.consul.discovery.ConsulDiscoveryClientConfiguration
org.springframework.cloud.bootstrap.BootstrapConfiguration=\
org.springframework.cloud.consul.discovery.configclient.ConsulDiscoveryClientConfigServiceBootstrapConfiguration

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2016 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,6 +20,7 @@ import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
@@ -29,19 +30,17 @@ import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
/**
* @author Spencer Gibb
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ConsulDiscoveryClientAclTests.MyTestConfig.class,
properties = {"spring.application.name=testConsulDiscoveryAcl",
"spring.cloud.consul.discovery.preferIpAddress=true",
"consul.token=2d2e6b3b-1c82-40ab-8171-54609d8ad304"},
webEnvironment = RANDOM_PORT)
@SpringBootTest(classes = ConsulDiscoveryClientAclTests.MyTestConfig.class, properties = {
"spring.application.name=testConsulDiscoveryAcl",
"spring.cloud.consul.discovery.preferIpAddress=true",
"consul.token=2d2e6b3b-1c82-40ab-8171-54609d8ad304" }, webEnvironment = RANDOM_PORT)
public class ConsulDiscoveryClientAclTests {
@Autowired
@@ -49,24 +48,25 @@ public class ConsulDiscoveryClientAclTests {
@Test
public void getInstancesForThisServiceWorks() {
List<ServiceInstance> instances = discoveryClient.getInstances("testConsulDiscoveryAcl");
assertNotNull("instances was null", instances);
assertFalse("instances was empty", instances.isEmpty());
List<ServiceInstance> instances = this.discoveryClient
.getInstances("testConsulDiscoveryAcl");
assertThat(instances).as("instances was null").isNotNull();
assertThat(instances.isEmpty()).as("instances was empty").isFalse();
}
@Test
public void getInstancesForSecondServiceWorks() throws Exception {
new SpringApplicationBuilder(MyTestConfig.class)
.run("--spring.application.name=testSecondServiceAcl",
"--server.port=0",
"--spring.cloud.consul.discovery.preferIpAddress=true",
"--consul.token=2d2e6b3b-1c82-40ab-8171-54609d8ad304");
new SpringApplicationBuilder(MyTestConfig.class).run(
"--spring.application.name=testSecondServiceAcl", "--server.port=0",
"--spring.cloud.consul.discovery.preferIpAddress=true",
"--consul.token=2d2e6b3b-1c82-40ab-8171-54609d8ad304");
List<ServiceInstance> instances = discoveryClient.getInstances("testSecondServiceAcl");
assertNotNull("second service instances was null", instances);
assertFalse("second service instances was empty", instances.isEmpty());
List<ServiceInstance> instances = this.discoveryClient
.getInstances("testSecondServiceAcl");
assertThat(instances).as("second service instances was null").isNotNull();
assertThat(instances.isEmpty()).as("second service instances was empty")
.isFalse();
}
@Configuration
@@ -75,4 +75,5 @@ public class ConsulDiscoveryClientAclTests {
public static class MyTestConfig {
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2018 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,6 +22,7 @@ import java.util.Map;
import org.apache.http.conn.util.InetAddressUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
@@ -30,9 +31,7 @@ import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
/**
@@ -40,13 +39,12 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
* @author Tim Ysewyn
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ConsulDiscoveryClientCustomizedTests.MyTestConfig.class,
properties = { "spring.application.name=testConsulDiscovery2",
@SpringBootTest(classes = ConsulDiscoveryClientCustomizedTests.MyTestConfig.class, properties = {
"spring.application.name=testConsulDiscovery2",
"spring.cloud.consul.discovery.instanceId=testConsulDiscovery2Id",
"spring.cloud.consul.discovery.hostname=testConsulDiscovery2Host",
"spring.cloud.consul.discovery.registerHealthCheck=false",
"spring.cloud.consul.discovery.tags=plaintag,foo=bar,foo2=bar2=baz2" },
webEnvironment = RANDOM_PORT)
"spring.cloud.consul.discovery.tags=plaintag,foo=bar,foo2=bar2=baz2" }, webEnvironment = RANDOM_PORT)
public class ConsulDiscoveryClientCustomizedTests {
@Autowired
@@ -54,42 +52,44 @@ public class ConsulDiscoveryClientCustomizedTests {
@Test
public void getInstancesForServiceWorks() {
List<ServiceInstance> instances = discoveryClient.getInstances("consul");
assertNotNull("instances was null", instances);
assertFalse("instances was empty", instances.isEmpty());
List<ServiceInstance> instances = this.discoveryClient.getInstances("consul");
assertThat(instances).as("instances was null").isNotNull();
assertThat(instances.isEmpty()).as("instances was empty").isFalse();
}
private void assertNotIpAddress(ServiceInstance instance) {
assertFalse("host is an ip address",
InetAddressUtils.isIPv4Address(instance.getHost()));
assertThat(InetAddressUtils.isIPv4Address(instance.getHost()))
.as("host is an ip address").isFalse();
}
@Test
public void getMetadataWorks() throws InterruptedException {
List<ServiceInstance> instances = discoveryClient
List<ServiceInstance> instances = this.discoveryClient
.getInstances("testConsulDiscovery2");
assertNotNull("instances was null", instances);
assertFalse("instances was empty", instances.isEmpty());
assertThat(instances).as("instances was null").isNotNull();
assertThat(instances.isEmpty()).as("instances was empty").isFalse();
ServiceInstance instance = instances.get(0);
assertInstance(instance);
}
private void assertInstance(ServiceInstance instance) {
assertEquals("instance id was wrong", "testConsulDiscovery2Id", instance.getInstanceId());
assertEquals("service id was wrong", "testConsulDiscovery2", instance.getServiceId());
assertThat(instance.getInstanceId()).as("instance id was wrong")
.isEqualTo("testConsulDiscovery2Id");
assertThat(instance.getServiceId()).as("service id was wrong")
.isEqualTo("testConsulDiscovery2");
Map<String, String> metadata = instance.getMetadata();
assertNotNull("metadata was null", metadata);
assertThat(metadata).as("metadata was null").isNotNull();
String foo = metadata.get("foo");
assertEquals("metadata key foo was wrong", "bar", foo);
assertThat(foo).as("metadata key foo was wrong").isEqualTo("bar");
String plaintag = metadata.get("plaintag");
assertEquals("metadata key plaintag was wrong", "plaintag", plaintag);
assertThat(plaintag).as("metadata key plaintag was wrong").isEqualTo("plaintag");
String foo2 = metadata.get("foo2");
assertEquals("metadata key foo2 was wrong", "bar2=baz2", foo2);
assertThat(foo2).as("metadata key foo2 was wrong").isEqualTo("bar2=baz2");
}
@Configuration
@@ -98,4 +98,5 @@ public class ConsulDiscoveryClientCustomizedTests {
public static class MyTestConfig {
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2015 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,38 +19,33 @@ package org.springframework.cloud.consul.discovery;
import java.util.Arrays;
import java.util.List;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.agent.model.NewService;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.agent.model.NewService;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasEntry;
import static org.hamcrest.Matchers.hasSize;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.MOCK;
/**
* @author Piotr Wielgolaski
*/
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = MOCK,
classes = ConsulDiscoveryClientDefaultQueryTagTests.TestConfig.class,
properties = {
"spring.application.name=consulServiceDefaultTag",
"spring.cloud.consul.discovery.catalogServicesWatch.enabled=false",
"spring.cloud.consul.discovery.defaultQueryTag=intg"})
@SpringBootTest(webEnvironment = MOCK, classes = ConsulDiscoveryClientDefaultQueryTagTests.TestConfig.class, properties = {
"spring.application.name=consulServiceDefaultTag",
"spring.cloud.consul.discovery.catalogServicesWatch.enabled=false",
"spring.cloud.consul.discovery.defaultQueryTag=intg" })
@DirtiesContext
public class ConsulDiscoveryClientDefaultQueryTagTests {
@@ -63,25 +58,27 @@ public class ConsulDiscoveryClientDefaultQueryTagTests {
private ConsulClient consulClient;
private NewService intgService = serviceForEnvironment("intg", 9081);
private NewService uatService = serviceForEnvironment("uat", 9080);
@Before
public void setUp() throws Exception {
consulClient.agentServiceRegister(intgService);
consulClient.agentServiceRegister(uatService);
this.consulClient.agentServiceRegister(this.intgService);
this.consulClient.agentServiceRegister(this.uatService);
}
@After
public void tearDown() throws Exception {
consulClient.agentServiceDeregister(intgService.getId());
consulClient.agentServiceDeregister(uatService.getId());
this.consulClient.agentServiceDeregister(this.intgService.getId());
this.consulClient.agentServiceDeregister(this.uatService.getId());
}
@Test
public void shouldReturnOnlyIntgInstance() {
List<ServiceInstance> instances = discoveryClient.getInstances(NAME);
assertThat("instances was wrong size", instances, hasSize(1));
assertThat("instance is not intg", instances.get(0).getMetadata(), hasEntry("intg", "intg"));
List<ServiceInstance> instances = this.discoveryClient.getInstances(NAME);
assertThat(instances).as("instances was wrong size").hasSize(1);
assertThat(instances.get(0).getMetadata()).as("instance is not intg")
.containsEntry("intg", "intg");
}
private NewService serviceForEnvironment(String env, int port) {
@@ -100,4 +97,5 @@ public class ConsulDiscoveryClientDefaultQueryTagTests {
protected static class TestConfig {
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2015 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,15 +16,11 @@
package org.springframework.cloud.consul.discovery;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
@@ -33,15 +29,16 @@ import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
/**
* @author Glen Lockhart
*/
@RunWith(SpringRunner.class)
@SpringBootTest(properties = { "spring.application.name=testConsulDiscoveryHttps",
"spring.cloud.consul.discovery.prefer-ip-address=true",
"spring.cloud.consul.discovery.scheme=https"},
classes = ConsulDiscoveryClientHttpsTests.MyTestConfig.class,
webEnvironment = RANDOM_PORT)
"spring.cloud.consul.discovery.prefer-ip-address=true",
"spring.cloud.consul.discovery.scheme=https" }, classes = ConsulDiscoveryClientHttpsTests.MyTestConfig.class, webEnvironment = RANDOM_PORT)
public class ConsulDiscoveryClientHttpsTests {
@Autowired
@@ -49,12 +46,13 @@ public class ConsulDiscoveryClientHttpsTests {
@Test
public void getInstancesForServiceWorks() {
List<ServiceInstance> instances = discoveryClient.getInstances("testConsulDiscoveryHttps");
assertNotNull("instances was null", instances);
assertFalse("instances was empty", instances.isEmpty());
List<ServiceInstance> instances = this.discoveryClient
.getInstances("testConsulDiscoveryHttps");
assertThat(instances).as("instances was null").isNotNull();
assertThat(instances.isEmpty()).as("instances was empty").isFalse();
ServiceInstance instance = instances.get(0);
assertTrue("instance was not secure (https)", instance.isSecure());
assertThat(instance.isSecure()).as("instance was not secure (https)").isTrue();
}
@Configuration
@@ -63,4 +61,5 @@ public class ConsulDiscoveryClientHttpsTests {
public static class MyTestConfig {
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2015 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,16 +16,14 @@
package org.springframework.cloud.consul.discovery;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
import java.util.List;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.QueryParams;
import com.ecwid.consul.v1.Response;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
@@ -34,9 +32,8 @@ import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.QueryParams;
import com.ecwid.consul.v1.Response;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
/**
* @author Spencer Gibb
@@ -45,46 +42,46 @@ import com.ecwid.consul.v1.Response;
@RunWith(SpringRunner.class)
@SpringBootTest(properties = { "spring.application.name=testConsulDiscovery",
"spring.cloud.consul.discovery.prefer-ip-address=true",
"spring.cloud.consul.discovery.tags=foo=bar", },
classes = ConsulDiscoveryClientTests.MyTestConfig.class,
webEnvironment = RANDOM_PORT)
"spring.cloud.consul.discovery.tags=foo=bar" }, classes = ConsulDiscoveryClientTests.MyTestConfig.class, webEnvironment = RANDOM_PORT)
public class ConsulDiscoveryClientTests {
@Autowired
private ConsulDiscoveryClient discoveryClient;
@Autowired
private ConsulClient consulClient;
@Test
public void getInstancesForServiceWorks() {
List<ServiceInstance> instances = discoveryClient.getInstances("testConsulDiscovery");
assertNotNull("instances was null", instances);
assertFalse("instances was empty", instances.isEmpty());
List<ServiceInstance> instances = this.discoveryClient
.getInstances("testConsulDiscovery");
assertThat(instances).as("instances was null").isNotNull();
assertThat(instances.isEmpty()).as("instances was empty").isFalse();
ServiceInstance instance = instances.get(0);
assertFalse("instance was secure (https)", instance.isSecure());
assertThat(instance.isSecure()).as("instance was secure (https)").isFalse();
assertIpAddress(instance);
assertThat(instance.getMetadata())
.containsEntry("foo", "bar");
assertThat(instance.getMetadata()).containsEntry("foo", "bar");
}
@Test
public void getInstancesForServiceRespectsQueryParams() {
Response<List<String>> catalogDatacenters = consulClient.getCatalogDatacenters();
Response<List<String>> catalogDatacenters = this.consulClient
.getCatalogDatacenters();
List<String> dataCenterList = catalogDatacenters.getValue();
assertFalse("no data centers found", dataCenterList.isEmpty());
List<ServiceInstance> instances = discoveryClient.getInstances("testConsulDiscovery",
new QueryParams(dataCenterList.get(0)));
assertFalse("instances was empty", instances.isEmpty());
assertThat(dataCenterList.isEmpty()).as("no data centers found").isFalse();
List<ServiceInstance> instances = this.discoveryClient.getInstances(
"testConsulDiscovery", new QueryParams(dataCenterList.get(0)));
assertThat(instances.isEmpty()).as("instances was empty").isFalse();
ServiceInstance instance = instances.get(0);
assertIpAddress(instance);
}
private void assertIpAddress(ServiceInstance instance) {
assertTrue("host isn't an ip address",
Character.isDigit(instance.getHost().charAt(0)));
assertThat(Character.isDigit(instance.getHost().charAt(0)))
.as("host isn't an ip address").isTrue();
}
@Configuration
@@ -93,4 +90,5 @@ public class ConsulDiscoveryClientTests {
public static class MyTestConfig {
}
}

View File

@@ -1,3 +1,19 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.consul.discovery;
import java.util.Collections;
@@ -10,59 +26,73 @@ import org.springframework.cloud.commons.util.InetUtils;
import org.springframework.cloud.commons.util.InetUtilsProperties;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
public class ConsulDiscoveryPropertiesTests {
private static final String DEFAULT_TAG = "defaultTag";
private static final String MAP_TAG = "mapTag";
private static final String MAP_DC = "mapDc";
private static final String SERVICE_NAME_IN_MAP = "serviceNameInMap";
private static final String SERVICE_NAME_NOT_IN_MAP = "serviceNameNotInMap";
private final Map<String, String> serverListQueryTags = Collections
.singletonMap(SERVICE_NAME_IN_MAP, MAP_TAG);
private final Map<String, String> datacenters = Collections
.singletonMap(SERVICE_NAME_IN_MAP, MAP_DC);
private ConsulDiscoveryProperties properties;
private final Map<String, String> serverListQueryTags = Collections.singletonMap(SERVICE_NAME_IN_MAP, MAP_TAG);
private final Map<String, String> datacenters = Collections.singletonMap(SERVICE_NAME_IN_MAP, MAP_DC);
@Before
public void setUp() {
properties = new ConsulDiscoveryProperties(new InetUtils(new InetUtilsProperties()));
properties.setDefaultQueryTag(DEFAULT_TAG);
properties.setServerListQueryTags(serverListQueryTags);
properties.setDatacenters(datacenters);
this.properties = new ConsulDiscoveryProperties(
new InetUtils(new InetUtilsProperties()));
this.properties.setDefaultQueryTag(DEFAULT_TAG);
this.properties.setServerListQueryTags(this.serverListQueryTags);
this.properties.setDatacenters(this.datacenters);
}
@Test
public void testReturnsNullWhenNoDefaultAndNotInMap() {
properties.setDefaultQueryTag(null);
this.properties.setDefaultQueryTag(null);
assertNull(properties.getQueryTagForService(SERVICE_NAME_NOT_IN_MAP));
assertThat(this.properties.getQueryTagForService(SERVICE_NAME_NOT_IN_MAP))
.isNull();
}
@Test
public void testGetTagReturnsDefaultWhenNotInMap() {
assertEquals(DEFAULT_TAG, properties.getQueryTagForService(SERVICE_NAME_NOT_IN_MAP));
assertThat(this.properties.getQueryTagForService(SERVICE_NAME_NOT_IN_MAP))
.isEqualTo(DEFAULT_TAG);
}
@Test
public void testGetTagReturnsMapValueWhenInMap() {
assertEquals(MAP_TAG, properties.getQueryTagForService(SERVICE_NAME_IN_MAP));
assertThat(this.properties.getQueryTagForService(SERVICE_NAME_IN_MAP))
.isEqualTo(MAP_TAG);
}
@Test
public void testGetDcReturnsNullWhenNotInMap() {
assertNull(properties.getDatacenters().get(SERVICE_NAME_NOT_IN_MAP));
assertThat(this.properties.getDatacenters().get(SERVICE_NAME_NOT_IN_MAP))
.isNull();
}
@Test
public void testGetDcReturnsMapValueWhenInMap() {
assertEquals(MAP_DC, properties.getDatacenters().get(SERVICE_NAME_IN_MAP));
assertThat(this.properties.getDatacenters().get(SERVICE_NAME_IN_MAP))
.isEqualTo(MAP_DC);
}
@Test
public void testAddManagementTag() {
properties.getManagementTags().add("newTag");
assertThat(properties.getManagementTags())
this.properties.getManagementTags().add("newTag");
assertThat(this.properties.getManagementTags())
.containsOnly(ConsulDiscoveryProperties.MANAGEMENT, "newTag");
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2015 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -33,7 +33,6 @@ import org.springframework.context.annotation.Bean;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
/**
@@ -42,8 +41,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
@RunWith(SpringRunner.class)
@SpringBootTest(properties = { "spring.application.name=testConsulLoadBalancer",
"spring.cloud.consul.discovery.prefer-ip-address=true",
"spring.cloud.consul.discovery.tags=foo=bar", },
webEnvironment = RANDOM_PORT)
"spring.cloud.consul.discovery.tags=foo=bar" }, webEnvironment = RANDOM_PORT)
public class ConsulLoadbalancerClientTests {
@Autowired
@@ -51,25 +49,26 @@ public class ConsulLoadbalancerClientTests {
@Test
public void chooseWorks() {
ServiceInstance instance = client.choose("testConsulLoadBalancer");
ServiceInstance instance = this.client.choose("testConsulLoadBalancer");
assertThat(instance).isNotNull();
assertThat(instance.isSecure()).isFalse();
assertIpAddress(instance);
assertThat(instance.getMetadata())
.containsEntry("foo", "bar");
assertThat(instance.getMetadata()).containsEntry("foo", "bar");
}
private void assertIpAddress(ServiceInstance instance) {
assertTrue("host isn't an ip address",
Character.isDigit(instance.getHost().charAt(0)));
assertThat(Character.isDigit(instance.getHost().charAt(0)))
.as("host isn't an ip address").isTrue();
}
@SpringBootConfiguration
@EnableAutoConfiguration
@EnableDiscoveryClient
@RibbonClient(name = "testConsulLoadBalancer", configuration = MyRibbonConfig.class)
public static class MyTestConfig { }
public static class MyTestConfig {
}
public static class MyRibbonConfig {
@@ -81,5 +80,7 @@ public class ConsulLoadbalancerClientTests {
public ServerListFilter<Server> ribbonServerListFilter() {
return servers -> servers;
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2016 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,8 +18,11 @@ package org.springframework.cloud.consul.discovery;
import java.util.List;
import com.ecwid.consul.v1.ConsulClient;
import com.netflix.client.config.DefaultClientConfigImpl;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
@@ -27,45 +30,42 @@ import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import com.ecwid.consul.v1.ConsulClient;
import com.netflix.client.config.DefaultClientConfigImpl;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
/**
* @author bomee
* @author b omee
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ConsulServerListAclTests.TestConfig.class,
properties = {"spring.application.name=testConsulServerListAcl",
"spring.cloud.consul.discovery.preferIpAddress=true",
"consul.token=2d2e6b3b-1c82-40ab-8171-54609d8ad304"},
webEnvironment = RANDOM_PORT)
@SpringBootTest(classes = ConsulServerListAclTests.TestConfig.class, properties = {
"spring.application.name=testConsulServerListAcl",
"spring.cloud.consul.discovery.preferIpAddress=true",
"consul.token=2d2e6b3b-1c82-40ab-8171-54609d8ad304" }, webEnvironment = RANDOM_PORT)
public class ConsulServerListAclTests {
@Autowired
private ConsulClient consulClient;
@Autowired
private ConsulClient consulClient;
@Autowired
private ConsulDiscoveryProperties properties;
@Autowired
private ConsulDiscoveryProperties properties;
@Test
public void serverListWorksWithAcl() {
ConsulServerList consulServerList = new ConsulServerList(consulClient, properties);
DefaultClientConfigImpl config = new DefaultClientConfigImpl();
config.setClientName("testConsulServerListAcl");
consulServerList.initWithNiwsConfig(config);
List<ConsulServer> servers = consulServerList.getUpdatedListOfServers();
assertNotNull("servers was null", servers);
assertFalse("servers was empty", servers.isEmpty());
}
@Test
public void serverListWorksWithAcl() {
ConsulServerList consulServerList = new ConsulServerList(this.consulClient,
this.properties);
DefaultClientConfigImpl config = new DefaultClientConfigImpl();
config.setClientName("testConsulServerListAcl");
consulServerList.initWithNiwsConfig(config);
List<ConsulServer> servers = consulServerList.getUpdatedListOfServers();
assertThat(servers).as("servers was null").isNotNull();
assertThat(servers.isEmpty()).as("servers was empty").isFalse();
}
@Configuration
@EnableAutoConfiguration
@EnableDiscoveryClient
public static class TestConfig {
@Configuration
@EnableAutoConfiguration
@EnableDiscoveryClient
public static class TestConfig {
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2016 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,22 +20,21 @@ import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import org.junit.Test;
import org.springframework.cloud.commons.util.InetUtils;
import org.springframework.cloud.commons.util.InetUtilsProperties;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.agent.model.NewService;
import com.netflix.client.config.DefaultClientConfigImpl;
import org.junit.Test;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import org.springframework.cloud.commons.util.InetUtils;
import org.springframework.cloud.commons.util.InetUtilsProperties;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Spencer Gibb
*/
public class ConsulServerListTests {
private final String name = "consulServerListTestsService";
@Test
@@ -48,10 +47,12 @@ public class ConsulServerListTests {
NewService tagged = createService("Tagged", 9080, Arrays.asList(tag));
String zone = "myzone";
NewService withZone = createService("WithZone", 10080, Arrays.asList("zone=" + zone));
NewService withZone = createService("WithZone", 10080,
Arrays.asList("zone=" + zone));
String group = "test";
NewService withGroup = createService("WithGroup", 11080, Arrays.asList("group=" + group));
NewService withGroup = createService("WithGroup", 11080,
Arrays.asList("group=" + group));
try {
consul.agentServiceRegister(nonTagged);
@@ -61,43 +62,51 @@ public class ConsulServerListTests {
InetUtils inetUtils = new InetUtils(new InetUtilsProperties());
DefaultClientConfigImpl config = new DefaultClientConfigImpl();
config.setClientName(name);
config.setClientName(this.name);
ConsulServerList serverList = new ConsulServerList(consul, new ConsulDiscoveryProperties(inetUtils));
ConsulServerList serverList = new ConsulServerList(consul,
new ConsulDiscoveryProperties(inetUtils));
serverList.initWithNiwsConfig(config);
List<ConsulServer> servers = serverList.getInitialListOfServers();
assertThat("servers was wrong size", servers, hasSize(4));
assertThat(servers).as("servers was wrong size").hasSize(4);
int serverWithZoneCount = 0;
for (ConsulServer server : servers) {
if (server.getMetadata().containsKey("zone")) {
serverWithZoneCount++;
assertThat("server was wrong zone", server.getZone(), is(zone));
} else {
assertThat("server was wrong zone", server.getZone(), is(ConsulServer.UNKNOWN_ZONE));
assertThat(server.getZone()).as("server was wrong zone")
.isEqualTo(zone);
}
else {
assertThat(server.getZone()).as("server was wrong zone")
.isEqualTo(ConsulServer.UNKNOWN_ZONE);
}
}
assertThat("server was wrong zone", serverWithZoneCount, is(1));
assertThat(serverWithZoneCount).as("server was wrong zone").isEqualTo(1);
serverList = new ConsulServerList(consul, getProperties(name, tag, inetUtils));
serverList = new ConsulServerList(consul,
getProperties(this.name, tag, inetUtils));
serverList.initWithNiwsConfig(config);
servers = serverList.getInitialListOfServers();
assertThat("servers was wrong size", servers, hasSize(1));
assertThat(servers).as("servers was wrong size").hasSize(1);
ConsulServer server = servers.get(0);
assertThat("server was wrong", server.getPort(), is(9080));
assertThat(server.getPort()).as("server was wrong").isEqualTo(9080);
// test server group
serverList = new ConsulServerList(consul, getProperties(name, "group=" + group, inetUtils));
serverList = new ConsulServerList(consul,
getProperties(this.name, "group=" + group, inetUtils));
serverList.initWithNiwsConfig(config);
servers = serverList.getInitialListOfServers();
assertThat("servers was wrong size", servers, hasSize(1));
assertThat(servers).as("servers was wrong size").hasSize(1);
server = servers.get(0);
assertThat("server was wrong", server.getPort(), is(11080));
assertThat("server group was wrong", server.getMetaInfo().getServerGroup(), is(group));
} finally {
assertThat(server.getPort()).as("server was wrong").isEqualTo(11080);
assertThat(server.getMetaInfo().getServerGroup()).as("server group was wrong")
.isEqualTo(group);
}
finally {
consul.agentServiceDeregister(nonTagged.getId());
consul.agentServiceDeregister(tagged.getId());
consul.agentServiceDeregister(withZone.getId());
@@ -105,7 +114,8 @@ public class ConsulServerListTests {
}
}
private ConsulDiscoveryProperties getProperties(String name, String tag, InetUtils inetUtils) {
private ConsulDiscoveryProperties getProperties(String name, String tag,
InetUtils inetUtils) {
ConsulDiscoveryProperties properties = new ConsulDiscoveryProperties(inetUtils);
HashMap<String, String> map = new HashMap<>();
map.put(name, tag);
@@ -115,8 +125,8 @@ public class ConsulServerListTests {
private NewService createService(String id, int port, List<String> tags) {
NewService service = new NewService();
service.setName(name);
service.setId(name + id);
service.setName(this.name);
service.setId(this.name + id);
service.setAddress("localhost");
service.setPort(port);
if (tags != null) {
@@ -124,4 +134,5 @@ public class ConsulServerListTests {
}
return service;
}
}

View File

@@ -1,8 +1,24 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.consul.discovery;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Semenkov Alexey
@@ -12,19 +28,20 @@ public class ConsulServerUtilsTest {
@Test
public void testAddressFormat() {
String s1 = ConsulServerUtils.fixIPv6Address("fc00:ec:cd::242:ac11:c");
assertEquals("[fc00:ec:cd:0:0:242:ac11:c]", s1);
assertThat(s1).isEqualTo("[fc00:ec:cd:0:0:242:ac11:c]");
String s2 = ConsulServerUtils.fixIPv6Address("[fc00:ec:cd::242:ac11:c]");
assertEquals("[fc00:ec:cd:0:0:242:ac11:c]", s2);
assertThat(s2).isEqualTo("[fc00:ec:cd:0:0:242:ac11:c]");
String s3 = ConsulServerUtils.fixIPv6Address("192.168.0.1");
assertEquals("192.168.0.1", s3);
assertThat(s3).isEqualTo("192.168.0.1");
String s4 = ConsulServerUtils.fixIPv6Address("projects.spring.io");
assertEquals("projects.spring.io", s4);
assertThat(s4).isEqualTo("projects.spring.io");
String s5 = ConsulServerUtils.fixIPv6Address("veryLongHostName");
assertEquals("veryLongHostName", s5);
assertThat(s5).isEqualTo("veryLongHostName");
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2016 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,12 +22,12 @@ import java.util.List;
import com.ecwid.consul.v1.health.model.Check;
import com.ecwid.consul.v1.health.model.HealthService;
import com.netflix.loadbalancer.Server;
import org.junit.Test;
import static com.ecwid.consul.v1.health.model.Check.CheckStatus.*;
import static org.junit.Assert.assertThat;
import static org.hamcrest.Matchers.*;
import static com.ecwid.consul.v1.health.model.Check.CheckStatus.CRITICAL;
import static com.ecwid.consul.v1.health.model.Check.CheckStatus.PASSING;
import static com.ecwid.consul.v1.health.model.Check.CheckStatus.WARNING;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Spencer Gibb
@@ -45,20 +45,20 @@ public class HealthServiceServerListFilterTests {
servers.add(newServer(WARNING));
List<Server> filtered = filter.getFilteredListOfServers(servers);
assertThat("wrong # of filtered servers", filtered, hasSize(2));
assertThat(filtered).as("wrong # of filtered servers").hasSize(2);
}
private ConsulServer newServer(Check.CheckStatus checkStatus) {
HealthService healthService = new HealthService();
HealthService.Node node = new HealthService.Node();
node.setAddress("nodeaddr"+checkStatus.name());
node.setNode("nodenode"+checkStatus.name());
node.setAddress("nodeaddr" + checkStatus.name());
node.setNode("nodenode" + checkStatus.name());
healthService.setNode(node);
HealthService.Service service = new HealthService.Service();
service.setAddress("serviceaddr"+checkStatus.name());
service.setId("serviceid"+checkStatus.name());
service.setAddress("serviceaddr" + checkStatus.name());
service.setId("serviceid" + checkStatus.name());
service.setPort(8080);
service.setService("serviceservice"+checkStatus.name());
service.setService("serviceservice" + checkStatus.name());
healthService.setService(service);
ArrayList<Check> checks = new ArrayList<>();
Check check = new Check();
@@ -67,4 +67,5 @@ public class HealthServiceServerListFilterTests {
healthService.setChecks(checks);
return new ConsulServer(healthService);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2015 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,35 +16,33 @@
package org.springframework.cloud.consul.discovery;
import static org.junit.Assert.assertThat;
import static org.hamcrest.Matchers.*;
import org.joda.time.Period;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Spencer Gibb
*/
public class HeartbeatPropertiesTests {
@Test
public void computeHeartbeatIntervalWorks() {
HeartbeatProperties properties = new HeartbeatProperties();
Period period = properties.computeHearbeatInterval();
@Test
public void computeHeartbeatIntervalWorks() {
HeartbeatProperties properties = new HeartbeatProperties();
Period period = properties.computeHearbeatInterval();
assertThat(period, is(notNullValue()));
assertThat(period.getSeconds(), is(20));
}
assertThat(period).isNotNull();
assertThat(period.getSeconds()).isEqualTo(20);
}
@Test
public void computeShortHeartbeat() {
HeartbeatProperties properties = new HeartbeatProperties();
properties.setTtlValue(2);
Period period = properties.computeHearbeatInterval();
assertThat(period, is(notNullValue()));
assertThat(period.getSeconds(), is(1));
}
@Test
public void computeShortHeartbeat() {
HeartbeatProperties properties = new HeartbeatProperties();
properties.setTtlValue(2);
Period period = properties.computeHearbeatInterval();
assertThat(period).isNotNull();
assertThat(period.getSeconds()).isEqualTo(1);
}
}

View File

@@ -1,9 +1,30 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.consul.discovery;
import java.util.List;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.QueryParams;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.health.model.Check;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
@@ -13,27 +34,20 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.junit4.SpringRunner;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.QueryParams;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.health.model.Check;
import static com.ecwid.consul.v1.health.model.Check.CheckStatus.CRITICAL;
import static com.ecwid.consul.v1.health.model.Check.CheckStatus.PASSING;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertThat;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
/**
* @author Stéphane Leroy
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = TtlSchedulerRemoveTests.TtlSchedulerRemoveTestConfig.class,
properties = { "spring.application.name=ttlSchedulerRemove",
@SpringBootTest(classes = TtlSchedulerRemoveTests.TtlSchedulerRemoveTestConfig.class, properties = {
"spring.application.name=ttlSchedulerRemove",
"spring.cloud.consul.discovery.instance-id=ttlSchedulerRemove-id",
"spring.cloud.consul.discovery.heartbeat.enabled=true",
"spring.cloud.consul.discovery.heartbeat.ttlValue=2" },
webEnvironment = RANDOM_PORT)
"spring.cloud.consul.discovery.heartbeat.ttlValue=2" }, webEnvironment = RANDOM_PORT)
public class TtlSchedulerRemoveTests {
@Autowired
@@ -46,20 +60,20 @@ public class TtlSchedulerRemoveTests {
public void should_not_send_check_if_service_removed() throws InterruptedException {
Thread.sleep(1000); // wait for Ttlscheduler to send a check to consul.
Check serviceCheck = getCheckForService("ttlSchedulerRemove");
assertThat("Service check is in wrong state", serviceCheck.getStatus(),
equalTo(PASSING));
assertThat(serviceCheck.getStatus()).as("Service check is in wrong state")
.isEqualTo(PASSING);
// Remove service from TtlScheduler and wait for TTL to expired.
ttlScheduler.remove("ttlSchedulerRemove-id");
this.ttlScheduler.remove("ttlSchedulerRemove-id");
Thread.sleep(2100);
serviceCheck = getCheckForService("ttlSchedulerRemove");
assertThat("Service check is in wrong state", serviceCheck.getStatus(),
equalTo(CRITICAL));
assertThat(serviceCheck.getStatus()).as("Service check is in wrong state")
.isEqualTo(CRITICAL);
}
private Check getCheckForService(String serviceId) {
Response<List<Check>> checkResponse = consul.getHealthChecksForService(serviceId,
QueryParams.DEFAULT);
Response<List<Check>> checkResponse = this.consul
.getHealthChecksForService(serviceId, QueryParams.DEFAULT);
if (checkResponse.getValue().size() > 0) {
return checkResponse.getValue().get(0);
}
@@ -68,9 +82,10 @@ public class TtlSchedulerRemoveTests {
@Configuration
@EnableAutoConfiguration
@Import({ AutoServiceRegistrationConfiguration.class,
ConsulAutoConfiguration.class,
@Import({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class,
ConsulDiscoveryClientConfiguration.class })
public static class TtlSchedulerRemoveTestConfig { }
}
public static class TtlSchedulerRemoveTestConfig {
}
}

View File

@@ -1,9 +1,30 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.consul.discovery;
import java.util.List;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.QueryParams;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.health.model.Check;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
@@ -13,11 +34,6 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.junit4.SpringRunner;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.QueryParams;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.health.model.Check;
import static com.ecwid.consul.v1.health.model.Check.CheckStatus.PASSING;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
@@ -26,12 +42,12 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
* @author Stéphane Leroy
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = TtlSchedulerTests.TtlSchedulerTestConfig.class,
properties = { "spring.application.name=ttlScheduler",
@SpringBootTest(classes = TtlSchedulerTests.TtlSchedulerTestConfig.class, properties = {
"spring.application.name=ttlScheduler",
"spring.cloud.consul.discovery.instance-id=ttlScheduler-id",
"spring.cloud.consul.discovery.heartbeat.enabled=true",
"spring.cloud.consul.discovery.heartbeat.ttlValue=2", "management.server.port=0" },
webEnvironment = RANDOM_PORT)
"spring.cloud.consul.discovery.heartbeat.ttlValue=2",
"management.server.port=0" }, webEnvironment = RANDOM_PORT)
public class TtlSchedulerTests {
@Autowired
@@ -53,8 +69,8 @@ public class TtlSchedulerTests {
}
private Check getCheckForService(String serviceId) {
Response<List<Check>> checkResponse = consul.getHealthChecksForService(serviceId,
QueryParams.DEFAULT);
Response<List<Check>> checkResponse = this.consul
.getHealthChecksForService(serviceId, QueryParams.DEFAULT);
if (checkResponse.getValue().size() > 0) {
return checkResponse.getValue().get(0);
}
@@ -63,10 +79,10 @@ public class TtlSchedulerTests {
@Configuration
@EnableAutoConfiguration
@Import({ AutoServiceRegistrationConfiguration.class,
ConsulAutoConfiguration.class,
@Import({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class,
ConsulDiscoveryClientConfiguration.class })
public static class TtlSchedulerTestConfig { }
public static class TtlSchedulerTestConfig {
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2016 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,6 +18,7 @@ package org.springframework.cloud.consul.discovery.configclient;
import org.junit.After;
import org.junit.Test;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
@@ -26,9 +27,7 @@ import org.springframework.cloud.consul.discovery.ConsulDiscoveryProperties;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import static org.hamcrest.Matchers.contains;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Dave Syer
@@ -48,25 +47,28 @@ public class ConsulConfigServerAutoConfigurationTests {
public void offByDefault() throws Exception {
this.context = new AnnotationConfigApplicationContext(
ConsulConfigServerAutoConfiguration.class);
assertEquals(0,
this.context.getBeanNamesForType(ConsulDiscoveryProperties.class).length);
assertThat(
this.context.getBeanNamesForType(ConsulDiscoveryProperties.class).length)
.isEqualTo(0);
}
@Test
public void onWhenRequested() throws Exception {
setup("spring.cloud.config.server.prefix=/config");
assertEquals(1,
this.context.getBeanNamesForType(ConsulDiscoveryProperties.class).length);
ConsulDiscoveryProperties properties = this.context.getBean(ConsulDiscoveryProperties.class);
assertThat(properties.getTags(), contains("configPath=/config"));
assertThat(
this.context.getBeanNamesForType(ConsulDiscoveryProperties.class).length)
.isEqualTo(1);
ConsulDiscoveryProperties properties = this.context
.getBean(ConsulDiscoveryProperties.class);
assertThat(properties.getTags()).containsExactly("configPath=/config");
}
private void setup(String... env) {
this.context = new SpringApplicationBuilder(
PropertyPlaceholderAutoConfiguration.class,
ConsulConfigServerAutoConfiguration.class,
ConfigServerProperties.class, ConsulDiscoveryProperties.class).web(WebApplicationType.NONE)
.properties(env).run();
ConsulConfigServerAutoConfiguration.class, ConfigServerProperties.class,
ConsulDiscoveryProperties.class).web(WebApplicationType.NONE)
.properties(env).run();
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2018 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -32,7 +32,7 @@ import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.AbstractApplicationContext;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.verify;
@@ -47,7 +47,7 @@ public class DiscoveryClientConfigServiceAutoConfigurationTests {
@Before
public void init() {
//FIXME: why do I need to do this? (fails in maven build without it.
// FIXME: why do I need to do this? (fails in maven build without it.
TomcatURLStreamHandlerFactory.disable();
}
@@ -67,29 +67,30 @@ public class DiscoveryClientConfigServiceAutoConfigurationTests {
"logging.level.org.springframework.cloud.config.client=DEBUG",
"spring.cloud.consul.discovery.test.enabled:true",
"spring.application.name=discoveryclientconfigservicetest",
"spring.jmx.enabled=false",
"spring.cloud.consul.discovery.port:7001",
"spring.jmx.enabled=false", "spring.cloud.consul.discovery.port:7001",
"spring.cloud.consul.discovery.hostname:foo",
"spring.cloud.config.discovery.service-id:configserver");
assertEquals( 1, this.context
.getBeanNamesForType(ConsulConfigServerAutoConfiguration.class).length);
ConsulDiscoveryClient client = this.context.getParent().getBean(
ConsulDiscoveryClient.class);
assertThat(this.context
.getBeanNamesForType(ConsulConfigServerAutoConfiguration.class).length)
.isEqualTo(1);
ConsulDiscoveryClient client = this.context.getParent()
.getBean(ConsulDiscoveryClient.class);
verify(client, atLeast(2)).getInstances("configserver");
ConfigClientProperties locator = this.context
.getBean(ConfigClientProperties.class);
assertEquals("http://foo:7001/", locator.getUri()[0]);
assertThat(locator.getUri()[0]).isEqualTo("http://foo:7001/");
}
private void setup(String... env) {
this.context = new SpringApplicationBuilder(TestConfig.class)
.properties(env)
this.context = new SpringApplicationBuilder(TestConfig.class).properties(env)
.run();
}
@Configuration
@EnableAutoConfiguration
protected static class TestConfig { }
protected static class TestConfig {
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2018 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,6 +16,8 @@
package org.springframework.cloud.consul.discovery.configclient;
import java.util.Arrays;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.client.DefaultServiceInstance;
import org.springframework.cloud.client.ServiceInstance;
@@ -24,8 +26,6 @@ import org.springframework.cloud.consul.discovery.ConsulDiscoveryProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Arrays;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@@ -39,8 +39,8 @@ public class TestConsulDiscoveryClientBootstrapConfiguration {
ConsulDiscoveryClient client = mock(ConsulDiscoveryClient.class);
ServiceInstance instance = new DefaultServiceInstance("configserver",
properties.getHostname(), properties.getPort(), false);
given(client.getInstances("configserver"))
.willReturn(Arrays.asList(instance));
given(client.getInstances("configserver")).willReturn(Arrays.asList(instance));
return client;
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2017 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,11 +16,10 @@
package org.springframework.cloud.consul.serviceregistry;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
import com.ecwid.consul.v1.agent.model.NewService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
@@ -31,7 +30,8 @@ import org.springframework.cloud.consul.discovery.ConsulDiscoveryProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import com.ecwid.consul.v1.agent.model.NewService;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
/**
* @author Lomesh Patel
@@ -69,5 +69,7 @@ public class ConsulAutoRegistrationHealthCheckHeadersTests {
ConsulAutoConfiguration.class,
ConsulAutoServiceRegistrationAutoConfiguration.class })
public static class TestConfig {
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2017 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,6 +19,7 @@ package org.springframework.cloud.consul.serviceregistry;
import com.ecwid.consul.v1.agent.model.NewService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
@@ -66,5 +67,7 @@ public class ConsulAutoRegistrationHealthCheckTlsSkipVerifyTests {
ConsulAutoConfiguration.class,
ConsulAutoServiceRegistrationAutoConfiguration.class })
public static class TestConfig {
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2017 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,11 +16,14 @@
package org.springframework.cloud.consul.serviceregistry;
import java.util.Map;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.agent.model.Service;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
@@ -31,59 +34,62 @@ import org.springframework.cloud.consul.discovery.ConsulDiscoveryProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Map;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
/**
* @author Jon Freedman
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ConsulAutoServiceRegistrationDisabledTests.TestConfig.class,
properties = {"spring.application.name=myTestNotDeRegisteredService",
"spring.cloud.consul.discovery.instanceId=myTestNotDeRegisteredService-D",
"spring.cloud.consul.discovery.deregister=false"},
webEnvironment = RANDOM_PORT)
@SpringBootTest(classes = ConsulAutoServiceRegistrationDisabledTests.TestConfig.class, properties = {
"spring.application.name=myTestNotDeRegisteredService",
"spring.cloud.consul.discovery.instanceId=myTestNotDeRegisteredService-D",
"spring.cloud.consul.discovery.deregister=false" }, webEnvironment = RANDOM_PORT)
public class ConsulAutoServiceDeRegistrationDisabledTests {
@Autowired
private ConsulClient consul;
@Autowired(required = false)
private ConsulAutoServiceRegistration autoServiceRegistration;
@Autowired
private ConsulClient consul;
@Autowired(required = false)
private ConsulDiscoveryProperties discoveryProperties;
@Autowired(required = false)
private ConsulAutoServiceRegistration autoServiceRegistration;
@Test
public void contextLoads() {
assertNotNull("ConsulAutoServiceRegistration was not created", autoServiceRegistration);
assertNotNull("ConsulDiscoveryProperties was not created", discoveryProperties);
@Autowired(required = false)
private ConsulDiscoveryProperties discoveryProperties;
checkService(true);
autoServiceRegistration.deregister();
checkService(true);
discoveryProperties.setDeregister(true);
autoServiceRegistration.deregister();
checkService(false);
}
@Test
public void contextLoads() {
assertThat(this.autoServiceRegistration)
.as("ConsulAutoServiceRegistration was not created").isNotNull();
assertThat(this.discoveryProperties)
.as("ConsulDiscoveryProperties was not created").isNotNull();
private void checkService(final boolean expected) {
final Response<Map<String, Service>> response = consul.getAgentServices();
final Map<String, Service> services = response.getValue();
final Service service = services.get("myTestNotDeRegisteredService-D");
if (expected) {
assertNotNull("service was not registered", service);
} else {
assertNull("service was registered", service);
}
}
checkService(true);
this.autoServiceRegistration.deregister();
checkService(true);
this.discoveryProperties.setDeregister(true);
this.autoServiceRegistration.deregister();
checkService(false);
}
private void checkService(final boolean expected) {
final Response<Map<String, Service>> response = this.consul.getAgentServices();
final Map<String, Service> services = response.getValue();
final Service service = services.get("myTestNotDeRegisteredService-D");
if (expected) {
assertThat(service).as("service was not registered").isNotNull();
}
else {
assertThat(service).as("service was registered").isNull();
}
}
@Configuration
@EnableAutoConfiguration
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
ConsulAutoConfiguration.class,
ConsulAutoServiceRegistrationAutoConfiguration.class })
public static class TestConfig {
}
@Configuration
@EnableAutoConfiguration
@ImportAutoConfiguration({AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class,
ConsulAutoServiceRegistrationAutoConfiguration.class})
public static class TestConfig {
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2016 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,8 +18,12 @@ package org.springframework.cloud.consul.serviceregistry;
import java.util.Map;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.agent.model.Service;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
@@ -30,45 +34,45 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.StringUtils;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.agent.model.Service;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
/**
* @author Spencer Gibb
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ConsulAutoServiceRegistrationCustomizedAgentAddressTests.TestConfig.class,
properties = { "spring.application.name=myTestService-AA",
@SpringBootTest(classes = ConsulAutoServiceRegistrationCustomizedAgentAddressTests.TestConfig.class, properties = {
"spring.application.name=myTestService-AA",
"spring.cloud.consul.discovery.instanceId=myTestService1-AA",
"spring.cloud.consul.discovery.serviceName=myprefix-${spring.application.name}",
"spring.cloud.consul.discovery.preferAgentAddress=true"},
webEnvironment = RANDOM_PORT)
"spring.cloud.consul.discovery.preferAgentAddress=true" }, webEnvironment = RANDOM_PORT)
public class ConsulAutoServiceRegistrationCustomizedAgentAddressTests {
@Autowired
private ConsulClient consul;
@Test
public void contextLoads() {
Response<Map<String, Service>> response = consul.getAgentServices();
Response<Map<String, Service>> response = this.consul.getAgentServices();
Map<String, Service> services = response.getValue();
Service service = services.get("myTestService1-AA");
assertNotNull("service was null", service);
assertNotEquals("service port is 0", 0, service.getPort().intValue());
assertEquals("service id was wrong", "myTestService1-AA", service.getId());
assertEquals("service name was wrong", "myprefix-myTestService-AA", service.getService());
assertTrue("service address must be empty", StringUtils.isEmpty(service.getAddress()));
assertThat(service).as("service was null").isNotNull();
assertThat(service.getPort().intValue()).as("service port is 0").isNotEqualTo(0);
assertThat(service.getId()).as("service id was wrong")
.isEqualTo("myTestService1-AA");
assertThat(service.getService()).as("service name was wrong")
.isEqualTo("myprefix-myTestService-AA");
assertThat(StringUtils.isEmpty(service.getAddress()))
.as("service address must be empty").isTrue();
}
@Configuration
@EnableAutoConfiguration
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class, ConsulAutoServiceRegistrationAutoConfiguration.class })
public static class TestConfig { }
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
ConsulAutoConfiguration.class,
ConsulAutoServiceRegistrationAutoConfiguration.class })
public static class TestConfig {
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2017 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,10 +16,12 @@
package org.springframework.cloud.consul.serviceregistry;
import com.ecwid.consul.v1.agent.model.NewService;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
@@ -31,8 +33,6 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.SocketUtils;
import com.ecwid.consul.v1.agent.model.NewService;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.DEFINED_PORT;
@@ -40,9 +40,8 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
* @author Spencer Gibb
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ConsulAutoServiceRegistrationCustomizedDiscoveryPortTests.TestConfig.class,
properties = { "spring.application.name=myTestService-DiscoveryPort", },
webEnvironment = DEFINED_PORT)
@SpringBootTest(classes = ConsulAutoServiceRegistrationCustomizedDiscoveryPortTests.TestConfig.class, properties = {
"spring.application.name=myTestService-DiscoveryPort" }, webEnvironment = DEFINED_PORT)
public class ConsulAutoServiceRegistrationCustomizedDiscoveryPortTests {
@Autowired
@@ -73,17 +72,21 @@ public class ConsulAutoServiceRegistrationCustomizedDiscoveryPortTests {
NewService.Check check = service.getCheck();
assertThat(check).as("check was null").isNotNull();
String httpCheck = String.format("%s://%s:%s%s", properties.getScheme(),
properties.getHostname(), properties.getPort(),
properties.getHealthCheckPath());
String httpCheck = String.format("%s://%s:%s%s", this.properties.getScheme(),
this.properties.getHostname(), this.properties.getPort(),
this.properties.getHealthCheckPath());
assertThat(check.getHttp()).as("http check was wrong").isEqualTo(httpCheck);
// unable to call consul api to get health check details
}
@Configuration
@EnableAutoConfiguration
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class, ConsulAutoServiceRegistrationAutoConfiguration.class })
public static class TestConfig { }
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
ConsulAutoConfiguration.class,
ConsulAutoServiceRegistrationAutoConfiguration.class })
public static class TestConfig {
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2016 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,8 +19,13 @@ package org.springframework.cloud.consul.serviceregistry;
import java.util.List;
import java.util.Map;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.agent.model.Service;
import com.netflix.client.config.DefaultClientConfigImpl;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
@@ -33,26 +38,17 @@ import org.springframework.cloud.consul.discovery.ConsulServerList;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.agent.model.Service;
import com.netflix.client.config.DefaultClientConfigImpl;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
/**
* @author Jin Zhang
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ConsulAutoServiceRegistrationCustomizedInstanceGroupTests.TestConfig.class,
properties = { "spring.application.name=myTestService-WithGroup",
@SpringBootTest(classes = ConsulAutoServiceRegistrationCustomizedInstanceGroupTests.TestConfig.class, properties = {
"spring.application.name=myTestService-WithGroup",
"spring.cloud.consul.discovery.instanceId=myTestService1-WithGroup",
"spring.cloud.consul.discovery.instanceGroup=test"},
webEnvironment = RANDOM_PORT)
"spring.cloud.consul.discovery.instanceGroup=test" }, webEnvironment = RANDOM_PORT)
public class ConsulAutoServiceRegistrationCustomizedInstanceGroupTests {
@Autowired
@@ -63,27 +59,34 @@ public class ConsulAutoServiceRegistrationCustomizedInstanceGroupTests {
@Test
public void contextLoads() {
Response<Map<String, Service>> response = consul.getAgentServices();
Response<Map<String, Service>> response = this.consul.getAgentServices();
Map<String, Service> services = response.getValue();
Service service = services.get("myTestService1-WithGroup");
assertNotNull("service was null", service);
assertNotEquals("service port is 0", 0, service.getPort().intValue());
assertEquals("service id was wrong", "myTestService1-WithGroup", service.getId());
assertTrue("service group was wrong", service.getTags().contains("group=test"));
assertThat(service).as("service was null").isNotNull();
assertThat(service.getPort().intValue()).as("service port is 0").isNotEqualTo(0);
assertThat(service.getId()).as("service id was wrong")
.isEqualTo("myTestService1-WithGroup");
assertThat(service.getTags().contains("group=test")).as("service group was wrong")
.isTrue();
ConsulServerList serverList = new ConsulServerList(consul, properties);
ConsulServerList serverList = new ConsulServerList(this.consul, this.properties);
DefaultClientConfigImpl config = new DefaultClientConfigImpl();
config.setClientName("myTestService-WithGroup");
serverList.initWithNiwsConfig(config);
List<ConsulServer> servers = serverList.getInitialListOfServers();
assertEquals("servers was wrong size", 1, servers.size());
assertEquals("service group was wrong", "test", servers.get(0).getMetaInfo().getServerGroup());
assertThat(servers.size()).as("servers was wrong size").isEqualTo(1);
assertThat(servers.get(0).getMetaInfo().getServerGroup())
.as("service group was wrong").isEqualTo("test");
}
@Configuration
@EnableAutoConfiguration
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class, ConsulAutoServiceRegistrationAutoConfiguration.class })
public static class TestConfig { }
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
ConsulAutoConfiguration.class,
ConsulAutoServiceRegistrationAutoConfiguration.class })
public static class TestConfig {
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2016 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,8 +18,12 @@ package org.springframework.cloud.consul.serviceregistry;
import java.util.Map;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.agent.model.Service;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
@@ -29,26 +33,18 @@ import org.springframework.cloud.consul.ConsulAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.agent.model.Service;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
/**
* @author Sixian Liu
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ConsulAutoServiceRegistrationCustomizedInstanceZoneTests.TestConfig.class,
properties = { "spring.application.name=myTestService-WithZone",
@SpringBootTest(classes = ConsulAutoServiceRegistrationCustomizedInstanceZoneTests.TestConfig.class, properties = {
"spring.application.name=myTestService-WithZone",
"spring.cloud.consul.discovery.instanceId=myTestService1-WithZone",
"spring.cloud.consul.discovery.instanceZone=zone1",
"spring.cloud.consul.discovery.defaultZoneMetadataName=myZone"},
webEnvironment = RANDOM_PORT)
"spring.cloud.consul.discovery.defaultZoneMetadataName=myZone" }, webEnvironment = RANDOM_PORT)
public class ConsulAutoServiceRegistrationCustomizedInstanceZoneTests {
@Autowired
@@ -56,17 +52,24 @@ public class ConsulAutoServiceRegistrationCustomizedInstanceZoneTests {
@Test
public void contextLoads() {
Response<Map<String, Service>> response = consul.getAgentServices();
Response<Map<String, Service>> response = this.consul.getAgentServices();
Map<String, Service> services = response.getValue();
Service service = services.get("myTestService1-WithZone");
assertNotNull("service was null", service);
assertNotEquals("service port is 0", 0, service.getPort().intValue());
assertEquals("service id was wrong", "myTestService1-WithZone", service.getId());
assertTrue("service zone was wrong", service.getTags().contains("myZone=zone1"));
assertThat(service).as("service was null").isNotNull();
assertThat(service.getPort().intValue()).as("service port is 0").isNotEqualTo(0);
assertThat(service.getId()).as("service id was wrong")
.isEqualTo("myTestService1-WithZone");
assertThat(service.getTags().contains("myZone=zone1"))
.as("service zone was wrong").isTrue();
}
@Configuration
@EnableAutoConfiguration
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class, ConsulAutoServiceRegistrationAutoConfiguration.class })
public static class TestConfig { }
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
ConsulAutoConfiguration.class,
ConsulAutoServiceRegistrationAutoConfiguration.class })
public static class TestConfig {
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2016 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,16 +16,14 @@
package org.springframework.cloud.consul.serviceregistry;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertFalse;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
import java.util.Map;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.agent.model.Service;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.autoconfigure.web.server.ManagementServerProperties;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@@ -38,9 +36,8 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.StringUtils;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.agent.model.Service;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
/**
* @author Aleksandr Tarasov (aatarasov)
@@ -68,35 +65,37 @@ public class ConsulAutoServiceRegistrationCustomizedManagementServicePortTests {
@Test
public void contextLoads() {
final Response<Map<String, Service>> response = consul.getAgentServices();
final Response<Map<String, Service>> response = this.consul.getAgentServices();
final Map<String, Service> services = response.getValue();
final Service service = services.get("myTestService1-GG");
assertNotNull("service was null", service);
assertNotEquals("service port was 0", 0, service.getPort().intValue());
assertEquals("service id was wrong", "myTestService1-GG", service.getId());
assertEquals("service name was wrong", "myprefix-myTestService-GG",
service.getService());
assertFalse("service address must not be empty",
StringUtils.isEmpty(service.getAddress()));
assertEquals("service address must equals hostname from discovery properties",
discoveryProperties.getHostname(), service.getAddress());
assertThat(service).as("service was null").isNotNull();
assertThat(service.getPort().intValue()).as("service port was 0").isNotEqualTo(0);
assertThat(service.getId()).as("service id was wrong")
.isEqualTo("myTestService1-GG");
assertThat(service.getService()).as("service name was wrong")
.isEqualTo("myprefix-myTestService-GG");
assertThat(StringUtils.isEmpty(service.getAddress()))
.as("service address must not be empty").isFalse();
assertThat(service.getAddress())
.as("service address must equals hostname from discovery properties")
.isEqualTo(this.discoveryProperties.getHostname());
final Service managementService = services.get("myTestService1-GG-management");
assertNotNull("management service was null", managementService);
assertEquals("management service port is not 4452", 4452,
managementService.getPort().intValue());
assertEquals("management port is not 0", 0,
managementServerProperties.getPort().intValue());
assertEquals("management service id was wrong", "myTestService1-GG-management",
managementService.getId());
assertEquals("management service name was wrong",
"myprefix-myTestService-GG-management", managementService.getService());
assertFalse("management service address must not be empty",
StringUtils.isEmpty(managementService.getAddress()));
assertEquals(
"management service address must equals hostname from discovery properties",
discoveryProperties.getHostname(), managementService.getAddress());
assertThat(managementService).as("management service was null").isNotNull();
assertThat(managementService.getPort().intValue())
.as("management service port is not 4452").isEqualTo(4452);
assertThat(this.managementServerProperties.getPort().intValue())
.as("management port is not 0").isEqualTo(0);
assertThat(managementService.getId()).as("management service id was wrong")
.isEqualTo("myTestService1-GG-management");
assertThat(managementService.getService()).as("management service name was wrong")
.isEqualTo("myprefix-myTestService-GG-management");
assertThat(StringUtils.isEmpty(managementService.getAddress()))
.as("management service address must not be empty").isFalse();
assertThat(managementService.getAddress()).as(
"management service address must equals hostname from discovery properties")
.isEqualTo(this.discoveryProperties.getHostname());
}
@Configuration
@@ -105,5 +104,7 @@ public class ConsulAutoServiceRegistrationCustomizedManagementServicePortTests {
ConsulAutoConfiguration.class,
ConsulAutoServiceRegistrationAutoConfiguration.class })
public static class TestConfig {
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2016 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,8 +19,14 @@ package org.springframework.cloud.consul.serviceregistry;
import java.util.List;
import java.util.Map;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.QueryParams;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.agent.model.Service;
import com.ecwid.consul.v1.health.model.Check;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
@@ -31,18 +37,7 @@ import org.springframework.cloud.consul.discovery.ConsulDiscoveryProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.QueryParams;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.agent.model.Service;
import com.ecwid.consul.v1.health.model.Check;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
/**
@@ -50,15 +45,14 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
* @author Venil Noronha
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ConsulAutoServiceRegistrationCustomizedPropsTests.TestPropsConfig.class,
properties = { "spring.application.name=myTestService-B",
@SpringBootTest(classes = ConsulAutoServiceRegistrationCustomizedPropsTests.TestPropsConfig.class, properties = {
"spring.application.name=myTestService-B",
"spring.cloud.consul.discovery.instanceId=myTestService1-B",
"spring.cloud.consul.discovery.port=4452",
"spring.cloud.consul.discovery.hostname=myhost",
"spring.cloud.consul.discovery.ipAddress=10.0.0.1",
"spring.cloud.consul.discovery.registerHealthCheck=false",
"spring.cloud.consul.discovery.failFast=false" },
webEnvironment = RANDOM_PORT)
"spring.cloud.consul.discovery.failFast=false" }, webEnvironment = RANDOM_PORT)
public class ConsulAutoServiceRegistrationCustomizedPropsTests {
@Autowired
@@ -69,30 +63,42 @@ public class ConsulAutoServiceRegistrationCustomizedPropsTests {
@Test
public void contextLoads() {
Response<Map<String, Service>> response = consul.getAgentServices();
Response<Map<String, Service>> response = this.consul.getAgentServices();
Map<String, Service> services = response.getValue();
Service service = services.get("myTestService1-B");
assertThat("service was null", service, is(notNullValue()));
assertThat("service port is discovery port", service.getPort(), equalTo(4452));
assertThat("service id was wrong", "myTestService1-B", equalTo(service.getId()));
assertThat("service name was wrong", "myTestService-B", equalTo(service.getService()));
assertThat("property hostname was wrong", "myhost", equalTo(this.properties.getHostname()));
assertThat("property ipAddress was wrong", "10.0.0.1", equalTo(this.properties.getIpAddress()));
assertThat("service address was wrong", "myhost", equalTo(service.getAddress()));
assertThat(service).as("service was null").isNotNull();
assertThat(service.getPort()).as("service port is discovery port")
.isEqualTo(4452);
assertThat("myTestService1-B").as("service id was wrong")
.isEqualTo(service.getId());
assertThat("myTestService-B").as("service name was wrong")
.isEqualTo(service.getService());
assertThat("myhost").as("property hostname was wrong")
.isEqualTo(this.properties.getHostname());
assertThat("10.0.0.1").as("property ipAddress was wrong")
.isEqualTo(this.properties.getIpAddress());
assertThat("myhost").as("service address was wrong")
.isEqualTo(service.getAddress());
Response<List<Check>> checkResponse = consul.getHealthChecksForService("myTestService-B", QueryParams.DEFAULT);
Response<List<Check>> checkResponse = this.consul
.getHealthChecksForService("myTestService-B", QueryParams.DEFAULT);
List<Check> checks = checkResponse.getValue();
assertThat("checks was wrong size", checks, hasSize(0));
assertThat(checks).as("checks was wrong size").hasSize(0);
}
@Test
public void testFailFastDisabled() {
assertFalse("property failFast was wrong", this.properties.isFailFast());
assertThat(this.properties.isFailFast()).as("property failFast was wrong")
.isFalse();
}
@Configuration
@EnableAutoConfiguration
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class, ConsulAutoServiceRegistrationAutoConfiguration.class })
public static class TestPropsConfig { }
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
ConsulAutoConfiguration.class,
ConsulAutoServiceRegistrationAutoConfiguration.class })
public static class TestPropsConfig {
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2016 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,8 +18,12 @@ package org.springframework.cloud.consul.serviceregistry;
import java.util.Map;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.agent.model.Service;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
@@ -29,24 +33,17 @@ import org.springframework.cloud.consul.ConsulAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.agent.model.Service;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
/**
* @author Spencer Gibb
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ConsulAutoServiceRegistrationCustomizedServiceNameTests.TestConfig.class,
properties = { "spring.application.name=myTestService-CC",
@SpringBootTest(classes = ConsulAutoServiceRegistrationCustomizedServiceNameTests.TestConfig.class, properties = {
"spring.application.name=myTestService-CC",
"spring.cloud.consul.discovery.instanceId=myTestService1-CC",
"spring.cloud.consul.discovery.serviceName=myprefix-${spring.application.name}"},
webEnvironment = RANDOM_PORT)
"spring.cloud.consul.discovery.serviceName=myprefix-${spring.application.name}" }, webEnvironment = RANDOM_PORT)
public class ConsulAutoServiceRegistrationCustomizedServiceNameTests {
@Autowired
@@ -54,17 +51,24 @@ public class ConsulAutoServiceRegistrationCustomizedServiceNameTests {
@Test
public void contextLoads() {
Response<Map<String, Service>> response = consul.getAgentServices();
Response<Map<String, Service>> response = this.consul.getAgentServices();
Map<String, Service> services = response.getValue();
Service service = services.get("myTestService1-CC");
assertNotNull("service was null", service);
assertNotEquals("service port is 0", 0, service.getPort().intValue());
assertEquals("service id was wrong", "myTestService1-CC", service.getId());
assertEquals("service name was wrong", "myprefix-myTestService-CC", service.getService());
assertThat(service).as("service was null").isNotNull();
assertThat(service.getPort().intValue()).as("service port is 0").isNotEqualTo(0);
assertThat(service.getId()).as("service id was wrong")
.isEqualTo("myTestService1-CC");
assertThat(service.getService()).as("service name was wrong")
.isEqualTo("myprefix-myTestService-CC");
}
@Configuration
@EnableAutoConfiguration
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class, ConsulAutoServiceRegistrationAutoConfiguration.class })
public static class TestConfig { }
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
ConsulAutoConfiguration.class,
ConsulAutoServiceRegistrationAutoConfiguration.class })
public static class TestConfig {
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2016 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,8 +18,12 @@ package org.springframework.cloud.consul.serviceregistry;
import java.util.Map;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.agent.model.Service;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
@@ -27,10 +31,6 @@ import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.agent.model.Service;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
@@ -38,11 +38,10 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
* @author Piotr Wielgolaski
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ConsulAutoServiceRegistrationCustomizedServletContextTests.TestConfig.class,
properties = { "spring.application.name=myTestService-WithServletContext",
"spring.cloud.consul.discovery.instanceId=myTestService1-WithServletContext",
"server.servlet.context-path=/customContext"},
webEnvironment = RANDOM_PORT)
@SpringBootTest(classes = ConsulAutoServiceRegistrationCustomizedServletContextTests.TestConfig.class, properties = {
"spring.application.name=myTestService-WithServletContext",
"spring.cloud.consul.discovery.instanceId=myTestService1-WithServletContext",
"server.servlet.context-path=/customContext" }, webEnvironment = RANDOM_PORT)
public class ConsulAutoServiceRegistrationCustomizedServletContextTests {
@Autowired
@@ -50,17 +49,22 @@ public class ConsulAutoServiceRegistrationCustomizedServletContextTests {
@Test
public void contextLoads() {
Response<Map<String, Service>> response = consul.getAgentServices();
Response<Map<String, Service>> response = this.consul.getAgentServices();
Map<String, Service> services = response.getValue();
Service service = services.get("myTestService1-WithServletContext");
assertThat(service).as("service was null").isNotNull();
assertThat(service.getPort().intValue()).as("service port is 0").isNotEqualTo(0);
assertThat(service.getId()).as("service id was wrong").isEqualTo("myTestService1-WithServletContext");
assertThat(service.getTags()).as("contextPath tag missing").contains("contextPath=/customContext");
assertThat(service.getId()).as("service id was wrong")
.isEqualTo("myTestService1-WithServletContext");
assertThat(service.getTags()).as("contextPath tag missing")
.contains("contextPath=/customContext");
}
@EnableDiscoveryClient
@Configuration
@EnableAutoConfiguration
public static class TestConfig { }
public static class TestConfig {
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2016 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,6 +18,7 @@ package org.springframework.cloud.consul.serviceregistry;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@@ -30,16 +31,15 @@ import org.springframework.cloud.consul.discovery.ConsulDiscoveryProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
/**
* @author Marcin Biegan
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ConsulAutoServiceRegistrationCustomizedTests.MyTestConfig.class,
properties = { "spring.application.name=testCustomAutoServiceRegistration"},
webEnvironment = RANDOM_PORT)
@SpringBootTest(classes = ConsulAutoServiceRegistrationCustomizedTests.MyTestConfig.class, properties = {
"spring.application.name=testCustomAutoServiceRegistration" }, webEnvironment = RANDOM_PORT)
public class ConsulAutoServiceRegistrationCustomizedTests {
@Autowired
@@ -53,14 +53,19 @@ public class ConsulAutoServiceRegistrationCustomizedTests {
@Test
public void usesCustomConsulLifecycle() {
assertEquals("configuration is not customized", "customconfiguration", registration1.getConfiguration());
assertEquals("configuration is not customized", "customconfiguration", registration2.getConfiguration());
assertThat(this.registration1.getConfiguration())
.as("configuration is not customized").isEqualTo("customconfiguration");
assertThat(this.registration2.getConfiguration())
.as("configuration is not customized").isEqualTo("customconfiguration");
}
@SpringBootConfiguration
@EnableAutoConfiguration
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class, ConsulAutoServiceRegistrationAutoConfiguration.class })
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
ConsulAutoConfiguration.class,
ConsulAutoServiceRegistrationAutoConfiguration.class })
public static class MyTestConfig {
@Bean
public CustomAutoRegistration consulAutoServiceRegistration(
ConsulServiceRegistry serviceRegistry,
@@ -70,6 +75,7 @@ public class ConsulAutoServiceRegistrationCustomizedTests {
return new CustomAutoRegistration(serviceRegistry,
autoServiceRegistrationProperties, properties, registration);
}
}
public static class CustomAutoRegistration extends ConsulAutoServiceRegistration {
@@ -87,5 +93,7 @@ public class ConsulAutoServiceRegistrationCustomizedTests {
protected Object getConfiguration() {
return "customconfiguration";
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2017 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,16 +16,16 @@
package org.springframework.cloud.consul.serviceregistry;
import com.ecwid.consul.v1.ConsulClient;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.consul.discovery.ConsulDiscoveryProperties;
import org.springframework.cloud.consul.serviceregistry.ConsulAutoServiceRegistrationCustomizedPropsTests.TestPropsConfig;
import org.springframework.test.context.junit4.SpringRunner;
import com.ecwid.consul.v1.ConsulClient;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
@@ -34,13 +34,12 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
* @deprecated remove in Edgware
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestPropsConfig.class,
properties = { "spring.application.name=myTestServiceDefaultChecks",
"spring.cloud.consul.discovery.instanceId=myTestServiceDefaultChecks",
"spring.cloud.consul.discovery.healthCheckCriticalTimeout=30m",
"spring.cloud.consul.discovery.healthCheckInterval=19s",
"spring.cloud.consul.discovery.healthCheckTimeout=12s",
}, webEnvironment = RANDOM_PORT)
@SpringBootTest(classes = TestPropsConfig.class, properties = {
"spring.application.name=myTestServiceDefaultChecks",
"spring.cloud.consul.discovery.instanceId=myTestServiceDefaultChecks",
"spring.cloud.consul.discovery.healthCheckCriticalTimeout=30m",
"spring.cloud.consul.discovery.healthCheckInterval=19s",
"spring.cloud.consul.discovery.healthCheckTimeout=12s" }, webEnvironment = RANDOM_PORT)
public class ConsulAutoServiceRegistrationDefaultCheckTests {
@Autowired
@@ -51,19 +50,25 @@ public class ConsulAutoServiceRegistrationDefaultCheckTests {
@Test
public void contextLoads() {
assertThat(properties.getHealthCheckCriticalTimeout()).isEqualTo("30m");
assertThat(properties.getHealthCheckInterval()).isEqualTo("19s");
assertThat(properties.getHealthCheckTimeout()).isEqualTo("12s");
assertThat(this.properties.getHealthCheckCriticalTimeout()).isEqualTo("30m");
assertThat(this.properties.getHealthCheckInterval()).isEqualTo("19s");
assertThat(this.properties.getHealthCheckTimeout()).isEqualTo("12s");
// I'm unable to find a way to query consul to see the configuration of the health check
// so for now, just sending the new healthCheckCriticalTimeout and having consul accept
// I'm unable to find a way to query consul to see the configuration of the health
// check
// so for now, just sending the new healthCheckCriticalTimeout and having consul
// accept
// it is going to have to suffice
//final Response<List<com.ecwid.consul.v1.health.model.Check>> checksForService = consul.getHealthChecksForService("myTestServiceDefaultChecks", QueryParams.DEFAULT);
//final List<com.ecwid.consul.v1.health.model.Check> checkList = checksForService.getValue();
//final Response<Map<String, Check>> response2 = consul.getAgentChecks();
//final Map<String, Check> checks = response2.getValue();
//final Check check = checks.get("myTestServiceDefaultChecks");
//Assertions.assertThat(check).isNotNull();
// final Response<List<com.ecwid.consul.v1.health.model.Check>> checksForService =
// consul.getHealthChecksForService("myTestServiceDefaultChecks",
// QueryParams.DEFAULT);
// final List<com.ecwid.consul.v1.health.model.Check> checkList =
// checksForService.getValue();
// final Response<Map<String, Check>> response2 = consul.getAgentChecks();
// final Map<String, Check> checks = response2.getValue();
// final Check check = checks.get("myTestServiceDefaultChecks");
// Assertions.assertThat(check).isNotNull();
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2016 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,8 +18,12 @@ package org.springframework.cloud.consul.serviceregistry;
import java.util.Map;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.agent.model.Service;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
@@ -29,22 +33,16 @@ import org.springframework.cloud.consul.ConsulAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.agent.model.Service;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
/**
* @author Spencer Gibb
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ConsulAutoServiceRegistrationDefaultPortTests.TestConfig.class,
properties = { "spring.application.name=myTestService2-DD",
"spring.cloud.consul.discovery.instanceId=myTestService2-DD", },
webEnvironment = RANDOM_PORT)
@SpringBootTest(classes = ConsulAutoServiceRegistrationDefaultPortTests.TestConfig.class, properties = {
"spring.application.name=myTestService2-DD",
"spring.cloud.consul.discovery.instanceId=myTestService2-DD" }, webEnvironment = RANDOM_PORT)
public class ConsulAutoServiceRegistrationDefaultPortTests {
@Autowired
@@ -52,16 +50,20 @@ public class ConsulAutoServiceRegistrationDefaultPortTests {
@Test
public void contextLoads() {
Response<Map<String, Service>> response = consul.getAgentServices();
Response<Map<String, Service>> response = this.consul.getAgentServices();
Map<String, Service> services = response.getValue();
Service service = services.get("myTestService2-DD");
assertNotNull("service was null", service);
assertNotEquals("service port is 0", 0, service.getPort().intValue());
assertThat(service).as("service was null").isNotNull();
assertThat(service.getPort().intValue()).as("service port is 0").isNotEqualTo(0);
}
@Configuration
@EnableAutoConfiguration
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class, ConsulAutoServiceRegistrationAutoConfiguration.class })
public static class TestConfig { }
}
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
ConsulAutoConfiguration.class,
ConsulAutoServiceRegistrationAutoConfiguration.class })
public static class TestConfig {
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2016 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,8 +18,12 @@ package org.springframework.cloud.consul.serviceregistry;
import java.util.Map;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.agent.model.Service;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
@@ -29,21 +33,16 @@ import org.springframework.cloud.consul.ConsulAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.agent.model.Service;
import static org.junit.Assert.assertNull;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
/**
* @author Spencer Gibb
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ConsulAutoServiceRegistrationDisabledTests.TestConfig.class,
properties = { "spring.application.name=myTestNotRegisteredService2",
"spring.cloud.service-registry.auto-registration.enabled=false"},
webEnvironment = RANDOM_PORT)
@SpringBootTest(classes = ConsulAutoServiceRegistrationDisabledTests.TestConfig.class, properties = {
"spring.application.name=myTestNotRegisteredService2",
"spring.cloud.service-registry.auto-registration.enabled=false" }, webEnvironment = RANDOM_PORT)
public class ConsulAutoServiceRegistrationDisabledTests {
@Autowired
@@ -54,17 +53,22 @@ public class ConsulAutoServiceRegistrationDisabledTests {
@Test
public void contextLoads() {
assertNull("ConsulAutoServiceRegistration was created", autoServiceRegistration);
assertThat(this.autoServiceRegistration)
.as("ConsulAutoServiceRegistration was created").isNull();
Response<Map<String, Service>> response = consul.getAgentServices();
Response<Map<String, Service>> response = this.consul.getAgentServices();
Map<String, Service> services = response.getValue();
Service service = services.get("myTestNotRegisteredService2");
assertNull("service was registered", service);
assertThat(service).as("service was registered").isNull();
}
@Configuration
@EnableAutoConfiguration
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class,
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
ConsulAutoConfiguration.class,
ConsulAutoServiceRegistrationAutoConfiguration.class })
public static class TestConfig { }
public static class TestConfig {
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2016 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,9 +16,12 @@
package org.springframework.cloud.consul.serviceregistry;
import com.ecwid.consul.ConsulException;
import com.ecwid.consul.v1.ConsulClient;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
@@ -28,9 +31,6 @@ import org.springframework.cloud.consul.ConsulAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.test.annotation.DirtiesContext;
import com.ecwid.consul.ConsulException;
import com.ecwid.consul.v1.ConsulClient;
/**
* @author Spencer Gibb
* @author Venil Noronha
@@ -44,20 +44,25 @@ public class ConsulAutoServiceRegistrationFailFastTests {
@Test
public void testFailFastEnabled() {
this.exception.expect(ConsulException.class);
new SpringApplicationBuilder(TestConfig.class).properties("spring.application.name=testregistrationfails-fast",
"spring.jmx.default-domain=testautoregfailfast",
"server.port=0", "spring.cloud.consul.discovery.failFast=true").run();
new SpringApplicationBuilder(TestConfig.class)
.properties("spring.application.name=testregistrationfails-fast",
"spring.jmx.default-domain=testautoregfailfast", "server.port=0",
"spring.cloud.consul.discovery.failFast=true")
.run();
}
@SpringBootConfiguration
@EnableAutoConfiguration
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class, ConsulAutoServiceRegistrationAutoConfiguration.class })
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
ConsulAutoConfiguration.class,
ConsulAutoServiceRegistrationAutoConfiguration.class })
protected static class TestConfig {
@Bean
public ConsulClient consulClient() {
return new ConsulClient("localhost", 4321);
}
}
}
}
}

View File

@@ -16,10 +16,14 @@
package org.springframework.cloud.consul.serviceregistry;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import com.ecwid.consul.v1.agent.model.NewService;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
@@ -30,10 +34,7 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
/**
@@ -42,12 +43,10 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {
ConsulAutoServiceRegistrationManagementCustomizerTests.TestConfig.class,
ConsulAutoServiceRegistrationManagementCustomizerTests.ManagementConfig.class
}, properties = {
"spring.application.name=myTestService-SS",
"spring.cloud.consul.discovery.registerHealthCheck=false",
"management.server.port=4453"
}, webEnvironment = RANDOM_PORT)
ConsulAutoServiceRegistrationManagementCustomizerTests.ManagementConfig.class }, properties = {
"spring.application.name=myTestService-SS",
"spring.cloud.consul.discovery.registerHealthCheck=false",
"management.server.port=4453" }, webEnvironment = RANDOM_PORT)
public class ConsulAutoServiceRegistrationManagementCustomizerTests {
@Autowired
@@ -58,11 +57,17 @@ public class ConsulAutoServiceRegistrationManagementCustomizerTests {
@Test
public void contextLoads() {
ConsulAutoRegistration managementRegistration = autoRegistration.managementRegistration();
ConsulAutoRegistration managementRegistration = this.autoRegistration
.managementRegistration();
List<NewService.Check> checks = managementRegistration.getService().getChecks();
List<String> ttls = checks.stream().map(NewService.Check::getTtl).collect(Collectors.toList());
Assert.assertTrue("Management registration not customized with 'foo' customizer", ttls.contains("39s"));
Assert.assertTrue("Management registration not customized with 'bar' customizer", ttls.contains("36s"));
List<String> ttls = checks.stream().map(NewService.Check::getTtl)
.collect(Collectors.toList());
assertThat(ttls.contains("39s"))
.as("Management registration not customized with 'foo' customizer")
.isTrue();
assertThat(ttls.contains("36s"))
.as("Management registration not customized with 'bar' customizer")
.isTrue();
}
@Configuration
@@ -86,7 +91,8 @@ public class ConsulAutoServiceRegistrationManagementCustomizerTests {
NewService managementService = managementRegistration.getService();
NewService.Check check = new NewService.Check();
check.setTtl(ttl);
List<NewService.Check> checks = managementService.getChecks() != null ? new ArrayList<>(managementService.getChecks()) : new ArrayList<>();
List<NewService.Check> checks = managementService.getChecks() != null
? new ArrayList<>(managementService.getChecks()) : new ArrayList<>();
checks.add(check);
managementRegistration.getService().setChecks(checks);
}
@@ -95,11 +101,11 @@ public class ConsulAutoServiceRegistrationManagementCustomizerTests {
@Configuration
@EnableAutoConfiguration
@ImportAutoConfiguration({
AutoServiceRegistrationConfiguration.class,
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
ConsulAutoConfiguration.class,
ConsulAutoServiceRegistrationAutoConfiguration.class
})
ConsulAutoServiceRegistrationAutoConfiguration.class })
public static class TestConfig {
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2016 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,8 +18,12 @@ package org.springframework.cloud.consul.serviceregistry;
import java.util.Map;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.agent.model.Service;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
@@ -31,15 +35,7 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.StringUtils;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.agent.model.Service;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
/**
@@ -62,21 +58,24 @@ public class ConsulAutoServiceRegistrationManagementDisabledServiceTests {
@Test
public void contextLoads() {
Response<Map<String, Service>> response = consul.getAgentServices();
Response<Map<String, Service>> response = this.consul.getAgentServices();
Map<String, Service> services = response.getValue();
Service mgmtService = services.get("myTestService-NM-0-management");
assertNull("Management service was not null", mgmtService);
assertThat(mgmtService).as("Management service was not null").isNull();
Service service = services.get("myTestService1-NM");
assertNotNull("Service was not null", service);
assertNotEquals("service port was 0", 0, service.getPort().intValue());
assertEquals("service id was wrong", "myTestService1-NM", service.getId());
assertEquals("service name was wrong", "myTestService-NM", service.getService());
assertFalse("service address must not be empty",
StringUtils.isEmpty(service.getAddress()));
assertEquals("service address must equals hostname from discovery properties",
discoveryProperties.getHostname(), service.getAddress());
assertThat(service).as("Service was not null").isNotNull();
assertThat(service.getPort().intValue()).as("service port was 0").isNotEqualTo(0);
assertThat(service.getId()).as("service id was wrong")
.isEqualTo("myTestService1-NM");
assertThat(service.getService()).as("service name was wrong")
.isEqualTo("myTestService-NM");
assertThat(StringUtils.isEmpty(service.getAddress()))
.as("service address must not be empty").isFalse();
assertThat(service.getAddress())
.as("service address must equals hostname from discovery properties")
.isEqualTo(this.discoveryProperties.getHostname());
}
@@ -86,5 +85,7 @@ public class ConsulAutoServiceRegistrationManagementDisabledServiceTests {
ConsulAutoConfiguration.class,
ConsulAutoServiceRegistrationAutoConfiguration.class })
public static class TestConfig {
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2016 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,16 +16,14 @@
package org.springframework.cloud.consul.serviceregistry;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertFalse;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
import java.util.Map;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.agent.model.Service;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
@@ -37,9 +35,8 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.StringUtils;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.agent.model.Service;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
/**
* @author Aleksandr Tarasov (aatarasov)
@@ -60,32 +57,35 @@ public class ConsulAutoServiceRegistrationManagementServiceTests {
@Test
public void contextLoads() {
final Response<Map<String, Service>> response = consul.getAgentServices();
final Response<Map<String, Service>> response = this.consul.getAgentServices();
final Map<String, Service> services = response.getValue();
final Service service = services.get("myTestService-EE-0");
assertNotNull("service was null", service);
assertNotEquals("service port was 0", 0, service.getPort().intValue());
assertEquals("service id was wrong", "myTestService-EE-0", service.getId());
assertEquals("service name was wrong", "myTestService-EE", service.getService());
assertFalse("service address must not be empty",
StringUtils.isEmpty(service.getAddress()));
assertEquals("service address must equals hostname from discovery properties",
discoveryProperties.getHostname(), service.getAddress());
assertThat(service).as("service was null").isNotNull();
assertThat(service.getPort().intValue()).as("service port was 0").isNotEqualTo(0);
assertThat(service.getId()).as("service id was wrong")
.isEqualTo("myTestService-EE-0");
assertThat(service.getService()).as("service name was wrong")
.isEqualTo("myTestService-EE");
assertThat(StringUtils.isEmpty(service.getAddress()))
.as("service address must not be empty").isFalse();
assertThat(service.getAddress())
.as("service address must equals hostname from discovery properties")
.isEqualTo(this.discoveryProperties.getHostname());
final Service managementService = services.get("myTestService-EE-0-management");
assertNotNull("management service was null", managementService);
assertEquals("management service port was wrong", 4452,
managementService.getPort().intValue());
assertEquals("management service id was wrong", "myTestService-EE-0-management",
managementService.getId());
assertEquals("management service name was wrong", "myTestService-EE-management",
managementService.getService());
assertFalse("management service address must not be empty",
StringUtils.isEmpty(managementService.getAddress()));
assertEquals(
"management service address must equals hostname from discovery properties",
discoveryProperties.getHostname(), managementService.getAddress());
assertThat(managementService).as("management service was null").isNotNull();
assertThat(managementService.getPort().intValue())
.as("management service port was wrong").isEqualTo(4452);
assertThat(managementService.getId()).as("management service id was wrong")
.isEqualTo("myTestService-EE-0-management");
assertThat(managementService.getService()).as("management service name was wrong")
.isEqualTo("myTestService-EE-management");
assertThat(StringUtils.isEmpty(managementService.getAddress()))
.as("management service address must not be empty").isFalse();
assertThat(managementService.getAddress()).as(
"management service address must equals hostname from discovery properties")
.isEqualTo(this.discoveryProperties.getHostname());
}
@Configuration
@@ -94,5 +94,7 @@ public class ConsulAutoServiceRegistrationManagementServiceTests {
ConsulAutoConfiguration.class,
ConsulAutoServiceRegistrationAutoConfiguration.class })
public static class TestConfig {
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2016 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,8 +18,12 @@ package org.springframework.cloud.consul.serviceregistry;
import java.util.Map;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.agent.model.Service;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
@@ -27,21 +31,16 @@ import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.agent.model.Service;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE;
/**
* @author Spencer Gibb
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ConsulAutoServiceRegistrationNonWebTests.TestConfig.class,
properties = { "spring.application.name=consulNonWebTest", "server.port=32111" },
webEnvironment = NONE)
@SpringBootTest(classes = ConsulAutoServiceRegistrationNonWebTests.TestConfig.class, properties = {
"spring.application.name=consulNonWebTest",
"server.port=32111" }, webEnvironment = NONE)
public class ConsulAutoServiceRegistrationNonWebTests {
@Autowired
@@ -52,16 +51,22 @@ public class ConsulAutoServiceRegistrationNonWebTests {
@Test
public void contextLoads() {
assertNotNull("ConsulAutoServiceRegistration was created", autoServiceRegistration);
assertThat(this.autoServiceRegistration)
.as("ConsulAutoServiceRegistration was created").isNotNull();
Response<Map<String, Service>> response = consul.getAgentServices();
Response<Map<String, Service>> response = this.consul.getAgentServices();
Map<String, Service> services = response.getValue();
Service service = services.get("consulNonWebTest");
assertNull("service was registered", service); //no port to listen, hence no registration
assertThat(service).as("service was registered").isNull(); // no port to listen,
// hence no
// registration
}
@EnableDiscoveryClient
@Configuration
@EnableAutoConfiguration
public static class TestConfig { }
public static class TestConfig {
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2016 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -50,24 +50,30 @@ public class ConsulAutoServiceRegistrationRetryTests {
@Test
public void testRetry() {
this.exception.expect(ConsulException.class);
try (ConfigurableApplicationContext context = new SpringApplicationBuilder(TestConfig.class).properties("spring.application.name=testregistrationretry",
"spring.jmx.default-domain=testautoregretry",
"spring.cloud.consul.retry.max-attempts=2",
"logging.level.org.springframework.retry=DEBUG",
"server.port=0").run()) {
output.expect(Matchers.containsString("Retry: count="));
try (ConfigurableApplicationContext context = new SpringApplicationBuilder(
TestConfig.class)
.properties("spring.application.name=testregistrationretry",
"spring.jmx.default-domain=testautoregretry",
"spring.cloud.consul.retry.max-attempts=2",
"logging.level.org.springframework.retry=DEBUG",
"server.port=0")
.run()) {
this.output.expect(Matchers.containsString("Retry: count="));
}
}
@SpringBootConfiguration
@EnableAutoConfiguration
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class, ConsulAutoServiceRegistrationAutoConfiguration.class })
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
ConsulAutoConfiguration.class,
ConsulAutoServiceRegistrationAutoConfiguration.class })
protected static class TestConfig {
@Bean
public ConsulClient consulClient() {
return new ConsulClient("localhost", 4321);
}
}
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2016 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,8 +18,12 @@ package org.springframework.cloud.consul.serviceregistry;
import java.util.Map;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.agent.model.Service;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@@ -31,14 +35,7 @@ import org.springframework.cloud.consul.discovery.ConsulDiscoveryProperties;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.StringUtils;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.agent.model.Service;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
import static org.springframework.cloud.consul.serviceregistry.ConsulAutoRegistration.normalizeForDns;
@@ -47,8 +44,8 @@ import static org.springframework.cloud.consul.serviceregistry.ConsulAutoRegistr
* @author Venil Noronha
*/
@RunWith(SpringRunner.class)
@SpringBootTest(properties = { "spring.application.name=myTestService1-FF::something" },
webEnvironment = RANDOM_PORT)
@SpringBootTest(properties = {
"spring.application.name=myTestService1-FF::something" }, webEnvironment = RANDOM_PORT)
public class ConsulAutoServiceRegistrationTests {
@Autowired
@@ -62,23 +59,30 @@ public class ConsulAutoServiceRegistrationTests {
@Test
public void contextLoads() {
Response<Map<String, Service>> response = consul.getAgentServices();
Response<Map<String, Service>> response = this.consul.getAgentServices();
Map<String, Service> services = response.getValue();
Service service = services.get(registration.getInstanceId());
assertNotNull("service was null", service);
assertNotEquals("service port is 0", 0, service.getPort().intValue());
assertFalse("service id contained invalid character: " + service.getId(), service.getId().contains(":"));
assertEquals("service id was wrong", registration.getInstanceId(), service.getId());
assertEquals("service name was wrong", "myTestService1-FF-something", service.getService());
assertFalse("service address must not be empty", StringUtils.isEmpty(service.getAddress()));
assertEquals("service address must equals hostname from discovery properties", discoveryProperties.getHostname(), service.getAddress());
Service service = services.get(this.registration.getInstanceId());
assertThat(service).as("service was null").isNotNull();
assertThat(service.getPort().intValue()).as("service port is 0").isNotEqualTo(0);
assertThat(service.getId().contains(":"))
.as("service id contained invalid character: " + service.getId())
.isFalse();
assertThat(service.getId()).as("service id was wrong")
.isEqualTo(this.registration.getInstanceId());
assertThat(service.getService()).as("service name was wrong")
.isEqualTo("myTestService1-FF-something");
assertThat(StringUtils.isEmpty(service.getAddress()))
.as("service address must not be empty").isFalse();
assertThat(service.getAddress())
.as("service address must equals hostname from discovery properties")
.isEqualTo(this.discoveryProperties.getHostname());
}
@Test
public void normalizeForDnsWorks() {
assertEquals("abc1", normalizeForDns("abc1"));
assertEquals("ab-c1", normalizeForDns("ab:c1"));
assertEquals("ab-c1", normalizeForDns("ab::c1"));
assertThat(normalizeForDns("abc1")).isEqualTo("abc1");
assertThat(normalizeForDns("ab:c1")).isEqualTo("ab-c1");
assertThat(normalizeForDns("ab::c1")).isEqualTo("ab-c1");
}
@Test(expected = IllegalArgumentException.class)
@@ -98,7 +102,11 @@ public class ConsulAutoServiceRegistrationTests {
@SpringBootConfiguration
@EnableAutoConfiguration
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class, ConsulAutoServiceRegistrationAutoConfiguration.class })
protected static class TestConfig { }
}
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
ConsulAutoConfiguration.class,
ConsulAutoServiceRegistrationAutoConfiguration.class })
protected static class TestConfig {
}
}

View File

@@ -16,9 +16,13 @@
package org.springframework.cloud.consul.serviceregistry;
import java.lang.reflect.Field;
import java.util.Map;
import com.ecwid.consul.v1.agent.model.NewService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
@@ -31,11 +35,7 @@ import org.springframework.cloud.consul.discovery.TtlScheduler;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import java.lang.reflect.Field;
import java.util.Map;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Alexey Savchuk
@@ -43,8 +43,7 @@ import static org.junit.Assert.assertTrue;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ConsulServiceRegistryCheckTtlTests.TestConfig.class, properties = {
"spring.application.name=myTestService-S",
"spring.cloud.consul.discovery.heartbeat.enabled=true"
}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
"spring.cloud.consul.discovery.heartbeat.enabled=true" }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ConsulServiceRegistryCheckTtlTests {
@LocalServerPort
@@ -63,38 +62,42 @@ public class ConsulServiceRegistryCheckTtlTests {
private TtlScheduler ttlScheduler;
private ConsulRegistration createHttpRegistration() {
NewService service = registration.getService();
NewService service = this.registration.getService();
NewService.Check httpCheck = new NewService.Check();
httpCheck.setHttp(String.format(
"%s://%s:%s%s",
discoveryProperties.getScheme(),
discoveryProperties.getHostname(),
randomServerPort,
discoveryProperties.getHealthCheckPath()
));
httpCheck.setInterval(discoveryProperties.getHealthCheckInterval());
httpCheck.setHttp(
String.format("%s://%s:%s%s", this.discoveryProperties.getScheme(),
this.discoveryProperties.getHostname(), this.randomServerPort,
this.discoveryProperties.getHealthCheckPath()));
httpCheck.setInterval(this.discoveryProperties.getHealthCheckInterval());
NewService httpService = new NewService();
httpService.setId(service.getId() + "-http");
httpService.setName(service.getName() + "-http");
httpService.setCheck(httpCheck);
return new ConsulRegistration(httpService, discoveryProperties);
return new ConsulRegistration(httpService, this.discoveryProperties);
}
@Test
public void contextLoads() throws NoSuchFieldException, IllegalAccessException {
ConsulRegistration httpRegistration = createHttpRegistration();
consulServiceRegistry.register(httpRegistration);
Field serviceHeartbeatsField = TtlScheduler.class.getDeclaredField("serviceHeartbeats");
this.consulServiceRegistry.register(httpRegistration);
Field serviceHeartbeatsField = TtlScheduler.class
.getDeclaredField("serviceHeartbeats");
serviceHeartbeatsField.setAccessible(true);
Map serviceHeartbeats = (Map) serviceHeartbeatsField.get(ttlScheduler);
assertTrue("Service with heartbeat check not registered in TTL scheduler", serviceHeartbeats.keySet().contains(registration.getInstanceId()));
assertFalse("Service with HTTP check registered in TTL scheduler", serviceHeartbeats.keySet().contains(httpRegistration.getInstanceId()));
Map serviceHeartbeats = (Map) serviceHeartbeatsField.get(this.ttlScheduler);
assertThat(serviceHeartbeats.keySet().contains(this.registration.getInstanceId()))
.as("Service with heartbeat check not registered in TTL scheduler")
.isTrue();
assertThat(serviceHeartbeats.keySet().contains(httpRegistration.getInstanceId()))
.as("Service with HTTP check registered in TTL scheduler").isFalse();
}
@Configuration
@EnableAutoConfiguration
@ImportAutoConfiguration({AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class, ConsulAutoServiceRegistrationAutoConfiguration.class})
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
ConsulAutoConfiguration.class,
ConsulAutoServiceRegistrationAutoConfiguration.class })
protected static class TestConfig {
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2017 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,21 +19,21 @@ package org.springframework.cloud.consul.serviceregistry;
import java.util.Collections;
import java.util.List;
import com.ecwid.consul.v1.agent.model.NewService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.consul.discovery.ConsulDiscoveryClient;
import org.springframework.cloud.consul.discovery.ConsulDiscoveryProperties;
import org.springframework.test.context.junit4.SpringRunner;
import com.ecwid.consul.v1.agent.model.NewService;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
@@ -41,8 +41,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
* @author Spencer Gibb
*/
@RunWith(SpringRunner.class)
@SpringBootTest(properties = "spring.cloud.consul.discovery.query-passing=true",
webEnvironment = RANDOM_PORT)
@SpringBootTest(properties = "spring.cloud.consul.discovery.query-passing=true", webEnvironment = RANDOM_PORT)
public class ConsulServiceRegistryTests {
@Autowired(required = false)
@@ -63,7 +62,8 @@ public class ConsulServiceRegistryTests {
@Test
public void contextLoads() {
assertThat(autoRegistration).as("autoRegistration created erroneously").isNull();
assertThat(this.autoRegistration).as("autoRegistration created erroneously")
.isNull();
String serviceId = "myNonAutoRegisteredService";
@@ -71,28 +71,31 @@ public class ConsulServiceRegistryTests {
service.setAddress("localhost");
service.setId("myNonAutoRegisteredService-A1");
service.setName(serviceId);
service.setPort(port);
service.setPort(this.port);
service.setTags(Collections.singletonList("mytag"));
ConsulRegistration registration = new ConsulRegistration(service, this.properties);
ConsulRegistration registration = new ConsulRegistration(service,
this.properties);
Throwable t = null;
try {
serviceRegistry.register(registration);
this.serviceRegistry.register(registration);
assertHasInstance(serviceId);
assertStatus(registration, "UP");
// only works if query-passing = true
serviceRegistry.setStatus(registration, "OUT_OF_SERVICE");
this.serviceRegistry.setStatus(registration, "OUT_OF_SERVICE");
assertEmptyInstances(serviceId);
assertStatus(registration, "OUT_OF_SERVICE");
serviceRegistry.setStatus(registration, "UP");
this.serviceRegistry.setStatus(registration, "UP");
assertHasInstance(serviceId);
} catch (RuntimeException e) {
throw e ;
} finally {
serviceRegistry.deregister(registration);
}
catch (RuntimeException e) {
throw e;
}
finally {
this.serviceRegistry.deregister(registration);
if (t == null) { // just deregister, test already failed
assertEmptyInstances(serviceId);
}
@@ -101,12 +104,12 @@ public class ConsulServiceRegistryTests {
}
private void assertStatus(ConsulRegistration registration, String status) {
Object o = serviceRegistry.getStatus(registration);
Object o = this.serviceRegistry.getStatus(registration);
assertThat(o).isEqualTo(status);
}
private void assertHasInstance(String serviceId) {
List<ServiceInstance> instances = discoveryClient.getInstances(serviceId);
List<ServiceInstance> instances = this.discoveryClient.getInstances(serviceId);
assertThat(instances).hasSize(1);
ServiceInstance instance = instances.get(0);
@@ -114,13 +117,15 @@ public class ConsulServiceRegistryTests {
}
private void assertEmptyInstances(String serviceId) {
List<ServiceInstance> instances = discoveryClient.getInstances(serviceId);
List<ServiceInstance> instances = this.discoveryClient.getInstances(serviceId);
assertThat(instances).isEmpty();
}
@EnableDiscoveryClient(autoRegister = false)
@SpringBootConfiguration
@EnableAutoConfiguration
protected static class TestConfig { }
}
protected static class TestConfig {
}
}