Formatting

This commit is contained in:
spencergibb
2020-09-17 10:53:40 -04:00
parent 59507ee8bc
commit 249285ae11
106 changed files with 666 additions and 1186 deletions

View File

@@ -29,8 +29,7 @@ import org.springframework.util.Assert;
/**
* @author Spencer Gibb
*/
public class ConsulBinder
extends AbstractBinder<MessageChannel, ConsumerProperties, ProducerProperties> {
public class ConsulBinder extends AbstractBinder<MessageChannel, ConsumerProperties, ProducerProperties> {
private static final String BEAN_NAME_TEMPLATE = "outbound.%s";
@@ -41,10 +40,9 @@ public class ConsulBinder
}
@Override
protected Binding<MessageChannel> doBindConsumer(String name, String group,
MessageChannel inputChannel, ConsumerProperties properties) {
ConsulInboundMessageProducer messageProducer = new ConsulInboundMessageProducer(
this.eventService);
protected Binding<MessageChannel> doBindConsumer(String name, String group, MessageChannel inputChannel,
ConsumerProperties properties) {
ConsulInboundMessageProducer messageProducer = new ConsulInboundMessageProducer(this.eventService);
messageProducer.setOutputChannel(inputChannel);
messageProducer.setBeanFactory(this.getBeanFactory());
messageProducer.afterPropertiesSet();
@@ -59,11 +57,9 @@ public class ConsulBinder
Assert.isInstanceOf(SubscribableChannel.class, channel);
this.logger.debug("Binding Consul client to eventName " + name);
ConsulSendingHandler sendingHandler = new ConsulSendingHandler(
this.eventService.getConsulClient(), name);
ConsulSendingHandler sendingHandler = new ConsulSendingHandler(this.eventService.getConsulClient(), name);
EventDrivenConsumer consumer = new EventDrivenConsumer(
(SubscribableChannel) channel, sendingHandler);
EventDrivenConsumer consumer = new EventDrivenConsumer((SubscribableChannel) channel, sendingHandler);
consumer.setBeanFactory(getBeanFactory());
consumer.setBeanName(String.format(BEAN_NAME_TEMPLATE, name));
consumer.afterPropertiesSet();

View File

@@ -39,8 +39,7 @@ import static org.springframework.util.Base64Utils.decodeFromString;
*/
public class ConsulInboundMessageProducer extends MessageProducerSupport {
protected static final Log logger = LogFactory
.getLog(ConsulInboundMessageProducer.class);
protected static final Log logger = LogFactory.getLog(ConsulInboundMessageProducer.class);
private final ScheduledExecutorService scheduler;
@@ -81,8 +80,7 @@ public class ConsulInboundMessageProducer extends MessageProducerSupport {
@Override
protected void doStart() {
// TODO: make configurable
this.eventsHandle = this.scheduler.scheduleWithFixedDelay(this.eventsRunnable,
500, 500, TimeUnit.MILLISECONDS);
this.eventsHandle = this.scheduler.scheduleWithFixedDelay(this.eventsRunnable, 500, 500, TimeUnit.MILLISECONDS);
}
@Override

View File

@@ -56,8 +56,8 @@ public class ConsulSendingHandler extends AbstractMessageHandler {
// TODO: support headers
// TODO: support consul event filters: NodeFilter, ServiceFilter, TagFilter
Response<Event> event = this.consul.eventFire(this.eventName, (String) payload,
new EventParams(), QueryParams.DEFAULT);
Response<Event> event = this.consul.eventFire(this.eventName, (String) payload, new EventParams(),
QueryParams.DEFAULT);
// TODO: return event?
}

View File

@@ -44,8 +44,7 @@ public class EventService {
private AtomicReference<Long> lastIndex = new AtomicReference<>();
public EventService(ConsulBinderProperties properties, ConsulClient consul,
ObjectMapper objectMapper) {
public EventService(ConsulBinderProperties properties, ConsulClient consul, ObjectMapper objectMapper) {
this.properties = properties;
this.consul = consul;
this.objectMapper = objectMapper;
@@ -72,14 +71,12 @@ public class EventService {
}
public Event fire(String name, String payload) {
Response<Event> response = this.consul.eventFire(name, payload, new EventParams(),
QueryParams.DEFAULT);
Response<Event> response = this.consul.eventFire(name, payload, new EventParams(), QueryParams.DEFAULT);
return response.getValue();
}
public Response<List<Event>> getEventsResponse() {
return this.consul.eventList(EventListRequest.newBuilder()
.setQueryParams(QueryParams.DEFAULT).build());
return this.consul.eventList(EventListRequest.newBuilder().setQueryParams(QueryParams.DEFAULT).build());
}
public List<Event> getEvents() {
@@ -104,8 +101,8 @@ public class EventService {
if (this.properties != null) {
eventTimeout = this.properties.getEventTimeout();
}
Response<List<Event>> watch = this.consul.eventList(EventListRequest.newBuilder()
.setQueryParams(new QueryParams(eventTimeout, index)).build());
Response<List<Event>> watch = this.consul
.eventList(EventListRequest.newBuilder().setQueryParams(new QueryParams(eventTimeout, index)).build());
return filterEvents(readEvents(watch), lastIndex);
}

View File

@@ -53,8 +53,7 @@ public class ConsulBinderConfiguration {
@Bean
@ConditionalOnMissingBean
public EventService eventService(ConsulClient consulClient) {
return new EventService(null/* consulBinderProperties */, consulClient,
this.objectMapper);
return new EventService(null/* consulBinderProperties */, consulClient, this.objectMapper);
}
@Bean

View File

@@ -40,8 +40,7 @@ public class ConsulBinderProperties {
@Override
public String toString() {
return new ToStringCreator(this).append("eventTimeout", this.eventTimeout)
.toString();
return new ToStringCreator(this).append("eventTimeout", this.eventTimeout).toString();
}
}

View File

@@ -69,8 +69,7 @@ public class ConsulBinderApplicationTests {
@Before
public void setUp() throws Exception {
this.wireMock.stubFor(put(urlPathMatching("/v1/event/fire/purchases"))
.willReturn(aResponse().withStatus(200)));
this.wireMock.stubFor(put(urlPathMatching("/v1/event/fire/purchases")).willReturn(aResponse().withStatus(200)));
/*
* wireMock.stubFor(get(urlPathMatching("/v1/event/list"))
@@ -89,8 +88,7 @@ public class ConsulBinderApplicationTests {
public void shouldPublishTextConsulMessage() {
// given
final Message<String> message = MessageBuilder.withPayload("Hello Consul!")
.build();
final Message<String> message = MessageBuilder.withPayload("Hello Consul!").build();
// when
this.events.purchases().send(message);

View File

@@ -164,9 +164,7 @@ public class ConsulBinderTests {
if (groups != null) {
args.add(String.format("--group=%s", groups[i]));
}
consumers.add(
new AppId(launchApplication(TestConsumer.class, appProperties, args),
consumerPort));
consumers.add(new AppId(launchApplication(TestConsumer.class, appProperties, args), consumerPort));
}
for (AppId app : consumers) {
waitForConsumer(app.port);
@@ -191,8 +189,7 @@ public class ConsulBinderTests {
args.add(String.format("--partitioned=%b", false));
args.add("--debug");
return new AppId(launchApplication(TestProducer.class, appProperties, args),
producerPort);
return new AppId(launchApplication(TestProducer.class, appProperties, args), producerPort);
}
/**
@@ -222,8 +219,7 @@ public class ConsulBinderTests {
*/
private boolean isConsumerBound(int port) {
try {
return this.restTemplate.getForObject(
String.format("http://localhost:%d/is-bound", port), Boolean.class);
return this.restTemplate.getForObject(String.format("http://localhost:%d/is-bound", port), Boolean.class);
}
catch (ResourceAccessException e) {
logger.trace("isConsumerBound", e);
@@ -238,8 +234,7 @@ public class ConsulBinderTests {
*/
private String getConsumerMessagePayload(int port) {
try {
return this.restTemplate.getForObject(
String.format("http://localhost:%d/message-payload", port),
return this.restTemplate.getForObject(String.format("http://localhost:%d/message-payload", port),
String.class);
}
catch (ResourceAccessException e) {
@@ -255,8 +250,7 @@ public class ConsulBinderTests {
*/
private boolean partitionSelectorUsed(int port) {
try {
return this.restTemplate.getForObject(
String.format("http://localhost:%d/partition-strategy-invoked", port),
return this.restTemplate.getForObject(String.format("http://localhost:%d/partition-strategy-invoked", port),
Boolean.class);
}
catch (ResourceAccessException e) {
@@ -294,21 +288,17 @@ public class ConsulBinderTests {
* @param args the command line arguments for the application
* @return a string identifier for the application
*/
private String launchApplication(Class<?> clz, Map<String, String> properties,
List<String> args) {
Resource resource = new UrlResource(
clz.getProtectionDomain().getCodeSource().getLocation());
private String launchApplication(Class<?> clz, Map<String, String> properties, List<String> args) {
Resource resource = new UrlResource(clz.getProtectionDomain().getCodeSource().getLocation());
properties.put(AppDeployer.GROUP_PROPERTY_KEY, "test-group");
properties.put("main", clz.getName());
properties.put("classpath", System.getProperty("java.class.path"));
String appName = String.format("%s-%s", clz.getSimpleName(),
properties.get("server.port"));
String appName = String.format("%s-%s", clz.getSimpleName(), properties.get("server.port"));
AppDefinition definition = new AppDefinition(appName, properties);
AppDeploymentRequest request = new AppDeploymentRequest(definition, resource,
properties, args);
AppDeploymentRequest request = new AppDeploymentRequest(definition, resource, properties, args);
return this.deployer.deploy(request);
}
@@ -336,8 +326,7 @@ public class ConsulBinderTests {
* @param request the request
* @return the string[]
*/
protected String[] buildJarExecutionCommand(String jarPath,
AppDeploymentRequest request) {
protected String[] buildJarExecutionCommand(String jarPath, AppDeploymentRequest request) {
ArrayList<String> commands = new ArrayList<>();
commands.add(super.getLocalDeployerProperties().getJavaCmd());

View File

@@ -33,8 +33,7 @@ public class ConsulInboundMessageProducerTests {
EventService eventService = mock(EventService.class);
when(eventService.watch()).thenThrow(new OperationException(500, "error", ""));
ConsulInboundMessageProducer producer = new ConsulInboundMessageProducer(
eventService);
ConsulInboundMessageProducer producer = new ConsulInboundMessageProducer(eventService);
try {
producer.getEvents();

View File

@@ -43,8 +43,7 @@ public class ConsulBinderConfigurationTests {
@Ignore // FIXME 2.0.0 need stream fix
public void consulBinderDisabledWorks() {
this.exception.expectMessage(containsString("no proper implementation found"));
new SpringApplicationBuilder(Application.class)
.initializers(new ConsulTestcontainers())
new SpringApplicationBuilder(Application.class).initializers(new ConsulTestcontainers())
.properties("spring.cloud.consul.binder.enabled=false").run();
}
@@ -52,8 +51,7 @@ public class ConsulBinderConfigurationTests {
@Ignore // FIXME 2.0.0 need stream fix
public void consulDisabledDisablesBinder() {
this.exception.expectMessage(containsString("no proper implementation found"));
new SpringApplicationBuilder(Application.class)
.initializers(new ConsulTestcontainers())
new SpringApplicationBuilder(Application.class).initializers(new ConsulTestcontainers())
.properties("spring.cloud.consul.enabled=false").run();
}

View File

@@ -88,8 +88,7 @@ public class TestConsumer implements ApplicationRunner {
group = args.getOptionValues("group").get(0);
}
this.binder.bindConsumer(ConsulBinderTests.BINDING_NAME, group, consumerChannel,
new ConsumerProperties());
this.binder.bindConsumer(ConsulBinderTests.BINDING_NAME, group, consumerChannel, new ConsumerProperties());
this.isBound = true;
}

View File

@@ -68,10 +68,8 @@ public class TestProducer implements ApplicationRunner {
*/
SubscribableChannel producerChannel = producerChannel();
ProducerProperties properties = new ProducerProperties();
properties.setPartitionKeyExpression(
new SpelExpressionParser().parseExpression("payload"));
this.binder.bindProducer(ConsulBinderTests.BINDING_NAME, producerChannel,
properties);
properties.setPartitionKeyExpression(new SpelExpressionParser().parseExpression("payload"));
this.binder.bindProducer(ConsulBinderTests.BINDING_NAME, producerChannel, properties);
Message<String> message = new GenericMessage<>(ConsulBinderTests.MESSAGE_PAYLOAD);
logger.info("Writing message to binder {}", this.binder);
@@ -93,15 +91,13 @@ public class TestProducer implements ApplicationRunner {
return stubPartitionSelectorStrategy().invoked;
}
public static class StubPartitionSelectorStrategy
implements PartitionSelectorStrategy {
public static class StubPartitionSelectorStrategy implements PartitionSelectorStrategy {
public volatile boolean invoked = false;
@Override
public int selectPartition(Object key, int partitionCount) {
logger.info("Selecting partition for key {}; partition count: {}", key,
partitionCount);
logger.info("Selecting partition for key {}; partition count: {}", key, partitionCount);
this.invoked = true;
return 1;
}

View File

@@ -92,8 +92,8 @@ public class ConfigWatch implements ApplicationEventPublisherAware, SmartLifecyc
@Override
public void start() {
if (this.running.compareAndSet(false, true)) {
this.watchFuture = this.taskScheduler.scheduleWithFixedDelay(
this::watchConfigKeyValues, this.properties.getWatch().getDelay());
this.watchFuture = this.taskScheduler.scheduleWithFixedDelay(this::watchConfigKeyValues,
this.properties.getWatch().getDelay());
}
}
@@ -145,8 +145,7 @@ public class ConfigWatch implements ApplicationEventPublisherAware, SmartLifecyc
}
if (log.isTraceEnabled()) {
log.trace("watching consul for context '" + context + "' with index "
+ currentIndex);
log.trace("watching consul for context '" + context + "' with index " + currentIndex);
}
// use the consul ACL token if found
@@ -155,9 +154,8 @@ public class ConfigWatch implements ApplicationEventPublisherAware, SmartLifecyc
aclToken = null;
}
Response<List<GetValue>> response = this.consul.getKVValues(context,
aclToken, new QueryParams(
this.properties.getWatch().getWaitTime(), currentIndex));
Response<List<GetValue>> response = this.consul.getKVValues(context, aclToken,
new QueryParams(this.properties.getWatch().getWaitTime(), currentIndex));
// if response.value == null, response was a 404, otherwise it was a
// 200, reducing churn if there wasn't anything
@@ -167,20 +165,15 @@ public class ConfigWatch implements ApplicationEventPublisherAware, SmartLifecyc
if (newIndex != null && !newIndex.equals(currentIndex)) {
// don't publish the same index again, don't publish the first
// time (-1) so index can be primed
if (!this.consulIndexes.containsValue(newIndex)
&& !currentIndex.equals(-1L)) {
if (!this.consulIndexes.containsValue(newIndex) && !currentIndex.equals(-1L)) {
if (log.isTraceEnabled()) {
log.trace("Context " + context + " has new index "
+ newIndex);
log.trace("Context " + context + " has new index " + newIndex);
}
RefreshEventData data = new RefreshEventData(context,
currentIndex, newIndex);
this.publisher.publishEvent(
new RefreshEvent(this, data, data.toString()));
RefreshEventData data = new RefreshEventData(context, currentIndex, newIndex);
this.publisher.publishEvent(new RefreshEvent(this, data, data.toString()));
}
else if (log.isTraceEnabled()) {
log.trace("Event for index already published for context "
+ context);
log.trace("Event for index already published for context " + context);
}
this.consulIndexes.put(context, newIndex);
}
@@ -196,19 +189,17 @@ public class ConfigWatch implements ApplicationEventPublisherAware, SmartLifecyc
catch (Exception e) {
// only fail fast on the initial query, otherwise just log the error
if (this.firstTime && this.properties.isFailFast()) {
log.error(
"Fail fast is set and there was an error reading configuration from consul.");
log.error("Fail fast is set and there was an error reading configuration from consul.");
ReflectionUtils.rethrowRuntimeException(e);
}
else if (log.isTraceEnabled()) {
log.trace("Error querying consul Key/Values for context '" + context
+ "'", e);
log.trace("Error querying consul Key/Values for context '" + context + "'", e);
}
else if (log.isWarnEnabled()) {
// simplified one line log message in the event of an agent
// failure
log.warn("Error querying consul Key/Values for context '" + context
+ "'. Message: " + e.getMessage());
log.warn("Error querying consul Key/Values for context '" + context + "'. Message: "
+ e.getMessage());
}
}
}
@@ -250,8 +241,7 @@ public class ConfigWatch implements ApplicationEventPublisherAware, SmartLifecyc
return false;
}
RefreshEventData that = (RefreshEventData) o;
return Objects.equals(this.context, that.context)
&& Objects.equals(this.prevIndex, that.prevIndex)
return Objects.equals(this.context, that.context) && Objects.equals(this.prevIndex, that.prevIndex)
&& Objects.equals(this.newIndex, that.newIndex);
}
@@ -262,9 +252,8 @@ public class ConfigWatch implements ApplicationEventPublisherAware, SmartLifecyc
@Override
public String toString() {
return new ToStringCreator(this).append("context", this.context)
.append("prevIndex", this.prevIndex).append("newIndex", this.newIndex)
.toString();
return new ToStringCreator(this).append("context", this.context).append("prevIndex", this.prevIndex)
.append("newIndex", this.newIndex).toString();
}
}

View File

@@ -53,17 +53,14 @@ public class ConsulConfigAutoConfiguration {
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(RefreshEndpoint.class)
@ConditionalOnProperty(name = "spring.cloud.consul.config.watch.enabled",
matchIfMissing = true)
@ConditionalOnProperty(name = "spring.cloud.consul.config.watch.enabled", matchIfMissing = true)
protected static class ConsulRefreshConfiguration {
@Bean
@ConditionalOnBean(ConsulConfigIndexes.class)
public ConfigWatch configWatch(ConsulConfigProperties properties,
ConsulConfigIndexes indexes, ConsulClient consul,
@Qualifier(CONFIG_WATCH_TASK_SCHEDULER_NAME) TaskScheduler taskScheduler) {
return new ConfigWatch(properties, consul, indexes.getIndexes(),
taskScheduler);
public ConfigWatch configWatch(ConsulConfigProperties properties, ConsulConfigIndexes indexes,
ConsulClient consul, @Qualifier(CONFIG_WATCH_TASK_SCHEDULER_NAME) TaskScheduler taskScheduler) {
return new ConfigWatch(properties, consul, indexes.getIndexes(), taskScheduler);
}
@Bean(name = CONFIG_WATCH_TASK_SCHEDULER_NAME)

View File

@@ -39,8 +39,7 @@ public class ConsulConfigBootstrapConfiguration {
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties
@Import(ConsulAutoConfiguration.class)
@ConditionalOnProperty(name = "spring.cloud.consul.config.enabled",
matchIfMissing = true)
@ConditionalOnProperty(name = "spring.cloud.consul.config.enabled", matchIfMissing = true)
protected static class ConsulPropertySourceConfiguration {
@Autowired
@@ -53,8 +52,7 @@ public class ConsulConfigBootstrapConfiguration {
}
@Bean
public ConsulPropertySourceLocator consulPropertySourceLocator(
ConsulConfigProperties consulConfigProperties) {
public ConsulPropertySourceLocator consulPropertySourceLocator(ConsulConfigProperties consulConfigProperties) {
return new ConsulPropertySourceLocator(this.consul, consulConfigProperties);
}

View File

@@ -32,26 +32,23 @@ import org.springframework.boot.env.BootstrapRegistry.Registration;
import static org.springframework.cloud.consul.config.ConsulConfigProperties.Format.FILES;
public class ConsulConfigDataLoader
implements ConfigDataLoader<ConsulConfigDataLocation> {
public class ConsulConfigDataLoader implements ConfigDataLoader<ConsulConfigDataLocation> {
private static final Log log = LogFactory.getLog(ConsulConfigDataLoader.class);
@Override
public ConfigData load(ConfigDataLoaderContext context,
ConsulConfigDataLocation location) {
public ConfigData load(ConfigDataLoaderContext context, ConsulConfigDataLocation location) {
try {
ConsulClient consul = getBean(context, ConsulClient.class);
ConsulConfigProperties properties = location.getProperties();
ConsulPropertySource propertySource = null;
if (properties.getFormat() == FILES) {
Response<GetValue> response = consul.getKVValue(location.getContext(),
properties.getAclToken());
Response<GetValue> response = consul.getKVValue(location.getContext(), properties.getAclToken());
addIndex(context, location, response.getConsulIndex());
if (response.getValue() != null) {
ConsulFilesPropertySource filesPropertySource = new ConsulFilesPropertySource(
location.getContext(), consul, properties);
ConsulFilesPropertySource filesPropertySource = new ConsulFilesPropertySource(location.getContext(),
consul, properties);
filesPropertySource.init(response.getValue());
propertySource = filesPropertySource;
}
@@ -79,26 +76,22 @@ public class ConsulConfigDataLoader
}
protected <T> T getBean(ConfigDataLoaderContext context, Class<T> type) {
Registration<T> registration = context.getBootstrapRegistry()
.getRegistration(type);
Registration<T> registration = context.getBootstrapRegistry().getRegistration(type);
if (registration == null) {
return null;
}
return registration.get();
}
protected ConsulPropertySource create(ConfigDataLoaderContext context,
ConsulConfigDataLocation location) {
ConsulPropertySource propertySource = new ConsulPropertySource(
location.getContext(), getBean(context, ConsulClient.class),
location.getProperties());
protected ConsulPropertySource create(ConfigDataLoaderContext context, ConsulConfigDataLocation location) {
ConsulPropertySource propertySource = new ConsulPropertySource(location.getContext(),
getBean(context, ConsulClient.class), location.getProperties());
propertySource.init();
addIndex(context, location, propertySource.getInitialIndex());
return propertySource;
}
private void addIndex(ConfigDataLoaderContext context,
ConsulConfigDataLocation location, Long consulIndex) {
private void addIndex(ConfigDataLoaderContext context, ConsulConfigDataLocation location, Long consulIndex) {
ConsulConfigIndexes indexes = getBean(context, ConsulConfigIndexes.class);
if (indexes != null) { // should never be the case
indexes.getIndexes().put(location.getContext(), consulIndex);

View File

@@ -29,8 +29,7 @@ public class ConsulConfigDataLocation extends ConfigDataLocation {
private final boolean optional;
public ConsulConfigDataLocation(ConsulConfigProperties properties, String context,
boolean optional) {
public ConsulConfigDataLocation(ConsulConfigProperties properties, String context, boolean optional) {
this.properties = properties;
this.context = context;
this.optional = optional;
@@ -68,8 +67,8 @@ public class ConsulConfigDataLocation extends ConfigDataLocation {
@Override
public String toString() {
return new ToStringCreator(this).append("context", context)
.append("optional", optional).append("properties", properties).toString();
return new ToStringCreator(this).append("context", context).append("optional", optional)
.append("properties", properties).toString();
}

View File

@@ -42,8 +42,7 @@ import org.springframework.web.util.UriComponentsBuilder;
import static org.springframework.cloud.consul.config.ConsulConfigProperties.Format.FILES;
public class ConsulConfigDataLocationResolver
implements ConfigDataLocationResolver<ConsulConfigDataLocation> {
public class ConsulConfigDataLocationResolver implements ConfigDataLocationResolver<ConsulConfigDataLocation> {
/**
* Consul ConfigData prefix.
@@ -56,55 +55,44 @@ public class ConsulConfigDataLocationResolver
.unmodifiableList(Arrays.asList(".yml", ".yaml", ".properties"));
@Override
public boolean isResolvable(ConfigDataLocationResolverContext context,
String location) {
public boolean isResolvable(ConfigDataLocationResolverContext context, String location) {
if (!location.startsWith(PREFIX)) {
return false;
}
// only bind if correct prefix
boolean enabled = context.getBinder()
.bind(ConsulProperties.PREFIX + ".enabled", Boolean.class).orElse(true);
boolean configEnabled = context.getBinder()
.bind(ConsulConfigProperties.PREFIX + ".enabled", Boolean.class)
boolean enabled = context.getBinder().bind(ConsulProperties.PREFIX + ".enabled", Boolean.class).orElse(true);
boolean configEnabled = context.getBinder().bind(ConsulConfigProperties.PREFIX + ".enabled", Boolean.class)
.orElse(true);
return configEnabled && enabled;
}
@Override
public List<ConsulConfigDataLocation> resolve(
ConfigDataLocationResolverContext context, String location, boolean optional)
throws ConfigDataLocationNotFoundException {
public List<ConsulConfigDataLocation> resolve(ConfigDataLocationResolverContext context, String location,
boolean optional) throws ConfigDataLocationNotFoundException {
return Collections.emptyList();
}
@Override
public List<ConsulConfigDataLocation> resolveProfileSpecific(
ConfigDataLocationResolverContext context, String location, boolean optional,
Profiles profiles) throws ConfigDataLocationNotFoundException {
public List<ConsulConfigDataLocation> resolveProfileSpecific(ConfigDataLocationResolverContext context,
String location, boolean optional, Profiles profiles) throws ConfigDataLocationNotFoundException {
UriComponents locationUri = parseLocation(context, location);
ConsulConfigProperties properties = loadConfigProperties(context.getBinder(),
locationUri);
ConsulConfigProperties properties = loadConfigProperties(context.getBinder(), locationUri);
List<String> contexts = (locationUri == null
|| CollectionUtils.isEmpty(locationUri.getPathSegments()))
? getAutomaticContexts(profiles, properties)
: getCustomContexts(locationUri, properties);
List<String> contexts = (locationUri == null || CollectionUtils.isEmpty(locationUri.getPathSegments()))
? getAutomaticContexts(profiles, properties) : getCustomContexts(locationUri, properties);
registerBean(context, ConsulClient.class,
() -> createConsulClient(context, locationUri));
registerBean(context, ConsulClient.class, () -> createConsulClient(context, locationUri));
registerBean(context, ConsulConfigIndexes.class, ConsulConfigDataIndexes::new);
return contexts.stream()
.map(propertySourceContext -> new ConsulConfigDataLocation(properties,
propertySourceContext, optional))
.map(propertySourceContext -> new ConsulConfigDataLocation(properties, propertySourceContext, optional))
.collect(Collectors.toList());
}
private List<String> getCustomContexts(UriComponents uriComponents,
ConsulConfigProperties properties) {
private List<String> getCustomContexts(UriComponents uriComponents, ConsulConfigProperties properties) {
if (StringUtils.isEmpty(uriComponents.getPath())) {
return Collections.emptyList();
}
@@ -126,8 +114,7 @@ public class ConsulConfigDataLocationResolver
return DIR_SUFFIXES;
}
protected List<String> getAutomaticContexts(Profiles profiles,
ConsulConfigProperties properties) {
protected List<String> getAutomaticContexts(Profiles profiles, ConsulConfigProperties properties) {
List<String> contexts = new ArrayList<>();
String prefix = properties.getPrefix();
@@ -162,17 +149,15 @@ public class ConsulConfigDataLocationResolver
}
}
protected void addProfiles(List<String> contexts, String baseContext,
Profiles profiles, String suffix, ConsulConfigProperties properties) {
protected void addProfiles(List<String> contexts, String baseContext, Profiles profiles, String suffix,
ConsulConfigProperties properties) {
for (String profile : profiles.getAccepted()) {
contexts.add(
baseContext + properties.getProfileSeparator() + profile + suffix);
contexts.add(baseContext + properties.getProfileSeparator() + profile + suffix);
}
}
@Nullable
protected UriComponents parseLocation(ConfigDataLocationResolverContext context,
String location) {
protected UriComponents parseLocation(ConfigDataLocationResolverContext context, String location) {
String uri = location.substring(PREFIX.length());
if (!StringUtils.hasText(uri)) {
return null;
@@ -186,23 +171,19 @@ public class ConsulConfigDataLocationResolver
return UriComponentsBuilder.fromUriString(uri).build();
}
protected <T> void registerBean(ConfigDataLocationResolverContext context,
Class<T> type, Supplier<T> supplier) {
protected <T> void registerBean(ConfigDataLocationResolverContext context, Class<T> type, Supplier<T> supplier) {
context.getBootstrapRegistry().register(type, supplier)
.onApplicationContextPrepared(
(ctxt, consulClient) -> ctxt.getBeanFactory().registerSingleton(
"configData" + type.getSimpleName(), consulClient));
.onApplicationContextPrepared((ctxt, consulClient) -> ctxt.getBeanFactory()
.registerSingleton("configData" + type.getSimpleName(), consulClient));
}
protected ConsulClient createConsulClient(ConfigDataLocationResolverContext context,
UriComponents location) {
protected ConsulClient createConsulClient(ConfigDataLocationResolverContext context, UriComponents location) {
ConsulProperties properties = loadProperties(context.getBinder(), location);
return ConsulAutoConfiguration.createConsulClient(properties);
}
protected ConsulProperties loadProperties(Binder binder, UriComponents location) {
ConsulProperties consulProperties = binder
.bind(ConsulProperties.PREFIX, Bindable.of(ConsulProperties.class))
ConsulProperties consulProperties = binder.bind(ConsulProperties.PREFIX, Bindable.of(ConsulProperties.class))
.orElse(new ConsulProperties());
if (location != null) {
@@ -217,16 +198,13 @@ public class ConsulConfigDataLocationResolver
return consulProperties;
}
protected ConsulConfigProperties loadConfigProperties(Binder binder,
UriComponents location) {
protected ConsulConfigProperties loadConfigProperties(Binder binder, UriComponents location) {
ConsulConfigProperties properties = binder
.bind(ConsulConfigProperties.PREFIX,
Bindable.of(ConsulConfigProperties.class))
.bind(ConsulConfigProperties.PREFIX, Bindable.of(ConsulConfigProperties.class))
.orElse(new ConsulConfigProperties());
if (StringUtils.isEmpty(properties.getName())) {
properties.setName(binder.bind("spring.application.name", String.class)
.orElse("application"));
properties.setName(binder.bind("spring.application.name", String.class).orElse("application"));
}
return properties;
}

View File

@@ -166,13 +166,10 @@ public class ConsulConfigProperties {
@Override
public String toString() {
return new ToStringCreator(this).append("enabled", this.enabled)
.append("prefix", this.prefix)
.append("defaultContext", this.defaultContext)
.append("profileSeparator", this.profileSeparator)
.append("format", this.format).append("dataKey", this.dataKey)
.append("aclToken", this.aclToken).append("watch", this.watch)
.append("failFast", this.failFast).append("name", this.name).toString();
return new ToStringCreator(this).append("enabled", this.enabled).append("prefix", this.prefix)
.append("defaultContext", this.defaultContext).append("profileSeparator", this.profileSeparator)
.append("format", this.format).append("dataKey", this.dataKey).append("aclToken", this.aclToken)
.append("watch", this.watch).append("failFast", this.failFast).append("name", this.name).toString();
}
/**
@@ -273,9 +270,8 @@ public class ConsulConfigProperties {
@Override
public String toString() {
return new ToStringCreator(this).append("waitTime", this.waitTime)
.append("enabled", this.enabled).append("delay", this.delay)
.toString();
return new ToStringCreator(this).append("waitTime", this.waitTime).append("enabled", this.enabled)
.append("delay", this.delay).toString();
}
}

View File

@@ -27,8 +27,7 @@ import static org.springframework.cloud.consul.config.ConsulConfigProperties.For
*/
public class ConsulFilesPropertySource extends ConsulPropertySource {
public ConsulFilesPropertySource(String context, ConsulClient source,
ConsulConfigProperties configProperties) {
public ConsulFilesPropertySource(String context, ConsulClient source, ConsulConfigProperties configProperties) {
super(context, source, configProperties);
}
@@ -45,8 +44,7 @@ public class ConsulFilesPropertySource extends ConsulPropertySource {
parseValue(value, PROPERTIES);
}
else {
throw new IllegalStateException(
"Unknown files extension for context " + this.getContext());
throw new IllegalStateException("Unknown files extension for context " + this.getContext());
}
}

View File

@@ -52,8 +52,7 @@ public class ConsulPropertySource extends EnumerablePropertySource<ConsulClient>
private Long initialIndex;
public ConsulPropertySource(String context, ConsulClient source,
ConsulConfigProperties configProperties) {
public ConsulPropertySource(String context, ConsulClient source, ConsulConfigProperties configProperties) {
super(context, source);
this.context = context;
this.configProperties = configProperties;
@@ -65,8 +64,8 @@ public class ConsulPropertySource extends EnumerablePropertySource<ConsulClient>
this.context = this.context + "/";
}
Response<List<GetValue>> response = this.source.getKVValues(this.context,
this.configProperties.getAclToken(), QueryParams.DEFAULT);
Response<List<GetValue>> response = this.source.getKVValues(this.context, this.configProperties.getAclToken(),
QueryParams.DEFAULT);
this.initialIndex = response.getConsulIndex();
@@ -112,8 +111,7 @@ public class ConsulPropertySource extends EnumerablePropertySource<ConsulClient>
* @param values values to parse
* @param format format in which the values should be parsed
*/
protected void parsePropertiesWithNonKeyValueFormat(List<GetValue> values,
ConsulConfigProperties.Format format) {
protected void parsePropertiesWithNonKeyValueFormat(List<GetValue> values, ConsulConfigProperties.Format format) {
if (values == null) {
return;
}
@@ -139,8 +137,7 @@ public class ConsulPropertySource extends EnumerablePropertySource<ConsulClient>
}
}
protected Properties generateProperties(String value,
ConsulConfigProperties.Format format) {
protected Properties generateProperties(String value, ConsulConfigProperties.Format format) {
final Properties props = new Properties();
if (format == PROPERTIES) {
@@ -150,16 +147,14 @@ public class ConsulPropertySource extends EnumerablePropertySource<ConsulClient>
props.load(new ByteArrayInputStream(value.getBytes("ISO-8859-1")));
}
catch (IOException e) {
throw new IllegalArgumentException(
value + " can't be encoded using ISO-8859-1");
throw new IllegalArgumentException(value + " can't be encoded using ISO-8859-1");
}
return props;
}
else if (format == YAML) {
final YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
yaml.setResources(
new ByteArrayResource(value.getBytes(Charset.forName("UTF-8"))));
yaml.setResources(new ByteArrayResource(value.getBytes(Charset.forName("UTF-8"))));
return yaml.getObject();
}

View File

@@ -46,8 +46,7 @@ import static org.springframework.cloud.consul.config.ConsulConfigProperties.For
* @author Spencer Gibb
*/
@Order(0)
public class ConsulPropertySourceLocator
implements PropertySourceLocator, ConsulConfigIndexes {
public class ConsulPropertySourceLocator implements PropertySourceLocator, ConsulConfigIndexes {
private static final Log log = LogFactory.getLog(ConsulPropertySourceLocator.class);
@@ -59,8 +58,7 @@ public class ConsulPropertySourceLocator
private final LinkedHashMap<String, Long> contextIndex = new LinkedHashMap<>();
public ConsulPropertySourceLocator(ConsulClient consul,
ConsulConfigProperties properties) {
public ConsulPropertySourceLocator(ConsulClient consul, ConsulConfigProperties properties) {
this.consul = consul;
this.properties = properties;
}
@@ -106,8 +104,7 @@ public class ConsulPropertySourceLocator
suffixes.add(".properties");
}
String defaultContext = getContext(prefix,
this.properties.getDefaultContext());
String defaultContext = getContext(prefix, this.properties.getDefaultContext());
for (String suffix : suffixes) {
this.contexts.add(defaultContext + suffix);
@@ -133,8 +130,8 @@ public class ConsulPropertySourceLocator
try {
ConsulPropertySource propertySource = null;
if (this.properties.getFormat() == FILES) {
Response<GetValue> response = this.consul.getKVValue(
propertySourceContext, this.properties.getAclToken());
Response<GetValue> response = this.consul.getKVValue(propertySourceContext,
this.properties.getAclToken());
addIndex(propertySourceContext, response.getConsulIndex());
if (response.getValue() != null) {
ConsulFilesPropertySource filesPropertySource = new ConsulFilesPropertySource(
@@ -152,13 +149,11 @@ public class ConsulPropertySourceLocator
}
catch (Exception e) {
if (this.properties.isFailFast()) {
log.error(
"Fail fast is set and there was an error reading configuration from consul.");
log.error("Fail fast is set and there was an error reading configuration from consul.");
ReflectionUtils.rethrowRuntimeException(e);
}
else {
log.warn("Unable to load consul config from "
+ propertySourceContext, e);
log.warn("Unable to load consul config from " + propertySourceContext, e);
}
}
}
@@ -182,18 +177,15 @@ public class ConsulPropertySourceLocator
}
private ConsulPropertySource create(String context, Map<String, Long> contextIndex) {
ConsulPropertySource propertySource = new ConsulPropertySource(context,
this.consul, this.properties);
ConsulPropertySource propertySource = new ConsulPropertySource(context, this.consul, this.properties);
propertySource.init();
addIndex(context, propertySource.getInitialIndex());
return propertySource;
}
private void addProfiles(List<String> contexts, String baseContext,
List<String> profiles, String suffix) {
private void addProfiles(List<String> contexts, String baseContext, List<String> profiles, String suffix) {
for (String profile : profiles) {
contexts.add(baseContext + this.properties.getProfileSeparator() + profile
+ suffix);
contexts.add(baseContext + this.properties.getProfileSeparator() + profile + suffix);
}
}

View File

@@ -32,8 +32,7 @@ public class PropertySourcesLocatedEvent extends ApplicationEvent {
* @param source the object on which the event initially occurred (never {@code null})
* @param contextsToIndexes contexts to indexes
*/
public PropertySourcesLocatedEvent(Object source,
LinkedHashMap<String, Long> contextsToIndexes) {
public PropertySourcesLocatedEvent(Object source, LinkedHashMap<String, Long> contextsToIndexes) {
super(source);
this.contextsToIndexes = contextsToIndexes;
}

View File

@@ -60,8 +60,7 @@ public class ConfigWatchTests {
public void watchPublishesEventWithAcl() {
ApplicationEventPublisher eventPublisher = mock(ApplicationEventPublisher.class);
setupWatch(eventPublisher, new GetValue(), "/app/",
"2ee647bd-bd69-4118-9f34-b9a6e9e60746");
setupWatch(eventPublisher, new GetValue(), "/app/", "2ee647bd-bd69-4118-9f34-b9a6e9e60746");
verify(eventPublisher, atLeastOnce()).publishEvent(any(RefreshEvent.class));
}
@@ -94,13 +93,12 @@ public class ConfigWatchTests {
verify(eventPublisher, atLeastOnce()).publishEvent(any(RefreshEvent.class));
}
private void setupWatch(ApplicationEventPublisher eventPublisher, GetValue getValue,
String context) {
private void setupWatch(ApplicationEventPublisher eventPublisher, GetValue getValue, String context) {
setupWatch(eventPublisher, getValue, context, null);
}
private void setupWatch(ApplicationEventPublisher eventPublisher, GetValue getValue,
String context, String aclToken) {
private void setupWatch(ApplicationEventPublisher eventPublisher, GetValue getValue, String context,
String aclToken) {
ConsulClient consul = mock(ConsulClient.class);
List<GetValue> getValues = null;
@@ -109,8 +107,7 @@ public class ConfigWatchTests {
}
Response<List<GetValue>> response = new Response<>(getValues, 1L, false, 1L);
when(consul.getKVValues(eq(context), nullable(String.class),
any(QueryParams.class))).thenReturn(response);
when(consul.getKVValues(eq(context), nullable(String.class), any(QueryParams.class))).thenReturn(response);
if (StringUtils.hasText(aclToken)) {
this.configProperties.setAclToken(aclToken);
@@ -118,8 +115,7 @@ public class ConfigWatchTests {
LinkedHashMap<String, Long> initialIndexes = new LinkedHashMap<>();
initialIndexes.put(context, 0L);
ConfigWatch watch = new ConfigWatch(this.configProperties, consul,
initialIndexes);
ConfigWatch watch = new ConfigWatch(this.configProperties, consul, initialIndexes);
watch.setApplicationEventPublisher(eventPublisher);
watch.start();
@@ -137,11 +133,9 @@ public class ConfigWatchTests {
List<GetValue> getValues = Collections.singletonList(getValue);
Response<List<GetValue>> response = new Response<>(getValues, 1L, false, 1L);
when(consul.getKVValues(eq(context), anyString(), any(QueryParams.class)))
.thenReturn(response);
when(consul.getKVValues(eq(context), anyString(), any(QueryParams.class))).thenReturn(response);
ConfigWatch watch = new ConfigWatch(this.configProperties, consul,
new LinkedHashMap<String, Long>());
ConfigWatch watch = new ConfigWatch(this.configProperties, consul, new LinkedHashMap<String, Long>());
watch.setApplicationEventPublisher(eventPublisher);
watch.watchConfigKeyValues();

View File

@@ -36,16 +36,11 @@ public class ConsulConfigBootstrapConfigurationTests {
*/
@Test
public void testConfigPropsBeanBacksOff() {
this.contextRunner.withUserConfiguration(TestConfig.class)
.withInitializer(new ConsulTestcontainers())
.withUserConfiguration(ConsulConfigBootstrapConfiguration.class)
.run(context -> {
ConsulConfigProperties config = context
.getBean(ConsulConfigProperties.class);
assertThat(config.getPrefix()).as("Prefix did not match")
.isEqualTo("platform-config");
assertThat(config.getDefaultContext())
.as("Default context did not match").isEqualTo("defaults");
this.contextRunner.withUserConfiguration(TestConfig.class).withInitializer(new ConsulTestcontainers())
.withUserConfiguration(ConsulConfigBootstrapConfiguration.class).run(context -> {
ConsulConfigProperties config = context.getBean(ConsulConfigProperties.class);
assertThat(config.getPrefix()).as("Prefix did not match").isEqualTo("platform-config");
assertThat(config.getDefaultContext()).as("Default context did not match").isEqualTo("defaults");
});
}
@@ -57,12 +52,9 @@ public class ConsulConfigBootstrapConfigurationTests {
public void testConfigPropsBeanKicksIn() {
this.contextRunner.withUserConfiguration(ConsulConfigBootstrapConfiguration.class)
.withInitializer(new ConsulTestcontainers()).run(context -> {
ConsulConfigProperties config = context
.getBean(ConsulConfigProperties.class);
assertThat(config.getPrefix()).as("Prefix did not match")
.isEqualTo("config");
assertThat(config.getDefaultContext())
.as("Default context did not match").isEqualTo("application");
ConsulConfigProperties config = context.getBean(ConsulConfigProperties.class);
assertThat(config.getPrefix()).as("Prefix did not match").isEqualTo("config");
assertThat(config.getDefaultContext()).as("Default context did not match").isEqualTo("application");
});
}

View File

@@ -87,12 +87,11 @@ public class ConsulConfigDataIntegrationTests {
client.setKVValue(KEY1, VALUE1);
client.setKVValue(KEY2, VALUE2);
context = new SpringApplicationBuilder(Config.class).web(WebApplicationType.NONE)
.run("--spring.application.name=" + APP_NAME,
"--spring.config.import=consul:" + ConsulTestcontainers.getHost()
+ ":" + ConsulTestcontainers.getPort(),
"--spring.cloud.consul.config.prefix=" + ROOT,
"--spring.cloud.consul.config.watch.delay=10");
context = new SpringApplicationBuilder(Config.class).web(WebApplicationType.NONE).run(
"--spring.application.name=" + APP_NAME,
"--spring.config.import=consul:" + ConsulTestcontainers.getHost() + ":"
+ ConsulTestcontainers.getPort(),
"--spring.cloud.consul.config.prefix=" + ROOT, "--spring.cloud.consul.config.watch.delay=10");
client = context.getBean(ConsulClient.class);
environment = context.getEnvironment();
@@ -124,8 +123,7 @@ public class ConsulConfigDataIntegrationTests {
assertThat(receivedEvent).as("listener didn't receive event").isTrue();
testProp = environment.getProperty(TEST_PROP_CANONICAL);
assertThat(testProp).as("testProp was wrong after update")
.isEqualTo("testPropValUpdate");
assertThat(testProp).as("testProp was wrong after update").isEqualTo("testPropValUpdate");
}
@Test
@@ -140,8 +138,7 @@ public class ConsulConfigDataIntegrationTests {
assertThat(receivedEvent).as("listener didn't receive event").isTrue();
testProp = environment.getProperty(TEST_PROP3_CANONICAL);
assertThat(testProp).as(TEST_PROP3 + " was wrong after update")
.isEqualTo("testPropValInsert");
assertThat(testProp).as(TEST_PROP3 + " was wrong after update").isEqualTo("testPropValInsert");
}
@Configuration

View File

@@ -40,14 +40,12 @@ public class ConsulConfigDataLocationResolverTests {
@Test
public void testParseLocation() {
ConsulConfigDataLocationResolver resolver = new ConsulConfigDataLocationResolver();
UriComponents uriComponents = resolver.parseLocation(null,
"consul:myhost:8501/mypath1;/mypath2;/mypath3");
assertThat(uriComponents.toUri()).hasScheme("consul").hasHost("myhost")
.hasPort(8501).hasPath("/mypath1;/mypath2;/mypath3");
UriComponents uriComponents = resolver.parseLocation(null, "consul:myhost:8501/mypath1;/mypath2;/mypath3");
assertThat(uriComponents.toUri()).hasScheme("consul").hasHost("myhost").hasPort(8501)
.hasPath("/mypath1;/mypath2;/mypath3");
uriComponents = resolver.parseLocation(null, "consul:myhost:8501");
assertThat(uriComponents.toUri()).hasScheme("consul").hasHost("myhost")
.hasPort(8501).hasPath("");
assertThat(uriComponents.toUri()).hasScheme("consul").hasHost("myhost").hasPort(8501).hasPath("");
}
@Test
@@ -55,8 +53,7 @@ public class ConsulConfigDataLocationResolverTests {
String location = "consul:myhost:8501/mypath1;/mypath2;/mypath3";
List<ConsulConfigDataLocation> locations = testResolveProfileSpecific(location);
assertThat(locations).hasSize(3);
assertThat(toContexts(locations)).containsExactly("/mypath1/", "/mypath2/",
"/mypath3/");
assertThat(toContexts(locations)).containsExactly("/mypath1/", "/mypath2/", "/mypath3/");
}
@Test
@@ -64,28 +61,25 @@ public class ConsulConfigDataLocationResolverTests {
String location = "consul:myhost";
List<ConsulConfigDataLocation> locations = testResolveProfileSpecific(location);
assertThat(locations).hasSize(4);
assertThat(toContexts(locations)).containsExactly("config/testapp,dev/",
"config/testapp/", "config/application,dev/", "config/application/");
assertThat(toContexts(locations)).containsExactly("config/testapp,dev/", "config/testapp/",
"config/application,dev/", "config/application/");
}
@Test
public void testLoadProperties() {
ConsulProperties properties = createResolver().loadProperties(
Binder.get(new MockEnvironment()),
ConsulProperties properties = createResolver().loadProperties(Binder.get(new MockEnvironment()),
UriComponentsBuilder.fromUriString("consul://myhost:8502").build());
assertThat(properties.getHost()).isEqualTo("myhost");
assertThat(properties.getPort()).isEqualTo(8502);
}
private List<String> toContexts(List<ConsulConfigDataLocation> locations) {
return locations.stream().map(ConsulConfigDataLocation::getContext)
.collect(Collectors.toList());
return locations.stream().map(ConsulConfigDataLocation::getContext).collect(Collectors.toList());
}
private List<ConsulConfigDataLocation> testResolveProfileSpecific(String location) {
ConsulConfigDataLocationResolver resolver = createResolver();
ConfigDataLocationResolverContext context = mock(
ConfigDataLocationResolverContext.class);
ConfigDataLocationResolverContext context = mock(ConfigDataLocationResolverContext.class);
MockEnvironment env = new MockEnvironment();
env.setProperty("spring.application.name", "testapp");
when(context.getBinder()).thenReturn(Binder.get(env));
@@ -97,8 +91,8 @@ public class ConsulConfigDataLocationResolverTests {
private ConsulConfigDataLocationResolver createResolver() {
ConsulConfigDataLocationResolver resolver = new ConsulConfigDataLocationResolver() {
@Override
protected <T> void registerBean(ConfigDataLocationResolverContext context,
Class<T> type, Supplier<T> supplier) {
protected <T> void registerBean(ConfigDataLocationResolverContext context, Class<T> type,
Supplier<T> supplier) {
// do nothing
}
};

View File

@@ -47,24 +47,18 @@ public class ConsulPropertyPrefixTests {
this.client.setKVValue(kvContext + "/fooprop", "fookvval");
this.client.setKVValue(kvContext + "/bar/prop", "8080");
ConsulPropertySource source = getConsulPropertySource(
new ConsulConfigProperties(), kvContext);
ConsulPropertySource source = getConsulPropertySource(new ConsulConfigProperties(), kvContext);
assertProperties(source, "fookvval", "8080");
}
private void assertProperties(ConsulPropertySource source, Object fooval,
Object barval) {
assertThat(source.getProperty("fooprop")).as("fooprop was wrong")
.isEqualTo(fooval);
assertThat(source.getProperty("bar.prop")).as("bar.prop was wrong")
.isEqualTo(barval);
private void assertProperties(ConsulPropertySource source, Object fooval, Object barval) {
assertThat(source.getProperty("fooprop")).as("fooprop was wrong").isEqualTo(fooval);
assertThat(source.getProperty("bar.prop")).as("bar.prop was wrong").isEqualTo(barval);
}
@SuppressWarnings("Duplicates")
private ConsulPropertySource getConsulPropertySource(
ConsulConfigProperties configProperties, String context) {
ConsulPropertySource source = new ConsulPropertySource(context, this.client,
configProperties);
private ConsulPropertySource getConsulPropertySource(ConsulConfigProperties configProperties, String context) {
ConsulPropertySource source = new ConsulPropertySource(context, this.client, configProperties);
source.init();
String[] names = source.getPropertyNames();
assertThat(names).as("names was null").isNotNull();

View File

@@ -72,14 +72,12 @@ public class ConsulPropertySourceLocatorAppNameCustomizedTests {
this.client.setKVValue(KEY1, VALUE1);
this.client.setKVValue(KEY2, VALUE2);
this.context = new SpringApplicationBuilder(Config.class)
.web(WebApplicationType.NONE)
.run("--spring.application.name=testConsulPropertySourceLocatorAppNameCustomized",
"--spring.config.use-legacy-processing=true",
"--spring.cloud.consul.host=" + ConsulTestcontainers.getHost(),
"--spring.cloud.consul.port=" + ConsulTestcontainers.getPort(),
"--spring.cloud.consul.config.name=" + CONFIG_NAME,
"--spring.cloud.consul.config.prefix=" + ROOT);
this.context = new SpringApplicationBuilder(Config.class).web(WebApplicationType.NONE).run(
"--spring.application.name=testConsulPropertySourceLocatorAppNameCustomized",
"--spring.config.use-legacy-processing=true",
"--spring.cloud.consul.host=" + ConsulTestcontainers.getHost(),
"--spring.cloud.consul.port=" + ConsulTestcontainers.getPort(),
"--spring.cloud.consul.config.name=" + CONFIG_NAME, "--spring.cloud.consul.config.prefix=" + ROOT);
this.client = this.context.getBean(ConsulClient.class);
this.environment = this.context.getEnvironment();

View File

@@ -33,10 +33,8 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
@SpringBootTest(classes = ConsulPropertySourceLocatorFailFastTests.Config.class,
properties = { "spring.application.name=testConsulPropertySourceLocatorFailFast",
"spring.config.use-legacy-processing=true",
"spring.cloud.consul.host=53210a7c-4809-42cb-8b30-057d2db85fcc",
"spring.cloud.consul.port=65530",
"spring.cloud.consul.retry.enabled=false",
"spring.cloud.consul.retry.maxAttempts=0",
"spring.cloud.consul.host=53210a7c-4809-42cb-8b30-057d2db85fcc", "spring.cloud.consul.port=65530",
"spring.cloud.consul.retry.enabled=false", "spring.cloud.consul.retry.maxAttempts=0",
"spring.cloud.consul.config.failFast=false" },
webEnvironment = RANDOM_PORT)
public class ConsulPropertySourceLocatorFailFastTests {

View File

@@ -66,22 +66,17 @@ public class ConsulPropertySourceLocatorFilesTests {
ConsulTestcontainers.start();
this.client = ConsulTestcontainers.client();
this.client.setKVValue(ROOT + APPLICATION_YML, "foo: bar\nmy.baz: ${foo}");
this.client.setKVValue(ROOT + APPLICATION_DEV_YML,
"foo: bar-dev\nmy.baz: ${foo}");
this.client.setKVValue(ROOT + APPLICATION_DEV_YML, "foo: bar-dev\nmy.baz: ${foo}");
this.client.setKVValue(ROOT + "/master.ref", UUID.randomUUID().toString());
this.client.setKVValue(ROOT + APP_NAME_PROPS, "foo: bar-app\nmy.baz: ${foo}");
this.client.setKVValue(ROOT + APP_NAME_DEV_PROPS,
"foo: bar-app-dev\nmy.baz: ${foo}");
this.client.setKVValue(ROOT + APP_NAME_DEV_PROPS, "foo: bar-app-dev\nmy.baz: ${foo}");
this.context = new SpringApplicationBuilder(Config.class)
.web(WebApplicationType.NONE).run("--spring.application.name=" + APP_NAME,
"--spring.config.use-legacy-processing=true",
"--spring.cloud.consul.host=" + ConsulTestcontainers.getHost(),
"--spring.cloud.consul.port=" + ConsulTestcontainers.getPort(),
"--spring.cloud.consul.config.prefix=" + ROOT,
"--spring.cloud.consul.config.format=FILES",
"--spring.profiles.active=dev",
"spring.cloud.consul.config.watch.delay=1");
this.context = new SpringApplicationBuilder(Config.class).web(WebApplicationType.NONE).run(
"--spring.application.name=" + APP_NAME, "--spring.config.use-legacy-processing=true",
"--spring.cloud.consul.host=" + ConsulTestcontainers.getHost(),
"--spring.cloud.consul.port=" + ConsulTestcontainers.getPort(),
"--spring.cloud.consul.config.prefix=" + ROOT, "--spring.cloud.consul.config.format=FILES",
"--spring.profiles.active=dev", "spring.cloud.consul.config.watch.delay=1");
this.client = this.context.getBean(ConsulClient.class);
this.environment = this.context.getEnvironment();
@@ -111,10 +106,8 @@ public class ConsulPropertySourceLocatorFilesTests {
assertFilePropertySourceExists(propertySources, APPLICATION_YML);
}
private void assertFilePropertySourceExists(MutablePropertySources propertySources,
String name) {
boolean found = propertySources.stream()
.anyMatch(propertySource -> propertySource.getName().endsWith(name));
private void assertFilePropertySourceExists(MutablePropertySources propertySources, String name) {
boolean found = propertySources.stream().anyMatch(propertySource -> propertySource.getName().endsWith(name));
assertThat(found).as("missing consul filesource: " + name).isTrue();
}

View File

@@ -43,10 +43,8 @@ public class ConsulPropertySourceLocatorRetryTests {
"spring.application.name=testConsulPropertySourceLocatorRetry",
"spring.config.use-legacy-processing=true",
"spring.cloud.consul.host=53210a7c-4809-42cb-8b30-057d2db85fcc",
"logging.level.org.springframework.retry=TRACE", "server.port=0",
"spring.cloud.consul.port=65530",
"spring.cloud.consul.retry.maxAttempts=1",
"spring.cloud.consul.config.failFast=true").run();
"logging.level.org.springframework.retry=TRACE", "server.port=0", "spring.cloud.consul.port=65530",
"spring.cloud.consul.retry.maxAttempts=1", "spring.cloud.consul.config.failFast=true").run();
Assert.fail("Did not throw TransportException");
});
assertThat(output).contains("RetryContext retrieved");

View File

@@ -87,13 +87,11 @@ public class ConsulPropertySourceLocatorTests {
client.setKVValue(KEY1, VALUE1);
client.setKVValue(KEY2, VALUE2);
context = new SpringApplicationBuilder(Config.class).web(WebApplicationType.NONE)
.run("--spring.application.name=" + APP_NAME,
"--spring.config.use-legacy-processing=true",
"--spring.cloud.consul.host=" + ConsulTestcontainers.getHost(),
"--spring.cloud.consul.port=" + ConsulTestcontainers.getPort(),
"--spring.cloud.consul.config.prefix=" + ROOT,
"--spring.cloud.consul.config.watch.delay=10");
context = new SpringApplicationBuilder(Config.class).web(WebApplicationType.NONE).run(
"--spring.application.name=" + APP_NAME, "--spring.config.use-legacy-processing=true",
"--spring.cloud.consul.host=" + ConsulTestcontainers.getHost(),
"--spring.cloud.consul.port=" + ConsulTestcontainers.getPort(),
"--spring.cloud.consul.config.prefix=" + ROOT, "--spring.cloud.consul.config.watch.delay=10");
client = context.getBean(ConsulClient.class);
environment = context.getEnvironment();
@@ -125,8 +123,7 @@ public class ConsulPropertySourceLocatorTests {
assertThat(receivedEvent).as("listener didn't receive event").isTrue();
testProp = environment.getProperty(TEST_PROP_CANONICAL);
assertThat(testProp).as("testProp was wrong after update")
.isEqualTo("testPropValUpdate");
assertThat(testProp).as("testProp was wrong after update").isEqualTo("testPropValUpdate");
}
@Test
@@ -141,8 +138,7 @@ public class ConsulPropertySourceLocatorTests {
assertThat(receivedEvent).as("listener didn't receive event").isTrue();
testProp = environment.getProperty(TEST_PROP3_CANONICAL);
assertThat(testProp).as(TEST_PROP3 + " was wrong after update")
.isEqualTo("testPropValInsert");
assertThat(testProp).as(TEST_PROP3 + " was wrong after update").isEqualTo("testPropValInsert");
}
@Configuration

View File

@@ -43,8 +43,7 @@ public class ConsulPropertySourceTests {
@Before
public void setup() {
ConsulTestcontainers.start();
this.prefix = "consulPropertySourceTests"
+ new Random().nextInt(Integer.MAX_VALUE);
this.prefix = "consulPropertySourceTests" + new Random().nextInt(Integer.MAX_VALUE);
this.client = ConsulTestcontainers.client();
}
@@ -60,31 +59,25 @@ public class ConsulPropertySourceTests {
this.client.setKVValue(this.kvContext + "/fooprop", "fookvval");
this.client.setKVValue(this.prefix + "/kv" + "/bar/prop", "8080");
ConsulPropertySource source = getConsulPropertySource(
new ConsulConfigProperties(), this.kvContext);
ConsulPropertySource source = getConsulPropertySource(new ConsulConfigProperties(), this.kvContext);
assertProperties(source, "fookvval", "8080");
}
private void assertProperties(ConsulPropertySource source, Object fooval,
Object barval) {
assertThat(source.getProperty("fooprop")).as("fooprop was wrong")
.isEqualTo(fooval);
assertThat(source.getProperty("bar.prop")).as("bar.prop was wrong")
.isEqualTo(barval);
private void assertProperties(ConsulPropertySource source, Object fooval, Object barval) {
assertThat(source.getProperty("fooprop")).as("fooprop was wrong").isEqualTo(fooval);
assertThat(source.getProperty("bar.prop")).as("bar.prop was wrong").isEqualTo(barval);
}
@Test
public void testProperties() {
// properties file property
this.propertiesContext = this.prefix + "/properties";
this.client.setKVValue(this.propertiesContext + "/data",
"fooprop=foopropval\nbar.prop=8080");
this.client.setKVValue(this.propertiesContext + "/data", "fooprop=foopropval\nbar.prop=8080");
ConsulConfigProperties configProperties = new ConsulConfigProperties();
configProperties.setFormat(ConsulConfigProperties.Format.PROPERTIES);
ConsulPropertySource source = getConsulPropertySource(configProperties,
this.propertiesContext);
ConsulPropertySource source = getConsulPropertySource(configProperties, this.propertiesContext);
assertProperties(source, "foopropval", "8080");
}
@@ -93,13 +86,11 @@ public class ConsulPropertySourceTests {
public void testYaml() {
// yaml file property
String yamlContext = this.prefix + "/yaml";
this.client.setKVValue(yamlContext + "/data",
"fooprop: fooymlval\nbar:\n prop: 8080");
this.client.setKVValue(yamlContext + "/data", "fooprop: fooymlval\nbar:\n prop: 8080");
ConsulConfigProperties configProperties = new ConsulConfigProperties();
configProperties.setFormat(ConsulConfigProperties.Format.YAML);
ConsulPropertySource source = getConsulPropertySource(configProperties,
yamlContext);
ConsulPropertySource source = getConsulPropertySource(configProperties, yamlContext);
assertProperties(source, "fooymlval", 8080);
}
@@ -112,16 +103,13 @@ public class ConsulPropertySourceTests {
ConsulConfigProperties configProperties = new ConsulConfigProperties();
configProperties.setFormat(ConsulConfigProperties.Format.YAML);
ConsulPropertySource source = new ConsulPropertySource(yamlContext, this.client,
configProperties);
ConsulPropertySource source = new ConsulPropertySource(yamlContext, this.client, configProperties);
// Should NOT throw a NPE
source.init();
}
private ConsulPropertySource getConsulPropertySource(
ConsulConfigProperties configProperties, String context) {
ConsulPropertySource source = new ConsulPropertySource(context, this.client,
configProperties);
private ConsulPropertySource getConsulPropertySource(ConsulConfigProperties configProperties, String context) {
ConsulPropertySource source = new ConsulPropertySource(context, this.client, configProperties);
source.init();
String[] names = source.getPropertyNames();
assertThat(names).as("names was null").isNotNull();

View File

@@ -49,8 +49,7 @@ public @interface ConditionalOnConsulEnabled {
/**
* Consul property is enabled.
*/
@ConditionalOnProperty(value = "spring.cloud.consul.enabled",
matchIfMissing = true)
@ConditionalOnProperty(value = "spring.cloud.consul.enabled", matchIfMissing = true)
static class FoundProperty {
}

View File

@@ -60,14 +60,12 @@ public class ConsulAutoConfiguration {
public static ConsulClient createConsulClient(ConsulProperties consulProperties) {
final int agentPort = consulProperties.getPort();
final String agentHost = !StringUtils.isEmpty(consulProperties.getScheme())
? consulProperties.getScheme() + "://" + consulProperties.getHost()
: consulProperties.getHost();
? consulProperties.getScheme() + "://" + consulProperties.getHost() : consulProperties.getHost();
if (consulProperties.getTls() != null) {
ConsulProperties.TLSConfig tls = consulProperties.getTls();
TLSConfig tlsConfig = new TLSConfig(tls.getKeyStoreInstanceType(),
tls.getCertificatePath(), tls.getCertificatePassword(),
tls.getKeyStorePath(), tls.getKeyStorePassword());
TLSConfig tlsConfig = new TLSConfig(tls.getKeyStoreInstanceType(), tls.getCertificatePath(),
tls.getCertificatePassword(), tls.getKeyStorePath(), tls.getKeyStorePassword());
return new ConsulClient(agentHost, agentPort, tlsConfig);
}
return new ConsulClient(agentHost, agentPort);
@@ -98,18 +96,15 @@ public class ConsulAutoConfiguration {
@EnableRetry(proxyTargetClass = true)
@Import(AopAutoConfiguration.class)
@EnableConfigurationProperties(RetryProperties.class)
@ConditionalOnProperty(value = "spring.cloud.consul.retry.enabled",
matchIfMissing = true)
@ConditionalOnProperty(value = "spring.cloud.consul.retry.enabled", matchIfMissing = true)
protected static class RetryConfiguration {
@Bean(name = "consulRetryInterceptor")
@ConditionalOnMissingBean(name = "consulRetryInterceptor")
public RetryOperationsInterceptor consulRetryInterceptor(
RetryProperties properties) {
return RetryInterceptorBuilder.stateless()
.backOffOptions(properties.getInitialInterval(),
properties.getMultiplier(), properties.getMaxInterval())
.maxAttempts(properties.getMaxAttempts()).build();
public RetryOperationsInterceptor consulRetryInterceptor(RetryProperties properties) {
return RetryInterceptorBuilder.stateless().backOffOptions(properties.getInitialInterval(),
properties.getMultiplier(), properties.getMaxInterval()).maxAttempts(properties.getMaxAttempts())
.build();
}
}

View File

@@ -54,19 +54,16 @@ public class ConsulEndpoint {
data.setAgentServices(agentServices.getValue());
Response<Map<String, List<String>>> catalogServices = this.consul
.getCatalogServices(CatalogServicesRequest.newBuilder()
.setQueryParams(QueryParams.DEFAULT).build());
.getCatalogServices(CatalogServicesRequest.newBuilder().setQueryParams(QueryParams.DEFAULT).build());
for (String serviceId : catalogServices.getValue().keySet()) {
Response<List<CatalogService>> response = this.consul
.getCatalogService(serviceId, CatalogServiceRequest.newBuilder()
.setQueryParams(QueryParams.DEFAULT).build());
Response<List<CatalogService>> response = this.consul.getCatalogService(serviceId,
CatalogServiceRequest.newBuilder().setQueryParams(QueryParams.DEFAULT).build());
data.getCatalogServices().put(serviceId, response.getValue());
}
Response<List<Node>> catalogNodes = this.consul
.getCatalogNodes(CatalogNodesRequest.newBuilder()
.setQueryParams(QueryParams.DEFAULT).build());
.getCatalogNodes(CatalogNodesRequest.newBuilder().setQueryParams(QueryParams.DEFAULT).build());
data.setCatalogNodes(catalogNodes.getValue());
return data;
@@ -90,8 +87,7 @@ public class ConsulEndpoint {
return this.catalogServices;
}
public void setCatalogServices(
Map<String, List<CatalogService>> catalogServices) {
public void setCatalogServices(Map<String, List<CatalogService>> catalogServices) {
this.catalogServices = catalogServices;
}
@@ -113,10 +109,8 @@ public class ConsulEndpoint {
@Override
public String toString() {
return new ToStringCreator(this)
.append("catalogServices", this.catalogServices)
.append("agentServices", this.agentServices)
.append("catalogNodes", this.catalogNodes).toString();
return new ToStringCreator(this).append("catalogServices", this.catalogServices)
.append("agentServices", this.agentServices).append("catalogNodes", this.catalogNodes).toString();
}
}

View File

@@ -42,10 +42,8 @@ public class ConsulHealthIndicator extends AbstractHealthIndicator {
protected void doHealthCheck(Health.Builder builder) throws Exception {
final Response<String> leaderStatus = this.consul.getStatusLeader();
final Response<Map<String, List<String>>> services = this.consul
.getCatalogServices(CatalogServicesRequest.newBuilder()
.setQueryParams(QueryParams.DEFAULT).build());
builder.up().withDetail("leader", leaderStatus.getValue()).withDetail("services",
services.getValue());
.getCatalogServices(CatalogServicesRequest.newBuilder().setQueryParams(QueryParams.DEFAULT).build());
builder.up().withDetail("leader", leaderStatus.getValue()).withDetail("services", services.getValue());
}
}

View File

@@ -100,9 +100,8 @@ public class ConsulProperties {
@Override
public String toString() {
return "ConsulProperties{" + "host='" + this.host + '\'' + ", port=" + this.port
+ ", scheme=" + this.scheme + ", tls=" + this.tls + ", enabled="
+ this.enabled + '}';
return "ConsulProperties{" + "host='" + this.host + '\'' + ", port=" + this.port + ", scheme=" + this.scheme
+ ", tls=" + this.tls + ", enabled=" + this.enabled + '}';
}
/**
@@ -128,9 +127,8 @@ public class ConsulProperties {
public TLSConfig() {
}
public TLSConfig(KeyStoreInstanceType keyStoreInstanceType, String keyStorePath,
String keyStorePassword, String certificatePath,
String certificatePassword) {
public TLSConfig(KeyStoreInstanceType keyStoreInstanceType, String keyStorePath, String keyStorePassword,
String certificatePath, String certificatePassword) {
this.keyStoreInstanceType = keyStoreInstanceType;
this.keyStorePath = keyStorePath;
this.keyStorePassword = keyStorePassword;
@@ -180,10 +178,8 @@ public class ConsulProperties {
@Override
public String toString() {
return new ToStringCreator(this)
.append("keyStoreInstanceType", this.keyStoreInstanceType)
.append("keyStorePath", this.keyStorePath)
.append("keyStorePassword", this.keyStorePassword)
return new ToStringCreator(this).append("keyStoreInstanceType", this.keyStoreInstanceType)
.append("keyStorePath", this.keyStorePath).append("keyStorePassword", this.keyStorePassword)
.append("certificatePath", this.certificatePath)
.append("certificatePassword", this.certificatePassword).toString();
}

View File

@@ -85,10 +85,8 @@ public class RetryProperties {
@Override
public String toString() {
return new ToStringCreator(this).append("enabled", this.enabled)
.append("initialInterval", this.initialInterval)
.append("multiplier", this.multiplier)
.append("maxInterval", this.maxInterval)
return new ToStringCreator(this).append("enabled", this.enabled).append("initialInterval", this.initialInterval)
.append("multiplier", this.multiplier).append("maxInterval", this.maxInterval)
.append("maxAttempts", this.maxAttempts).toString();
}

View File

@@ -49,12 +49,10 @@ public class ConsulAutoConfigurationTests {
@Test
public void tlsConfigured() {
CatalogConsulClient client = (CatalogConsulClient) ReflectionTestUtils
.getField(this.consulClient, "catalogClient");
ConsulRawClient rawClient = (ConsulRawClient) ReflectionTestUtils.getField(client,
"rawClient");
HttpTransport httpTransport = (HttpTransport) ReflectionTestUtils
.getField(rawClient, "httpTransport");
CatalogConsulClient client = (CatalogConsulClient) ReflectionTestUtils.getField(this.consulClient,
"catalogClient");
ConsulRawClient rawClient = (ConsulRawClient) ReflectionTestUtils.getField(client, "rawClient");
HttpTransport httpTransport = (HttpTransport) ReflectionTestUtils.getField(rawClient, "httpTransport");
assertThat(httpTransport).isInstanceOf(DefaultHttpsTransport.class);
}

View File

@@ -41,8 +41,7 @@ public class ConsulHealthIndicatorDownTest {
@Test
public void doHealthCheck() {
assertThat(this.healthEndpoint.health().getStatus())
.as("health status was not DOWN").isEqualTo(Status.DOWN);
assertThat(this.healthEndpoint.health().getStatus()).as("health status was not DOWN").isEqualTo(Status.DOWN);
}
@EnableAutoConfiguration

View File

@@ -44,8 +44,7 @@ public class ConsulHealthIndicatorUpTest {
@Test
public void doHealthCheck() {
assertThat(this.healthEndpoint.health().getStatus())
.as("health status was not UP").isEqualTo(Status.UP);
assertThat(this.healthEndpoint.health().getStatus()).as("health status was not UP").isEqualTo(Status.UP);
}
@EnableAutoConfiguration

View File

@@ -31,16 +31,14 @@ import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.MutablePropertySources;
public class ConsulTestcontainers
implements ApplicationContextInitializer<ConfigurableApplicationContext> {
public class ConsulTestcontainers implements ApplicationContextInitializer<ConfigurableApplicationContext> {
static final Logger logger = LoggerFactory.getLogger(ConsulTestcontainers.class);
public static GenericContainer<?> consul = new GenericContainer<>("consul:1.7.2")
.withLogConsumer(new Slf4jLogConsumer(logger).withSeparateOutputStreams())
.waitingFor(Wait.forHttp("/v1/status/leader")).withExposedPorts(8500)
.withCommand("agent", "-dev", "-server", "-bootstrap", "-client", "0.0.0.0",
"-log-level", "trace");
.withCommand("agent", "-dev", "-server", "-bootstrap", "-client", "0.0.0.0", "-log-level", "trace");
@Override
public void initialize(ConfigurableApplicationContext context) {

View File

@@ -36,8 +36,7 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@ConditionalOnProperty(value = "spring.cloud.consul.discovery.enabled",
matchIfMissing = true)
@ConditionalOnProperty(value = "spring.cloud.consul.discovery.enabled", matchIfMissing = true)
public @interface ConditionalOnConsulDiscoveryEnabled {
}

View File

@@ -41,8 +41,7 @@ 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);
@@ -64,8 +63,7 @@ public class ConsulCatalogWatch
this(properties, consul, getTaskScheduler());
}
public ConsulCatalogWatch(ConsulDiscoveryProperties properties, ConsulClient consul,
TaskScheduler taskScheduler) {
public ConsulCatalogWatch(ConsulDiscoveryProperties properties, ConsulClient consul, TaskScheduler taskScheduler) {
this.properties = properties;
this.consul = consul;
this.taskScheduler = taskScheduler;
@@ -96,8 +94,7 @@ public class ConsulCatalogWatch
@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());
}
}
@@ -128,19 +125,16 @@ public class ConsulCatalogWatch
}
CatalogServicesRequest request = CatalogServicesRequest.newBuilder()
.setQueryParams(new QueryParams(
this.properties.getCatalogServicesWatchTimeout(), index))
.setQueryParams(new QueryParams(this.properties.getCatalogServicesWatchTimeout(), index))
.setToken(this.properties.getAclToken()).build();
Response<Map<String, List<String>>> response = this.consul
.getCatalogServices(request);
Response<Map<String, List<String>>> response = this.consul.getCatalogServices(request);
Long consulIndex = response.getConsulIndex();
if (consulIndex != null) {
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);
}
this.publisher.publishEvent(new HeartbeatEvent(this, consulIndex));
}

View File

@@ -37,9 +37,7 @@ import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnConsulEnabled
@ConditionalOnProperty(
value = "spring.cloud.consul.discovery.catalog-services-watch.enabled",
matchIfMissing = true)
@ConditionalOnProperty(value = "spring.cloud.consul.discovery.catalog-services-watch.enabled", matchIfMissing = true)
@ConditionalOnDiscoveryEnabled
@AutoConfigureAfter({ ConsulDiscoveryClientConfiguration.class })
@ConditionalOnBean(ConsulDiscoveryProperties.class)
@@ -52,9 +50,8 @@ public class ConsulCatalogWatchAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public ConsulCatalogWatch consulCatalogWatch(
ConsulDiscoveryProperties discoveryProperties, ConsulClient consulClient,
@Qualifier(CATALOG_WATCH_TASK_SCHEDULER_NAME) TaskScheduler taskScheduler) {
public ConsulCatalogWatch consulCatalogWatch(ConsulDiscoveryProperties discoveryProperties,
ConsulClient consulClient, @Qualifier(CATALOG_WATCH_TASK_SCHEDULER_NAME) TaskScheduler taskScheduler) {
return new ConsulCatalogWatch(discoveryProperties, consulClient, taskScheduler);
}

View File

@@ -49,8 +49,7 @@ public class ConsulDiscoveryClient implements DiscoveryClient {
private final ConsulDiscoveryProperties properties;
public ConsulDiscoveryClient(ConsulClient client,
ConsulDiscoveryProperties properties) {
public ConsulDiscoveryClient(ConsulClient client, ConsulDiscoveryProperties properties) {
this.client = client;
this.properties = properties;
}
@@ -62,12 +61,10 @@ public class ConsulDiscoveryClient implements DiscoveryClient {
@Override
public List<ServiceInstance> getInstances(final String serviceId) {
return getInstances(serviceId,
new QueryParams(this.properties.getConsistencyMode()));
return getInstances(serviceId, new QueryParams(this.properties.getConsistencyMode()));
}
public List<ServiceInstance> getInstances(final String serviceId,
final QueryParams queryParams) {
public List<ServiceInstance> getInstances(final String serviceId, final QueryParams queryParams) {
List<ServiceInstance> instances = new ArrayList<>();
addInstancesToList(instances, serviceId, queryParams);
@@ -75,15 +72,12 @@ public class ConsulDiscoveryClient implements DiscoveryClient {
return instances;
}
private void addInstancesToList(List<ServiceInstance> instances, String serviceId,
QueryParams queryParams) {
private void addInstancesToList(List<ServiceInstance> instances, String serviceId, QueryParams queryParams) {
HealthServicesRequest request = HealthServicesRequest.newBuilder()
.setTag(this.properties.getDefaultQueryTag())
HealthServicesRequest request = HealthServicesRequest.newBuilder().setTag(this.properties.getDefaultQueryTag())
.setPassing(this.properties.isQueryPassing()).setQueryParams(queryParams)
.setToken(this.properties.getAclToken()).build();
Response<List<HealthService>> services = this.client.getHealthServices(serviceId,
request);
Response<List<HealthService>> services = this.client.getHealthServices(serviceId, request);
for (HealthService service : services.getValue()) {
String host = findHost(service);
@@ -96,8 +90,8 @@ 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));
}
}
@@ -105,8 +99,7 @@ public class ConsulDiscoveryClient implements DiscoveryClient {
List<ServiceInstance> instances = new ArrayList<>();
Response<Map<String, List<String>>> services = this.client
.getCatalogServices(CatalogServicesRequest.newBuilder()
.setQueryParams(QueryParams.DEFAULT).build());
.getCatalogServices(CatalogServicesRequest.newBuilder().setQueryParams(QueryParams.DEFAULT).build());
for (String serviceId : services.getValue().keySet()) {
addInstancesToList(instances, serviceId, QueryParams.DEFAULT);
}
@@ -115,11 +108,9 @@ public class ConsulDiscoveryClient implements DiscoveryClient {
@Override
public List<String> getServices() {
CatalogServicesRequest request = CatalogServicesRequest.newBuilder()
.setQueryParams(QueryParams.DEFAULT)
CatalogServicesRequest request = CatalogServicesRequest.newBuilder().setQueryParams(QueryParams.DEFAULT)
.setToken(this.properties.getAclToken()).build();
return new ArrayList<>(
this.client.getCatalogServices(request).getValue().keySet());
return new ArrayList<>(this.client.getCatalogServices(request).getValue().keySet());
}
@Override

View File

@@ -44,8 +44,7 @@ import org.springframework.context.annotation.Configuration;
@ConditionalOnConsulEnabled
@ConditionalOnConsulDiscoveryEnabled
@EnableConfigurationProperties
@AutoConfigureBefore({ SimpleDiscoveryClientAutoConfiguration.class,
CommonsClientAutoConfiguration.class })
@AutoConfigureBefore({ SimpleDiscoveryClientAutoConfiguration.class, CommonsClientAutoConfiguration.class })
@AutoConfigureAfter({ UtilAutoConfiguration.class, ConsulAutoConfiguration.class })
public class ConsulDiscoveryClientConfiguration {

View File

@@ -580,40 +580,29 @@ public class ConsulDiscoveryProperties {
return new ToStringCreator(this).append("aclToken", this.aclToken)
.append("catalogServicesWatchDelay", this.catalogServicesWatchDelay)
.append("catalogServicesWatchTimeout", this.catalogServicesWatchTimeout)
.append("consistencyMode", this.consistencyMode)
.append("datacenters", this.datacenters)
.append("consistencyMode", this.consistencyMode).append("datacenters", this.datacenters)
.append("defaultQueryTag", this.defaultQueryTag)
.append("defaultZoneMetadataName", this.defaultZoneMetadataName)
.append("deregister", this.deregister).append("enabled", this.enabled)
.append("enableTagOverride", this.enableTagOverride)
.append("defaultZoneMetadataName", this.defaultZoneMetadataName).append("deregister", this.deregister)
.append("enabled", this.enabled).append("enableTagOverride", this.enableTagOverride)
.append("failFast", this.failFast).append("hostInfo", this.hostInfo)
.append("healthCheckCriticalTimeout", this.healthCheckCriticalTimeout)
.append("healthCheckHeaders", this.healthCheckHeaders)
.append("healthCheckInterval", this.healthCheckInterval)
.append("healthCheckPath", this.healthCheckPath)
.append("healthCheckInterval", this.healthCheckInterval).append("healthCheckPath", this.healthCheckPath)
.append("healthCheckTimeout", this.healthCheckTimeout)
.append("healthCheckTlsSkipVerify", this.healthCheckTlsSkipVerify)
.append("healthCheckUrl", this.healthCheckUrl)
.append("hostname", this.hostname)
.append("healthCheckUrl", this.healthCheckUrl).append("hostname", this.hostname)
.append("includeHostnameInInstanceId", this.includeHostnameInInstanceId)
.append("instanceId", this.instanceId)
.append("instanceGroup", this.instanceGroup)
.append("instanceZone", this.instanceZone)
.append("ipAddress", this.ipAddress).append("lifecycle", this.lifecycle)
.append("metadata", this.metadata)
.append("instanceId", this.instanceId).append("instanceGroup", this.instanceGroup)
.append("instanceZone", this.instanceZone).append("ipAddress", this.ipAddress)
.append("lifecycle", this.lifecycle).append("metadata", this.metadata)
.append("managementEnableTagOverride", this.managementEnableTagOverride)
.append("managementMetadata", this.managementMetadata)
.append("managementPort", this.managementPort)
.append("managementSuffix", this.managementSuffix)
.append("managementTags", this.managementTags).append("order", this.order)
.append("port", this.port)
.append("preferAgentAddress", this.preferAgentAddress)
.append("preferIpAddress", this.preferIpAddress)
.append("queryPassing", this.queryPassing)
.append("register", this.register)
.append("registerHealthCheck", this.registerHealthCheck)
.append("scheme", this.scheme).append("serviceName", this.serviceName)
.append("serverListQueryTags", this.serverListQueryTags)
.append("managementMetadata", this.managementMetadata).append("managementPort", this.managementPort)
.append("managementSuffix", this.managementSuffix).append("managementTags", this.managementTags)
.append("order", this.order).append("port", this.port)
.append("preferAgentAddress", this.preferAgentAddress).append("preferIpAddress", this.preferIpAddress)
.append("queryPassing", this.queryPassing).append("register", this.register)
.append("registerHealthCheck", this.registerHealthCheck).append("scheme", this.scheme)
.append("serviceName", this.serviceName).append("serverListQueryTags", this.serverListQueryTags)
.append("tags", this.tags).toString();
}

View File

@@ -38,8 +38,7 @@ import org.springframework.validation.annotation.Validated;
@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
@@ -87,16 +86,14 @@ public class HeartbeatProperties {
return this.intervalRatio;
}
public void setIntervalRatio(
@DecimalMin("0.1") @DecimalMax("0.9") double 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", this.enabled)
.append("ttl", this.ttl).append("intervalRatio", this.intervalRatio)
.toString();
return new ToStringCreator(this).append("enabled", this.enabled).append("ttl", this.ttl)
.append("intervalRatio", this.intervalRatio).toString();
}
}

View File

@@ -40,8 +40,7 @@ public class TtlScheduler {
private final Map<String, ScheduledFuture> serviceHeartbeats = new ConcurrentHashMap<>();
private final TaskScheduler scheduler = new ConcurrentTaskScheduler(
Executors.newSingleThreadScheduledExecutor());
private final TaskScheduler scheduler = new ConcurrentTaskScheduler(Executors.newSingleThreadScheduledExecutor());
private HeartbeatProperties configuration;
@@ -62,8 +61,7 @@ public class TtlScheduler {
* @param instanceId instance id
*/
public void add(String instanceId) {
ScheduledFuture task = this.scheduler.scheduleAtFixedRate(
new ConsulHeartbeatTask(instanceId),
ScheduledFuture task = this.scheduler.scheduleAtFixedRate(new ConsulHeartbeatTask(instanceId),
this.configuration.computeHeartbeatInterval().toMillis());
ScheduledFuture previousTask = this.serviceHeartbeats.put(instanceId, task);
if (previousTask != null) {

View File

@@ -35,8 +35,7 @@ import org.springframework.util.StringUtils;
*/
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties
@ConditionalOnClass({ ConsulDiscoveryProperties.class, ConsulClient.class,
ConfigServerProperties.class })
@ConditionalOnClass({ ConsulDiscoveryProperties.class, ConsulClient.class, ConfigServerProperties.class })
public class ConsulConfigServerAutoConfiguration {
/**

View File

@@ -34,8 +34,7 @@ import org.springframework.context.annotation.Configuration;
@ConditionalOnClass(ConfigServicePropertySourceLocator.class)
@ConditionalOnProperty("spring.cloud.config.discovery.enabled")
@Configuration(proxyBeanMethods = false)
@ImportAutoConfiguration({ ConsulAutoConfiguration.class,
ConsulDiscoveryClientConfiguration.class,
@ImportAutoConfiguration({ ConsulAutoConfiguration.class, ConsulDiscoveryClientConfiguration.class,
ConsulReactiveDiscoveryClientConfiguration.class })
public class ConsulDiscoveryClientConfigServiceBootstrapConfiguration {

View File

@@ -47,15 +47,13 @@ import static org.springframework.cloud.consul.discovery.ConsulServerUtils.findH
*/
public class ConsulReactiveDiscoveryClient implements ReactiveDiscoveryClient {
private static final Logger logger = LoggerFactory
.getLogger(ConsulReactiveDiscoveryClient.class);
private static final Logger logger = LoggerFactory.getLogger(ConsulReactiveDiscoveryClient.class);
private final ConsulClient client;
private final ConsulDiscoveryProperties properties;
public ConsulReactiveDiscoveryClient(ConsulClient client,
ConsulDiscoveryProperties properties) {
public ConsulReactiveDiscoveryClient(ConsulClient client, ConsulDiscoveryProperties properties) {
this.client = client;
this.properties = properties;
}
@@ -80,19 +78,15 @@ public class ConsulReactiveDiscoveryClient implements ReactiveDiscoveryClient {
}
private List<HealthService> getHealthServices(String serviceId) {
HealthServicesRequest request = HealthServicesRequest.newBuilder()
.setTag(this.properties.getDefaultQueryTag())
.setPassing(this.properties.isQueryPassing())
.setQueryParams(QueryParams.DEFAULT)
HealthServicesRequest request = HealthServicesRequest.newBuilder().setTag(this.properties.getDefaultQueryTag())
.setPassing(this.properties.isQueryPassing()).setQueryParams(QueryParams.DEFAULT)
.setToken(this.properties.getAclToken()).build();
Response<List<HealthService>> services = client.getHealthServices(serviceId,
request);
Response<List<HealthService>> services = client.getHealthServices(serviceId, request);
return services == null ? Collections.emptyList() : services.getValue();
}
private ServiceInstance mapToServiceInstance(HealthService service,
String serviceId) {
private ServiceInstance mapToServiceInstance(HealthService service, String serviceId) {
String host = findHost(service);
Map<String, String> metadata = service.getService().getMeta();
if (metadata == null) {
@@ -102,20 +96,17 @@ public class ConsulReactiveDiscoveryClient implements ReactiveDiscoveryClient {
if (metadata.containsKey("secure")) {
secure = Boolean.parseBoolean(metadata.get("secure"));
}
return new DefaultServiceInstance(service.getService().getId(), serviceId, host,
service.getService().getPort(), secure, metadata);
return new DefaultServiceInstance(service.getService().getId(), serviceId, host, service.getService().getPort(),
secure, metadata);
}
@Override
public Flux<String> getServices() {
return Flux.defer(() -> {
CatalogServicesRequest request = CatalogServicesRequest.newBuilder()
.setToken(properties.getAclToken())
CatalogServicesRequest request = CatalogServicesRequest.newBuilder().setToken(properties.getAclToken())
.setQueryParams(QueryParams.DEFAULT).build();
Response<Map<String, List<String>>> services = client
.getCatalogServices(request);
return services == null ? Flux.empty()
: Flux.fromIterable(services.getValue().keySet());
Response<Map<String, List<String>>> services = client.getCatalogServices(request);
return services == null ? Flux.empty() : Flux.fromIterable(services.getValue().keySet());
}).onErrorResume(exception -> {
logger.error("Error getting services from Consul.", exception);
return Flux.empty();

View File

@@ -49,8 +49,7 @@ import org.springframework.context.annotation.Configuration;
@ConditionalOnConsulDiscoveryEnabled
@EnableConfigurationProperties(DiscoveryClientHealthIndicatorProperties.class)
@AutoConfigureBefore(ReactiveCommonsClientAutoConfiguration.class)
@AutoConfigureAfter({ UtilAutoConfiguration.class,
ReactiveCompositeDiscoveryClientAutoConfiguration.class,
@AutoConfigureAfter({ UtilAutoConfiguration.class, ReactiveCompositeDiscoveryClientAutoConfiguration.class,
ConsulAutoConfiguration.class })
public class ConsulReactiveDiscoveryClientConfiguration {
@@ -62,18 +61,16 @@ public class ConsulReactiveDiscoveryClientConfiguration {
@Bean
@ConditionalOnMissingBean
public ConsulReactiveDiscoveryClient consulReactiveDiscoveryClient(
ConsulClient client, ConsulDiscoveryProperties discoveryProperties) {
public ConsulReactiveDiscoveryClient consulReactiveDiscoveryClient(ConsulClient client,
ConsulDiscoveryProperties discoveryProperties) {
return new ConsulReactiveDiscoveryClient(client, discoveryProperties);
}
@Bean
@ConditionalOnClass(
name = "org.springframework.boot.actuate.health.ReactiveHealthIndicator")
@ConditionalOnClass(name = "org.springframework.boot.actuate.health.ReactiveHealthIndicator")
@ConditionalOnDiscoveryHealthIndicatorEnabled
public ReactiveDiscoveryClientHealthIndicator consulReactiveDiscoveryClientHealthIndicator(
ConsulReactiveDiscoveryClient client,
DiscoveryClientHealthIndicatorProperties properties) {
ConsulReactiveDiscoveryClient client, DiscoveryClientHealthIndicatorProperties properties) {
return new ReactiveDiscoveryClientHealthIndicator(client, properties);
}

View File

@@ -56,17 +56,15 @@ public class ConsulAutoRegistration extends ConsulRegistration {
@Deprecated
public ConsulAutoRegistration(NewService service,
AutoServiceRegistrationProperties autoServiceRegistrationProperties,
ConsulDiscoveryProperties properties, ApplicationContext context,
HeartbeatProperties heartbeatProperties) {
this(service, autoServiceRegistrationProperties, properties, context,
heartbeatProperties, Collections.emptyList());
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,
AutoServiceRegistrationProperties autoServiceRegistrationProperties, ConsulDiscoveryProperties properties,
ApplicationContext context, HeartbeatProperties heartbeatProperties,
List<ConsulManagementRegistrationCustomizer> managementRegistrationCustomizers) {
super(service, properties);
this.autoServiceRegistrationProperties = autoServiceRegistrationProperties;
@@ -76,9 +74,8 @@ public class ConsulAutoRegistration extends ConsulRegistration {
}
public static ConsulAutoRegistration registration(
AutoServiceRegistrationProperties autoServiceRegistrationProperties,
ConsulDiscoveryProperties properties, ApplicationContext context,
List<ConsulRegistrationCustomizer> registrationCustomizers,
AutoServiceRegistrationProperties autoServiceRegistrationProperties, ConsulDiscoveryProperties properties,
ApplicationContext context, List<ConsulRegistrationCustomizer> registrationCustomizers,
List<ConsulManagementRegistrationCustomizer> managementRegistrationCustomizers,
HeartbeatProperties heartbeatProperties) {
@@ -96,19 +93,16 @@ 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,
public static void customize(List<ConsulRegistrationCustomizer> registrationCustomizers,
ConsulAutoRegistration registration) {
if (registrationCustomizers != null) {
for (ConsulRegistrationCustomizer customizer : registrationCustomizers) {
@@ -117,14 +111,11 @@ public class ConsulAutoRegistration extends ConsulRegistration {
}
}
public static void setCheck(NewService service,
AutoServiceRegistrationProperties autoServiceRegistrationProperties,
ConsulDiscoveryProperties properties, ApplicationContext context,
HeartbeatProperties heartbeatProperties) {
public static void setCheck(NewService service, AutoServiceRegistrationProperties autoServiceRegistrationProperties,
ConsulDiscoveryProperties properties, ApplicationContext context, 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 {
@@ -136,32 +127,27 @@ public class ConsulAutoRegistration extends ConsulRegistration {
}
public static ConsulAutoRegistration managementRegistration(
AutoServiceRegistrationProperties autoServiceRegistrationProperties,
ConsulDiscoveryProperties properties, ApplicationContext context,
List<ConsulManagementRegistrationCustomizer> managementRegistrationCustomizers,
AutoServiceRegistrationProperties autoServiceRegistrationProperties, ConsulDiscoveryProperties properties,
ApplicationContext context, List<ConsulManagementRegistrationCustomizer> managementRegistrationCustomizers,
HeartbeatProperties heartbeatProperties) {
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());
management.setEnableTagOverride(properties.getManagementEnableTagOverride());
management.setMeta(properties.getManagementMetadata());
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,
public static void managementCustomize(List<ConsulManagementRegistrationCustomizer> registrationCustomizers,
ConsulAutoRegistration registration) {
if (registrationCustomizers != null) {
for (ConsulManagementRegistrationCustomizer customizer : registrationCustomizers) {
@@ -170,23 +156,19 @@ 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(),
properties.isIncludeHostnameInInstanceId()));
return normalizeForDns(
IdUtils.getDefaultInstanceId(context.getEnvironment(), properties.isIncludeHostnameInInstanceId()));
}
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))) {
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);
"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();
@@ -216,8 +198,7 @@ public class ConsulAutoRegistration extends ConsulRegistration {
// add metadata from other properties. See createTags above.
if (!StringUtils.isEmpty(properties.getInstanceZone())) {
metadata.put(properties.getDefaultZoneMetadataName(),
properties.getInstanceZone());
metadata.put(properties.getDefaultZoneMetadataName(), properties.getInstanceZone());
}
if (!StringUtils.isEmpty(properties.getInstanceGroup())) {
metadata.put("group", properties.getInstanceGroup());
@@ -225,18 +206,16 @@ public class ConsulAutoRegistration extends ConsulRegistration {
// store the secure flag in the tags so that clients will be able to figure
// out whether to use http or https automatically
metadata.put("secure",
Boolean.toString(properties.getScheme().equalsIgnoreCase("https")));
metadata.put("secure", Boolean.toString(properties.getScheme().equalsIgnoreCase("https")));
return metadata;
}
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 (StringUtils.hasText(properties.getHealthCheckCriticalTimeout())) {
check.setDeregisterCriticalServiceAfter(
properties.getHealthCheckCriticalTimeout());
check.setDeregisterCriticalServiceAfter(properties.getHealthCheckCriticalTimeout());
}
if (ttlConfig.isEnabled()) {
// FIXME 3.0.0
@@ -252,8 +231,8 @@ public class ConsulAutoRegistration extends ConsulRegistration {
check.setHttp(properties.getHealthCheckUrl());
}
else {
check.setHttp(String.format("%s://%s:%s%s", properties.getScheme(),
properties.getHostname(), port, properties.getHealthCheckPath()));
check.setHttp(String.format("%s://%s:%s%s", properties.getScheme(), properties.getHostname(), port,
properties.getHealthCheckPath()));
}
check.setHeader(properties.getHealthCheckHeaders());
check.setInterval(properties.getHealthCheckInterval());
@@ -267,8 +246,7 @@ public class ConsulAutoRegistration extends ConsulRegistration {
* @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;
@@ -283,12 +261,10 @@ public class ConsulAutoRegistration extends ConsulRegistration {
* @return if the management service should be registered with the
* {@link ServiceRegistry}
*/
public static boolean shouldRegisterManagement(
AutoServiceRegistrationProperties autoServiceRegistrationProperties,
public static boolean shouldRegisterManagement(AutoServiceRegistrationProperties autoServiceRegistrationProperties,
ConsulDiscoveryProperties properties, ApplicationContext context) {
return autoServiceRegistrationProperties.isRegisterManagement()
&& getManagementPort(properties, context) != null
&& ManagementServerPortUtils.isDifferent(context);
&& getManagementPort(properties, context) != null && ManagementServerPortUtils.isDifferent(context);
}
/**
@@ -296,15 +272,12 @@ public class ConsulAutoRegistration extends ConsulRegistration {
* @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
return normalizeForDns(IdUtils.getDefaultInstanceId(context.getEnvironment(), false)) + SEPARATOR
+ properties.getManagementSuffix();
}
@@ -313,15 +286,12 @@ public class ConsulAutoRegistration extends ConsulRegistration {
* @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();
}
/**
@@ -329,8 +299,7 @@ public class ConsulAutoRegistration extends ConsulRegistration {
* @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();
@@ -346,14 +315,13 @@ public class ConsulAutoRegistration extends ConsulRegistration {
// 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,
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

@@ -30,8 +30,7 @@ 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);
@@ -40,8 +39,8 @@ public class ConsulAutoServiceRegistration
private ConsulAutoRegistration registration;
public ConsulAutoServiceRegistration(ConsulServiceRegistry serviceRegistry,
AutoServiceRegistrationProperties autoServiceRegistrationProperties,
ConsulDiscoveryProperties properties, ConsulAutoRegistration registration) {
AutoServiceRegistrationProperties autoServiceRegistrationProperties, ConsulDiscoveryProperties properties,
ConsulAutoRegistration registration) {
super(serviceRegistry, autoServiceRegistrationProperties);
this.properties = properties;
this.registration = registration;
@@ -53,12 +52,10 @@ public class ConsulAutoServiceRegistration
@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;
}

View File

@@ -43,12 +43,10 @@ import org.springframework.context.annotation.Configuration;
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnBean(AutoServiceRegistrationProperties.class)
@ConditionalOnMissingBean(
type = "org.springframework.cloud.consul.discovery.ConsulLifecycle")
@ConditionalOnMissingBean(type = "org.springframework.cloud.consul.discovery.ConsulLifecycle")
@ConditionalOnConsulEnabled
@Conditional(ConsulAutoServiceRegistrationAutoConfiguration.OnConsulRegistrationEnabledCondition.class)
@AutoConfigureAfter({ AutoServiceRegistrationConfiguration.class,
ConsulServiceRegistryAutoConfiguration.class })
@AutoConfigureAfter({ AutoServiceRegistrationConfiguration.class, ConsulServiceRegistryAutoConfiguration.class })
public class ConsulAutoServiceRegistrationAutoConfiguration {
@Autowired
@@ -56,13 +54,11 @@ public class ConsulAutoServiceRegistrationAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public ConsulAutoServiceRegistration consulAutoServiceRegistration(
ConsulServiceRegistry registry,
AutoServiceRegistrationProperties autoServiceRegistrationProperties,
ConsulDiscoveryProperties properties,
public ConsulAutoServiceRegistration consulAutoServiceRegistration(ConsulServiceRegistry registry,
AutoServiceRegistrationProperties autoServiceRegistrationProperties, ConsulDiscoveryProperties properties,
ConsulAutoRegistration consulRegistration) {
return new ConsulAutoServiceRegistration(registry,
autoServiceRegistrationProperties, properties, consulRegistration);
return new ConsulAutoServiceRegistration(registry, autoServiceRegistrationProperties, properties,
consulRegistration);
}
@Bean
@@ -74,14 +70,14 @@ public class ConsulAutoServiceRegistrationAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public ConsulAutoRegistration consulRegistration(
AutoServiceRegistrationProperties autoServiceRegistrationProperties,
ConsulDiscoveryProperties properties, ApplicationContext applicationContext,
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(proxyBeanMethods = false)
@@ -89,42 +85,35 @@ public class ConsulAutoServiceRegistrationAutoConfiguration {
protected static class ConsulServletConfiguration {
@Bean
public ConsulRegistrationCustomizer servletConsulCustomizer(
ObjectProvider<ServletContext> servletContext) {
public ConsulRegistrationCustomizer servletConsulCustomizer(ObjectProvider<ServletContext> servletContext) {
return new ConsulServletRegistrationCustomizer(servletContext);
}
}
protected static class OnConsulRegistrationEnabledCondition
extends AllNestedConditions {
protected static class OnConsulRegistrationEnabledCondition extends AllNestedConditions {
OnConsulRegistrationEnabledCondition() {
super(ConfigurationPhase.REGISTER_BEAN);
}
@ConditionalOnProperty(
value = "spring.cloud.service-registry.auto-registration.enabled",
matchIfMissing = true)
@ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true)
static class AutoRegistrationEnabledClass {
}
@ConditionalOnProperty(
value = "spring.cloud.consul.service-registry.auto-registration.enabled",
@ConditionalOnProperty(value = "spring.cloud.consul.service-registry.auto-registration.enabled",
matchIfMissing = true)
static class ConsulAutoRegistrationEnabledClass {
}
@ConditionalOnProperty(value = "spring.cloud.service-registry.enabled",
matchIfMissing = true)
@ConditionalOnProperty(value = "spring.cloud.service-registry.enabled", matchIfMissing = true)
static class ServiceRegistryEnabledClass {
}
@ConditionalOnProperty(value = "spring.cloud.consul.service-registry.enabled",
matchIfMissing = true)
@ConditionalOnProperty(value = "spring.cloud.consul.service-registry.enabled", matchIfMissing = true)
static class ConsulServiceRegistryEnabledClass {
}

View File

@@ -31,8 +31,7 @@ public class ConsulAutoServiceRegistrationListener implements SmartApplicationLi
private final ConsulAutoServiceRegistration autoServiceRegistration;
public ConsulAutoServiceRegistrationListener(
ConsulAutoServiceRegistration autoServiceRegistration) {
public ConsulAutoServiceRegistrationListener(ConsulAutoServiceRegistration autoServiceRegistration) {
this.autoServiceRegistration = autoServiceRegistration;
}
@@ -53,9 +52,7 @@ 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;
}
}

View File

@@ -52,8 +52,7 @@ public class ConsulServiceRegistry implements ServiceRegistry<ConsulRegistration
private final HeartbeatProperties heartbeatProperties;
public ConsulServiceRegistry(ConsulClient client,
ConsulDiscoveryProperties properties, TtlScheduler ttlScheduler,
public ConsulServiceRegistry(ConsulClient client, ConsulDiscoveryProperties properties, TtlScheduler ttlScheduler,
HeartbeatProperties heartbeatProperties) {
this.client = client;
this.properties = properties;
@@ -65,23 +64,19 @@ public class ConsulServiceRegistry implements ServiceRegistry<ConsulRegistration
public void register(ConsulRegistration reg) {
log.info("Registering service with consul: " + reg.getService());
try {
this.client.agentServiceRegister(reg.getService(),
this.properties.getAclToken());
this.client.agentServiceRegister(reg.getService(), this.properties.getAclToken());
NewService service = reg.getService();
if (this.heartbeatProperties.isEnabled() && this.ttlScheduler != null
&& service.getCheck() != null
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);
}
}
@@ -93,8 +88,7 @@ public class ConsulServiceRegistry implements ServiceRegistry<ConsulRegistration
if (log.isInfoEnabled()) {
log.info("Deregistering service with consul: " + reg.getInstanceId());
}
this.client.agentServiceDeregister(reg.getInstanceId(),
this.properties.getAclToken());
this.client.agentServiceDeregister(reg.getInstanceId(), this.properties.getAclToken());
}
@Override
@@ -120,8 +114,7 @@ public class ConsulServiceRegistry implements ServiceRegistry<ConsulRegistration
public Object getStatus(ConsulRegistration registration) {
String serviceId = registration.getServiceId();
Response<List<Check>> response = this.client.getHealthChecksForService(serviceId,
HealthChecksForServiceRequest.newBuilder()
.setQueryParams(QueryParams.DEFAULT).build());
HealthChecksForServiceRequest.newBuilder().setQueryParams(QueryParams.DEFAULT).build());
List<Check> checks = response.getValue();
for (Check check : checks) {

View File

@@ -45,11 +45,9 @@ public class ConsulServiceRegistryAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public ConsulServiceRegistry consulServiceRegistry(ConsulClient consulClient,
ConsulDiscoveryProperties properties, HeartbeatProperties heartbeatProperties,
@Autowired(required = false) TtlScheduler ttlScheduler) {
return new ConsulServiceRegistry(consulClient, properties, ttlScheduler,
heartbeatProperties);
public ConsulServiceRegistry consulServiceRegistry(ConsulClient consulClient, ConsulDiscoveryProperties properties,
HeartbeatProperties heartbeatProperties, @Autowired(required = false) TtlScheduler ttlScheduler) {
return new ConsulServiceRegistry(consulClient, properties, ttlScheduler, heartbeatProperties);
}
@Bean
@@ -65,21 +63,18 @@ public class ConsulServiceRegistryAutoConfiguration {
return new ConsulDiscoveryProperties(inetUtils);
}
protected static class OnConsulRegistrationEnabledCondition
extends AllNestedConditions {
protected static class OnConsulRegistrationEnabledCondition extends AllNestedConditions {
OnConsulRegistrationEnabledCondition() {
super(ConfigurationPhase.REGISTER_BEAN);
}
@ConditionalOnProperty(value = "spring.cloud.service-registry.enabled",
matchIfMissing = true)
@ConditionalOnProperty(value = "spring.cloud.service-registry.enabled", matchIfMissing = true)
static class ServiceRegistryEnabledClass {
}
@ConditionalOnProperty(value = "spring.cloud.consul.service-registry.enabled",
matchIfMissing = true)
@ConditionalOnProperty(value = "spring.cloud.consul.service-registry.enabled", matchIfMissing = true)
static class ConsulServiceRegistryEnabledClass {
}

View File

@@ -31,8 +31,7 @@ public class ConsulServletRegistrationCustomizer implements ConsulRegistrationCu
private ObjectProvider<ServletContext> servletContext;
public ConsulServletRegistrationCustomizer(
ObjectProvider<ServletContext> servletContext) {
public ConsulServletRegistrationCustomizer(ObjectProvider<ServletContext> servletContext) {
this.servletContext = servletContext;
}

View File

@@ -52,8 +52,7 @@ public class ConsulHeartbeatAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public TtlScheduler ttlScheduler(HeartbeatProperties heartbeatProperties,
ConsulClient consulClient) {
public TtlScheduler ttlScheduler(HeartbeatProperties heartbeatProperties, ConsulClient consulClient) {
return new TtlScheduler(heartbeatProperties, consulClient);
}

View File

@@ -52,8 +52,7 @@ public class ConsulDiscoveryClientAclTests {
@Test
public void getInstancesForThisServiceWorks() {
List<ServiceInstance> instances = this.discoveryClient
.getInstances("testConsulDiscoveryAcl");
List<ServiceInstance> instances = this.discoveryClient.getInstances("testConsulDiscoveryAcl");
assertThat(instances).as("instances was null").isNotNull();
assertThat(instances.isEmpty()).as("instances was empty").isFalse();
}
@@ -61,17 +60,14 @@ public class ConsulDiscoveryClientAclTests {
@Test
public void getInstancesForSecondServiceWorks() throws Exception {
new SpringApplicationBuilder(MyTestConfig.class)
.initializers(new ConsulTestcontainers())
.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).initializers(new ConsulTestcontainers()).run(
"--spring.application.name=testSecondServiceAcl", "--server.port=0",
"--spring.cloud.consul.discovery.preferIpAddress=true",
"--consul.token=2d2e6b3b-1c82-40ab-8171-54609d8ad304");
List<ServiceInstance> instances = this.discoveryClient
.getInstances("testSecondServiceAcl");
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();
assertThat(instances.isEmpty()).as("second service instances was empty").isFalse();
}
@Configuration(proxyBeanMethods = false)

View File

@@ -45,8 +45,7 @@ public class ConsulDiscoveryClientConfigurationTests {
@Test
public void consulConfigNotLoadedWhenDiscoveryClientDisabled() {
TestPropertyValues.of("spring.cloud.discovery.enabled=false")
.applyTo(this.context);
TestPropertyValues.of("spring.cloud.discovery.enabled=false").applyTo(this.context);
setupContext();
assertBeanNotPresent(ConsulDiscoveryProperties.class);
assertBeanNotPresent(ConsulDiscoveryClient.class);
@@ -55,9 +54,8 @@ public class ConsulDiscoveryClientConfigurationTests {
private void setupContext(Class<?>... config) {
ConfigurationPropertySources.attach(this.context.getEnvironment());
this.context.register(UtilAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class, ConsulAutoConfiguration.class,
ConsulDiscoveryClientConfiguration.class);
this.context.register(UtilAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class,
ConsulAutoConfiguration.class, ConsulDiscoveryClientConfiguration.class);
for (Class<?> value : config) {
this.context.register(value);
}

View File

@@ -46,8 +46,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
"spring.cloud.consul.discovery.instanceId=testConsulDiscovery2Id",
"spring.cloud.consul.discovery.hostname=testConsulDiscovery2Host",
"spring.cloud.consul.discovery.registerHealthCheck=false",
"spring.cloud.consul.discovery.tags=plaintag",
"spring.cloud.consul.discovery.metadata[foo]=bar",
"spring.cloud.consul.discovery.tags=plaintag", "spring.cloud.consul.discovery.metadata[foo]=bar",
"spring.cloud.consul.discovery.metadata[foo2]=bar2" },
webEnvironment = RANDOM_PORT)
@ContextConfiguration(initializers = ConsulTestcontainers.class)
@@ -64,14 +63,12 @@ public class ConsulDiscoveryClientCustomizedTests {
}
private void assertNotIpAddress(ServiceInstance instance) {
assertThat(InetAddressUtils.isIPv4Address(instance.getHost()))
.as("host is an ip address").isFalse();
assertThat(InetAddressUtils.isIPv4Address(instance.getHost())).as("host is an ip address").isFalse();
}
@Test
public void getMetadataWorks() throws InterruptedException {
List<ServiceInstance> instances = this.discoveryClient
.getInstances("testConsulDiscovery2");
List<ServiceInstance> instances = this.discoveryClient.getInstances("testConsulDiscovery2");
assertThat(instances).as("instances was null").isNotNull();
assertThat(instances.isEmpty()).as("instances was empty").isFalse();
@@ -80,10 +77,8 @@ public class ConsulDiscoveryClientCustomizedTests {
}
private void assertInstance(ServiceInstance instance) {
assertThat(instance.getInstanceId()).as("instance id was wrong")
.isEqualTo("testConsulDiscovery2Id");
assertThat(instance.getServiceId()).as("service id was wrong")
.isEqualTo("testConsulDiscovery2");
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();
assertThat(metadata).as("metadata was null").isNotNull();

View File

@@ -44,8 +44,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
* @author Piotr Wielgolaski
*/
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = MOCK,
classes = ConsulDiscoveryClientDefaultQueryTagTests.TestConfig.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" })

View File

@@ -40,10 +40,8 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
@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)
@ContextConfiguration(initializers = ConsulTestcontainers.class)
public class ConsulDiscoveryClientHttpsTests {
@@ -52,8 +50,7 @@ public class ConsulDiscoveryClientHttpsTests {
@Test
public void getInstancesForServiceWorks() {
List<ServiceInstance> instances = this.discoveryClient
.getInstances("testConsulDiscoveryHttps");
List<ServiceInstance> instances = this.discoveryClient.getInstances("testConsulDiscoveryHttps");
assertThat(instances).as("instances was null").isNotNull();
assertThat(instances.isEmpty()).as("instances was empty").isFalse();

View File

@@ -42,12 +42,9 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
* @author Joe Athman
*/
@RunWith(SpringRunner.class)
@SpringBootTest(
properties = { "spring.application.name=testConsulDiscovery",
"spring.cloud.consul.discovery.prefer-ip-address=true",
"spring.cloud.consul.discovery.metadata[foo]=bar" },
classes = ConsulDiscoveryClientTests.MyTestConfig.class,
webEnvironment = RANDOM_PORT)
@SpringBootTest(properties = { "spring.application.name=testConsulDiscovery",
"spring.cloud.consul.discovery.prefer-ip-address=true", "spring.cloud.consul.discovery.metadata[foo]=bar" },
classes = ConsulDiscoveryClientTests.MyTestConfig.class, webEnvironment = RANDOM_PORT)
@ContextConfiguration(initializers = ConsulTestcontainers.class)
public class ConsulDiscoveryClientTests {
@@ -59,8 +56,7 @@ public class ConsulDiscoveryClientTests {
@Test
public void getInstancesForServiceWorks() {
List<ServiceInstance> instances = this.discoveryClient
.getInstances("testConsulDiscovery");
List<ServiceInstance> instances = this.discoveryClient.getInstances("testConsulDiscovery");
assertThat(instances).as("instances was null").isNotNull();
assertThat(instances.isEmpty()).as("instances was empty").isFalse();
@@ -72,13 +68,12 @@ public class ConsulDiscoveryClientTests {
@Test
public void getInstancesForServiceRespectsQueryParams() {
Response<List<String>> catalogDatacenters = this.consulClient
.getCatalogDatacenters();
Response<List<String>> catalogDatacenters = this.consulClient.getCatalogDatacenters();
List<String> dataCenterList = catalogDatacenters.getValue();
assertThat(dataCenterList.isEmpty()).as("no data centers found").isFalse();
List<ServiceInstance> instances = this.discoveryClient.getInstances(
"testConsulDiscovery", new QueryParams(dataCenterList.get(0)));
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);
@@ -86,8 +81,7 @@ public class ConsulDiscoveryClientTests {
}
private void assertIpAddress(ServiceInstance instance) {
assertThat(Character.isDigit(instance.getHost().charAt(0)))
.as("host isn't an ip address").isTrue();
assertThat(Character.isDigit(instance.getHost().charAt(0))).as("host isn't an ip address").isTrue();
}
@Configuration(proxyBeanMethods = false)

View File

@@ -39,18 +39,15 @@ public class ConsulDiscoveryPropertiesTests {
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> serverListQueryTags = Collections.singletonMap(SERVICE_NAME_IN_MAP, MAP_TAG);
private final Map<String, String> datacenters = Collections
.singletonMap(SERVICE_NAME_IN_MAP, MAP_DC);
private final Map<String, String> datacenters = Collections.singletonMap(SERVICE_NAME_IN_MAP, MAP_DC);
private ConsulDiscoveryProperties properties;
@Before
public void setUp() {
this.properties = new ConsulDiscoveryProperties(
new InetUtils(new InetUtilsProperties()));
this.properties = new ConsulDiscoveryProperties(new InetUtils(new InetUtilsProperties()));
this.properties.setDefaultQueryTag(DEFAULT_TAG);
this.properties.setServerListQueryTags(this.serverListQueryTags);
this.properties.setDatacenters(this.datacenters);
@@ -60,39 +57,33 @@ public class ConsulDiscoveryPropertiesTests {
public void testReturnsNullWhenNoDefaultAndNotInMap() {
this.properties.setDefaultQueryTag(null);
assertThat(this.properties.getQueryTagForService(SERVICE_NAME_NOT_IN_MAP))
.isNull();
assertThat(this.properties.getQueryTagForService(SERVICE_NAME_NOT_IN_MAP)).isNull();
}
@Test
public void testGetTagReturnsDefaultWhenNotInMap() {
assertThat(this.properties.getQueryTagForService(SERVICE_NAME_NOT_IN_MAP))
.isEqualTo(DEFAULT_TAG);
assertThat(this.properties.getQueryTagForService(SERVICE_NAME_NOT_IN_MAP)).isEqualTo(DEFAULT_TAG);
}
@Test
public void testGetTagReturnsMapValueWhenInMap() {
assertThat(this.properties.getQueryTagForService(SERVICE_NAME_IN_MAP))
.isEqualTo(MAP_TAG);
assertThat(this.properties.getQueryTagForService(SERVICE_NAME_IN_MAP)).isEqualTo(MAP_TAG);
}
@Test
public void testGetDcReturnsNullWhenNotInMap() {
assertThat(this.properties.getDatacenters().get(SERVICE_NAME_NOT_IN_MAP))
.isNull();
assertThat(this.properties.getDatacenters().get(SERVICE_NAME_NOT_IN_MAP)).isNull();
}
@Test
public void testGetDcReturnsMapValueWhenInMap() {
assertThat(this.properties.getDatacenters().get(SERVICE_NAME_IN_MAP))
.isEqualTo(MAP_DC);
assertThat(this.properties.getDatacenters().get(SERVICE_NAME_IN_MAP)).isEqualTo(MAP_DC);
}
@Test
public void testAddManagementTag() {
this.properties.getManagementTags().add("newTag");
assertThat(this.properties.getManagementTags())
.containsOnly(ConsulDiscoveryProperties.MANAGEMENT, "newTag");
assertThat(this.properties.getManagementTags()).containsOnly(ConsulDiscoveryProperties.MANAGEMENT, "newTag");
}
}

View File

@@ -40,8 +40,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" },
"spring.cloud.consul.discovery.prefer-ip-address=true", "spring.cloud.consul.discovery.tags=foo=bar" },
webEnvironment = RANDOM_PORT)
@ContextConfiguration(initializers = ConsulTestcontainers.class)
public class ConsulLoadbalancerClientTests {
@@ -61,8 +60,7 @@ public class ConsulLoadbalancerClientTests {
}
private void assertIpAddress(ServiceInstance instance) {
assertThat(Character.isDigit(instance.getHost().charAt(0)))
.as("host isn't an ip address").isTrue();
assertThat(Character.isDigit(instance.getHost().charAt(0))).as("host isn't an ip address").isTrue();
}
@SpringBootConfiguration

View File

@@ -48,11 +48,9 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
* @author Stéphane Leroy
*/
@RunWith(SpringRunner.class)
@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" },
@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)
@ContextConfiguration(initializers = ConsulTestcontainers.class)
public class TtlSchedulerRemoveTests {
@@ -68,21 +66,18 @@ 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(serviceCheck.getStatus()).as("Service check is in wrong state")
.isEqualTo(PASSING);
assertThat(serviceCheck.getStatus()).as("Service check is in wrong state").isEqualTo(PASSING);
// Remove service from TtlScheduler and wait for TTL to expired.
this.ttlScheduler.remove("ttlSchedulerRemove-id");
Thread.sleep(2100);
serviceCheck = getCheckForService("ttlSchedulerRemove");
assertThat(serviceCheck.getStatus()).as("Service check is in wrong state")
.isEqualTo(CRITICAL);
assertThat(serviceCheck.getStatus()).as("Service check is in wrong state").isEqualTo(CRITICAL);
}
private Check getCheckForService(String serviceId) {
Response<List<Check>> checkResponse = this.consul
.getHealthChecksForService(serviceId, HealthChecksForServiceRequest
.newBuilder().setQueryParams(QueryParams.DEFAULT).build());
Response<List<Check>> checkResponse = this.consul.getHealthChecksForService(serviceId,
HealthChecksForServiceRequest.newBuilder().setQueryParams(QueryParams.DEFAULT).build());
if (checkResponse.getValue().size() > 0) {
return checkResponse.getValue().get(0);
}
@@ -92,8 +87,7 @@ public class TtlSchedulerRemoveTests {
@Configuration(proxyBeanMethods = false)
@EnableAutoConfiguration
@Import({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class,
ConsulDiscoveryClientConfiguration.class,
ConsulHeartbeatAutoConfiguration.class })
ConsulDiscoveryClientConfiguration.class, ConsulHeartbeatAutoConfiguration.class })
public static class TtlSchedulerRemoveTestConfig {
}

View File

@@ -50,8 +50,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
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" },
"spring.cloud.consul.discovery.heartbeat.ttlValue=2", "management.server.port=0" },
webEnvironment = RANDOM_PORT)
@ContextConfiguration(initializers = ConsulTestcontainers.class)
public class TtlSchedulerTests {
@@ -60,14 +59,12 @@ public class TtlSchedulerTests {
private ConsulClient consul;
@Test
public void should_send_a_check_before_ttl_for_all_services()
throws InterruptedException {
public void should_send_a_check_before_ttl_for_all_services() throws InterruptedException {
Thread.sleep(2100); // Wait for TTL to expired (TTL is set to 2 seconds)
Check serviceCheck = getCheckForService("ttlScheduler");
assertThat(serviceCheck).isNotNull();
assertThat(serviceCheck.getStatus()).isEqualTo(PASSING)
.as("Service check is in wrong state");
assertThat(serviceCheck.getStatus()).isEqualTo(PASSING).as("Service check is in wrong state");
Check serviceManagementCheck = getCheckForService("ttlScheduler-management");
assertThat(serviceManagementCheck).isNotNull();
assertThat(serviceManagementCheck.getStatus()).isEqualTo(PASSING)
@@ -75,9 +72,8 @@ public class TtlSchedulerTests {
}
private Check getCheckForService(String serviceId) {
Response<List<Check>> checkResponse = this.consul
.getHealthChecksForService(serviceId, HealthChecksForServiceRequest
.newBuilder().setQueryParams(QueryParams.DEFAULT).build());
Response<List<Check>> checkResponse = this.consul.getHealthChecksForService(serviceId,
HealthChecksForServiceRequest.newBuilder().setQueryParams(QueryParams.DEFAULT).build());
if (checkResponse.getValue().size() > 0) {
return checkResponse.getValue().get(0);
}
@@ -87,8 +83,7 @@ public class TtlSchedulerTests {
@Configuration(proxyBeanMethods = false)
@EnableAutoConfiguration
@Import({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class,
ConsulDiscoveryClientConfiguration.class,
ConsulHeartbeatAutoConfiguration.class })
ConsulDiscoveryClientConfiguration.class, ConsulHeartbeatAutoConfiguration.class })
public static class TtlSchedulerTestConfig {
}

View File

@@ -45,31 +45,22 @@ public class ConsulConfigServerAutoConfigurationTests {
@Test
public void offByDefault() {
this.context = new AnnotationConfigApplicationContext(
ConsulConfigServerAutoConfiguration.class);
assertThat(
this.context.getBeanNamesForType(ConsulDiscoveryProperties.class).length)
.isEqualTo(0);
this.context = new AnnotationConfigApplicationContext(ConsulConfigServerAutoConfiguration.class);
assertThat(this.context.getBeanNamesForType(ConsulDiscoveryProperties.class).length).isEqualTo(0);
}
@Test
public void onWhenRequested() {
setup("spring.cloud.config.server.prefix=/config",
"spring.cloud.consul.discovery.tags-as-metadata=false");
assertThat(
this.context.getBeanNamesForType(ConsulDiscoveryProperties.class).length)
.isEqualTo(1);
ConsulDiscoveryProperties properties = this.context
.getBean(ConsulDiscoveryProperties.class);
setup("spring.cloud.config.server.prefix=/config", "spring.cloud.consul.discovery.tags-as-metadata=false");
assertThat(this.context.getBeanNamesForType(ConsulDiscoveryProperties.class).length).isEqualTo(1);
ConsulDiscoveryProperties properties = this.context.getBean(ConsulDiscoveryProperties.class);
assertThat(properties.getMetadata()).containsEntry("configPath", "/config");
}
private void setup(String... env) {
this.context = new SpringApplicationBuilder(
PropertyPlaceholderAutoConfiguration.class,
this.context = new SpringApplicationBuilder(PropertyPlaceholderAutoConfiguration.class,
ConsulConfigServerAutoConfiguration.class, ConfigServerProperties.class,
ConsulDiscoveryProperties.class).web(WebApplicationType.NONE)
.properties(env).run();
ConsulDiscoveryProperties.class).web(WebApplicationType.NONE).properties(env).run();
}
}

View File

@@ -67,30 +67,23 @@ public class DiscoveryClientConfigServiceAutoConfigurationTests {
ConsulTestcontainers.start();
Integer port = ConsulTestcontainers.getPort();
String host = ConsulTestcontainers.getHost();
setup("server.port=0", "spring.cloud.config.discovery.enabled=true",
"spring.cloud.consul.port=" + port, "spring.cloud.consul.host=" + host,
"logging.level.org.springframework.cloud.config.client=DEBUG",
setup("server.port=0", "spring.cloud.config.discovery.enabled=true", "spring.cloud.consul.port=" + port,
"spring.cloud.consul.host=" + host, "logging.level.org.springframework.cloud.config.client=DEBUG",
"spring.cloud.consul.discovery.catalog-services-watch.enabled=false",
"spring.cloud.consul.discovery.test.enabled:true",
"spring.application.name=discoveryclientconfigservicetest",
"spring.jmx.enabled=false", "spring.cloud.consul.discovery.port:7001",
"spring.cloud.consul.discovery.hostname:foo",
"spring.application.name=discoveryclientconfigservicetest", "spring.jmx.enabled=false",
"spring.cloud.consul.discovery.port:7001", "spring.cloud.consul.discovery.hostname:foo",
"spring.cloud.config.discovery.service-id:configserver");
assertThat(this.context
.getBeanNamesForType(ConsulConfigServerAutoConfiguration.class).length)
.isEqualTo(1);
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);
ConfigClientProperties locator = this.context.getBean(ConfigClientProperties.class);
assertThat(locator.getUri()[0]).isEqualTo("http://foo:7001/");
}
private void setup(String... env) {
this.context = new SpringApplicationBuilder(TestConfig.class).properties(env)
.run();
this.context = new SpringApplicationBuilder(TestConfig.class).properties(env).run();
}
@Configuration(proxyBeanMethods = false)

View File

@@ -29,17 +29,15 @@ import org.springframework.context.annotation.Configuration;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@ConditionalOnProperty(value = "spring.cloud.consul.discovery.test.enabled",
matchIfMissing = false)
@ConditionalOnProperty(value = "spring.cloud.consul.discovery.test.enabled", matchIfMissing = false)
@Configuration(proxyBeanMethods = false)
public class TestConsulDiscoveryClientBootstrapConfiguration {
@Bean
public ConsulDiscoveryClient consulDiscoveryClient(
ConsulDiscoveryProperties properties) {
public ConsulDiscoveryClient consulDiscoveryClient(ConsulDiscoveryProperties properties) {
ConsulDiscoveryClient client = mock(ConsulDiscoveryClient.class);
ServiceInstance instance = new DefaultServiceInstance("configserver1",
"configserver", properties.getHostname(), properties.getPort(), false);
ServiceInstance instance = new DefaultServiceInstance("configserver1", "configserver", properties.getHostname(),
properties.getPort(), false);
given(client.getInstances("configserver")).willReturn(Arrays.asList(instance));
return client;
}

View File

@@ -34,87 +34,68 @@ import static org.assertj.core.api.Assertions.assertThat;
*/
class ConsulReactiveDiscoveryClientConfigurationTests {
private ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(UtilAutoConfiguration.class,
ReactiveCommonsClientAutoConfiguration.class,
ConsulAutoConfiguration.class,
ConsulReactiveDiscoveryClientConfiguration.class));
private ApplicationContextRunner contextRunner = new ApplicationContextRunner().withConfiguration(
AutoConfigurations.of(UtilAutoConfiguration.class, ReactiveCommonsClientAutoConfiguration.class,
ConsulAutoConfiguration.class, ConsulReactiveDiscoveryClientConfiguration.class));
@Test
public void shouldWorkWithDefaults() {
contextRunner.run(context -> {
assertThat(context).hasSingleBean(ReactiveDiscoveryClient.class);
assertThat(context)
.hasSingleBean(ReactiveDiscoveryClientHealthIndicator.class);
assertThat(context).hasSingleBean(ReactiveDiscoveryClientHealthIndicator.class);
});
}
@Test
public void shouldNotHaveDiscoveryClientWhenDiscoveryDisabled() {
contextRunner.withPropertyValues("spring.cloud.discovery.enabled=false")
.run(context -> {
assertThat(context).doesNotHaveBean("consulReactiveDiscoveryClient");
assertThat(context).doesNotHaveBean(ReactiveDiscoveryClient.class);
assertThat(context).doesNotHaveBean(
ReactiveDiscoveryClientHealthIndicator.class);
});
contextRunner.withPropertyValues("spring.cloud.discovery.enabled=false").run(context -> {
assertThat(context).doesNotHaveBean("consulReactiveDiscoveryClient");
assertThat(context).doesNotHaveBean(ReactiveDiscoveryClient.class);
assertThat(context).doesNotHaveBean(ReactiveDiscoveryClientHealthIndicator.class);
});
}
@Test
public void shouldNotHaveDiscoveryClientWhenReactiveDiscoveryDisabled() {
contextRunner.withPropertyValues("spring.cloud.discovery.reactive.enabled=false")
.run(context -> {
assertThat(context).doesNotHaveBean("consulReactiveDiscoveryClient");
assertThat(context).doesNotHaveBean(ReactiveDiscoveryClient.class);
assertThat(context).doesNotHaveBean(
ReactiveDiscoveryClientHealthIndicator.class);
});
contextRunner.withPropertyValues("spring.cloud.discovery.reactive.enabled=false").run(context -> {
assertThat(context).doesNotHaveBean("consulReactiveDiscoveryClient");
assertThat(context).doesNotHaveBean(ReactiveDiscoveryClient.class);
assertThat(context).doesNotHaveBean(ReactiveDiscoveryClientHealthIndicator.class);
});
}
@Test
public void shouldNotHaveDiscoveryClientWhenConsulDisabled() {
contextRunner.withPropertyValues("spring.cloud.consul.enabled=false")
.run(context -> {
assertThat(context).doesNotHaveBean("consulReactiveDiscoveryClient");
assertThat(context).doesNotHaveBean(ReactiveDiscoveryClient.class);
assertThat(context).doesNotHaveBean(
ReactiveDiscoveryClientHealthIndicator.class);
});
contextRunner.withPropertyValues("spring.cloud.consul.enabled=false").run(context -> {
assertThat(context).doesNotHaveBean("consulReactiveDiscoveryClient");
assertThat(context).doesNotHaveBean(ReactiveDiscoveryClient.class);
assertThat(context).doesNotHaveBean(ReactiveDiscoveryClientHealthIndicator.class);
});
}
@Test
public void shouldNotHaveDiscoveryClientWhenConsulDiscoveryDisabled() {
contextRunner.withPropertyValues("spring.cloud.consul.discovery.enabled=false")
.run(context -> {
assertThat(context).doesNotHaveBean("consulReactiveDiscoveryClient");
assertThat(context).doesNotHaveBean(ReactiveDiscoveryClient.class);
assertThat(context).doesNotHaveBean(
ReactiveDiscoveryClientHealthIndicator.class);
});
contextRunner.withPropertyValues("spring.cloud.consul.discovery.enabled=false").run(context -> {
assertThat(context).doesNotHaveBean("consulReactiveDiscoveryClient");
assertThat(context).doesNotHaveBean(ReactiveDiscoveryClient.class);
assertThat(context).doesNotHaveBean(ReactiveDiscoveryClientHealthIndicator.class);
});
}
@Test
public void worksWithoutWebflux() {
contextRunner
.withClassLoader(
new FilteredClassLoader("org.springframework.web.reactive"))
.run(context -> {
assertThat(context).doesNotHaveBean(ReactiveDiscoveryClient.class);
assertThat(context).doesNotHaveBean(
ReactiveDiscoveryClientHealthIndicator.class);
});
contextRunner.withClassLoader(new FilteredClassLoader("org.springframework.web.reactive")).run(context -> {
assertThat(context).doesNotHaveBean(ReactiveDiscoveryClient.class);
assertThat(context).doesNotHaveBean(ReactiveDiscoveryClientHealthIndicator.class);
});
}
@Test
public void worksWithoutActuator() {
contextRunner
.withClassLoader(
new FilteredClassLoader("org.springframework.boot.actuate"))
.run(context -> {
assertThat(context).hasSingleBean(ReactiveDiscoveryClient.class);
assertThat(context).doesNotHaveBean(
ReactiveDiscoveryClientHealthIndicator.class);
});
contextRunner.withClassLoader(new FilteredClassLoader("org.springframework.boot.actuate")).run(context -> {
assertThat(context).hasSingleBean(ReactiveDiscoveryClient.class);
assertThat(context).doesNotHaveBean(ReactiveDiscoveryClientHealthIndicator.class);
});
}
}

View File

@@ -65,8 +65,7 @@ class ConsulReactiveDiscoveryClientTests {
@Test
public void verifyDefaults() {
when(properties.getOrder()).thenReturn(1);
assertThat(client.description())
.isEqualTo("Spring Cloud Consul Reactive Discovery Client");
assertThat(client.description()).isEqualTo("Spring Cloud Consul Reactive Discovery Client");
assertThat(client.getOrder()).isEqualTo(1);
}
@@ -82,8 +81,7 @@ class ConsulReactiveDiscoveryClientTests {
@Test
public void shouldReturnFluxOfServices() {
Flux<String> services = client.getServices();
when(consulClient.getCatalogServices(any(CatalogServicesRequest.class)))
.thenReturn(consulServicesResponse());
when(consulClient.getCatalogServices(any(CatalogServicesRequest.class))).thenReturn(consulServicesResponse());
StepVerifier.create(services).expectNext("my-service").expectComplete().verify();
verify(properties).getAclToken();
verify(consulClient).getCatalogServices(any(CatalogServicesRequest.class));
@@ -92,8 +90,7 @@ class ConsulReactiveDiscoveryClientTests {
@Test
public void shouldReturnFluxOfServicesWithAclToken() {
when(properties.getAclToken()).thenReturn("aclToken");
when(consulClient.getCatalogServices(any(CatalogServicesRequest.class)))
.thenReturn(consulServicesResponse());
when(consulClient.getCatalogServices(any(CatalogServicesRequest.class))).thenReturn(consulServicesResponse());
Flux<String> services = client.getServices();
StepVerifier.create(services).expectNext("my-service").expectComplete().verify();
verify(properties, times(1)).getAclToken();
@@ -103,9 +100,8 @@ class ConsulReactiveDiscoveryClientTests {
@Test
public void shouldReturnEmptyFluxForNonExistingService() {
configureCommonProperties();
when(consulClient.getHealthServices(eq("nonexistent-service"),
any(HealthServicesRequest.class)))
.thenReturn(emptyConsulInstancesResponse());
when(consulClient.getHealthServices(eq("nonexistent-service"), any(HealthServicesRequest.class)))
.thenReturn(emptyConsulInstancesResponse());
Flux<ServiceInstance> instances = client.getInstances("nonexistent-service");
StepVerifier.create(instances).expectNextCount(0).expectComplete().verify();
verify(properties).getAclToken();
@@ -115,9 +111,8 @@ class ConsulReactiveDiscoveryClientTests {
@Test
public void shouldReturnEmptyFluxWhenConsulFails() {
configureCommonProperties();
when(consulClient.getHealthServices(eq("existing-service"),
any(HealthServicesRequest.class)))
.thenThrow(new RuntimeException("Possible runtime exception"));
when(consulClient.getHealthServices(eq("existing-service"), any(HealthServicesRequest.class)))
.thenThrow(new RuntimeException("Possible runtime exception"));
Flux<ServiceInstance> instances = client.getInstances("existing-service");
StepVerifier.create(instances).expectNextCount(0).expectComplete().verify();
verify(consulClient).getHealthServices(eq("existing-service"), any());
@@ -127,8 +122,8 @@ class ConsulReactiveDiscoveryClientTests {
public void shouldReturnFluxOfServiceInstances() {
configureCommonProperties();
Response<List<HealthService>> response = consulInstancesResponse();
when(consulClient.getHealthServices(eq("existing-service"),
any(HealthServicesRequest.class))).thenReturn(response);
when(consulClient.getHealthServices(eq("existing-service"), any(HealthServicesRequest.class)))
.thenReturn(response);
Flux<ServiceInstance> instances = client.getInstances("existing-service");
StepVerifier.create(instances).expectNextCount(1).expectComplete().verify();
verify(properties).getAclToken();
@@ -142,8 +137,8 @@ class ConsulReactiveDiscoveryClientTests {
configureCommonProperties();
when(properties.getAclToken()).thenReturn("aclToken");
Response<List<HealthService>> response = consulInstancesResponse();
when(consulClient.getHealthServices(eq("existing-service"),
any(HealthServicesRequest.class))).thenReturn(response);
when(consulClient.getHealthServices(eq("existing-service"), any(HealthServicesRequest.class)))
.thenReturn(response);
Flux<ServiceInstance> instances = client.getInstances("existing-service");
StepVerifier.create(instances).expectNextCount(1).expectComplete().verify();
verify(properties, times(1)).getAclToken();
@@ -153,8 +148,7 @@ class ConsulReactiveDiscoveryClientTests {
}
private Response<Map<String, List<String>>> consulServicesResponse() {
return new Response<>(singletonMap("my-service", singletonList("")), 0L, true,
System.currentTimeMillis());
return new Response<>(singletonMap("my-service", singletonList("")), 0L, true, System.currentTimeMillis());
}
private void configureCommonProperties() {
@@ -175,8 +169,7 @@ class ConsulReactiveDiscoveryClientTests {
when(service.getPort()).thenReturn(443);
lenient().when(service.getTags()).thenReturn(singletonList("secure=true"));
return new Response<>(singletonList(healthService), 0L, true,
System.currentTimeMillis());
return new Response<>(singletonList(healthService), 0L, true, System.currentTimeMillis());
}
}

View File

@@ -38,10 +38,8 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Niko Tung
*/
@RunWith(SpringRunner.class)
@SpringBootTest(
classes = ConsulAutoRegistrationCheckTtlDeregisterCriticalServiceTests.TestConfig.class,
properties = {
"spring.application.name=myConsulServiceRegistryHealthCheckTtlDeregisterCriticalServiceAfter-N",
@SpringBootTest(classes = ConsulAutoRegistrationCheckTtlDeregisterCriticalServiceTests.TestConfig.class,
properties = { "spring.application.name=myConsulServiceRegistryHealthCheckTtlDeregisterCriticalServiceAfter-N",
"spring.cloud.consul.discovery.health-check-critical-timeout=1m",
"spring.cloud.consul.discovery.heartbeat.enabled=true" },
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@@ -55,16 +53,13 @@ public class ConsulAutoRegistrationCheckTtlDeregisterCriticalServiceTests {
public void contextLoads() {
NewService service = registration.getService();
assertThat("1m".equals(service.getCheck().getDeregisterCriticalServiceAfter()))
.as("Service with heartbeat check and deregister critical timeout registered")
.isTrue();
.as("Service with heartbeat check and deregister critical timeout registered").isTrue();
}
@Configuration(proxyBeanMethods = false)
@EnableAutoConfiguration
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
ConsulAutoConfiguration.class,
ConsulAutoServiceRegistrationAutoConfiguration.class,
ConsulHeartbeatAutoConfiguration.class })
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class,
ConsulAutoServiceRegistrationAutoConfiguration.class, ConsulHeartbeatAutoConfiguration.class })
protected static class TestConfig {
}

View File

@@ -40,8 +40,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ConsulAutoRegistrationHealthCheckHeadersTests.TestConfig.class,
properties = {
"spring.application.name=myTestService-DiscoveryHealthCheckTlsSkipVerify",
properties = { "spring.application.name=myTestService-DiscoveryHealthCheckTlsSkipVerify",
"spring.cloud.consul.discovery.health-check-headers.X-Config-Token=ACCESSTOKEN" },
webEnvironment = RANDOM_PORT)
@ContextConfiguration(initializers = ConsulTestcontainers.class)
@@ -62,16 +61,15 @@ public class ConsulAutoRegistrationHealthCheckHeadersTests {
assertThat(check).as("check was null").isNotNull();
assertThat(check.getHeader()).as("header is null").isNotNull();
assertThat(check.getHeader()).as("header is empty").isNotEmpty();
assertThat(check.getHeader().get("X-Config-Token").get(0))
.as("expected header value not found").isEqualTo("ACCESSTOKEN");
assertThat(check.getHeader().get("X-Config-Token").get(0)).as("expected header value not found")
.isEqualTo("ACCESSTOKEN");
// unable to call consul api to get health check details
}
@Configuration(proxyBeanMethods = false)
@EnableAutoConfiguration
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
ConsulAutoConfiguration.class,
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class,
ConsulAutoServiceRegistrationAutoConfiguration.class })
public static class TestConfig {

View File

@@ -39,10 +39,8 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
* @author Patrick Hi
*/
@RunWith(SpringRunner.class)
@SpringBootTest(
classes = ConsulAutoRegistrationHealthCheckTlsSkipVerifyTests.TestConfig.class,
properties = {
"spring.application.name=myTestService-DiscoveryHealthCheckTlsSkipVerify",
@SpringBootTest(classes = ConsulAutoRegistrationHealthCheckTlsSkipVerifyTests.TestConfig.class,
properties = { "spring.application.name=myTestService-DiscoveryHealthCheckTlsSkipVerify",
"spring.cloud.consul.discovery.health-check-tls-skip-verify=true" },
webEnvironment = RANDOM_PORT)
@ContextConfiguration(initializers = ConsulTestcontainers.class)
@@ -61,16 +59,14 @@ public class ConsulAutoRegistrationHealthCheckTlsSkipVerifyTests {
NewService.Check check = service.getCheck();
assertThat(check).as("check was null").isNotNull();
assertThat(check.getTlsSkipVerify()).as("tls_skip_verify was wrong")
.isEqualTo(Boolean.TRUE);
assertThat(check.getTlsSkipVerify()).as("tls_skip_verify was wrong").isEqualTo(Boolean.TRUE);
// unable to call consul api to get health check details
}
@Configuration(proxyBeanMethods = false)
@EnableAutoConfiguration
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
ConsulAutoConfiguration.class,
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class,
ConsulAutoServiceRegistrationAutoConfiguration.class })
public static class TestConfig {

View File

@@ -39,10 +39,8 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
* @author varnson
*/
@RunWith(SpringRunner.class)
@SpringBootTest(
classes = ConsulAutoRegistrationIncludeHostnameInInstanceIdTests.TestConfig.class,
properties = {
"spring.application.name=myTestService-IncludeHostnameInInstanceId",
@SpringBootTest(classes = ConsulAutoRegistrationIncludeHostnameInInstanceIdTests.TestConfig.class,
properties = { "spring.application.name=myTestService-IncludeHostnameInInstanceId",
"spring.cloud.consul.discovery.include-hostname-in-instance-id=true",
"spring.cloud.client.hostname=testhostname" },
webEnvironment = RANDOM_PORT)
@@ -63,15 +61,13 @@ public class ConsulAutoRegistrationIncludeHostnameInInstanceIdTests {
NewService.Check check = service.getCheck();
assertThat(service.getId()).as("id is null").isNotNull();
assertThat(service.getId()).as("id no include hostname").contains("testhostname");
assertThat(service.getId()).as("service id was wrong")
.isEqualTo(this.registration.getInstanceId());
assertThat(service.getId()).as("service id was wrong").isEqualTo(this.registration.getInstanceId());
}
@Configuration(proxyBeanMethods = false)
@EnableAutoConfiguration
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
ConsulAutoConfiguration.class,
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class,
ConsulAutoServiceRegistrationAutoConfiguration.class })
public static class TestConfig {

View File

@@ -62,10 +62,8 @@ public class ConsulAutoServiceDeRegistrationDisabledTests {
@Test
public void contextLoads() {
assertThat(this.autoServiceRegistration)
.as("ConsulAutoServiceRegistration was not created").isNotNull();
assertThat(this.discoveryProperties)
.as("ConsulDiscoveryProperties was not created").isNotNull();
assertThat(this.autoServiceRegistration).as("ConsulAutoServiceRegistration was not created").isNotNull();
assertThat(this.discoveryProperties).as("ConsulDiscoveryProperties was not created").isNotNull();
checkService(true);
this.autoServiceRegistration.deregister();
@@ -89,8 +87,7 @@ public class ConsulAutoServiceDeRegistrationDisabledTests {
@Configuration(proxyBeanMethods = false)
@EnableAutoConfiguration
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
ConsulAutoConfiguration.class,
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class,
ConsulAutoServiceRegistrationAutoConfiguration.class })
public static class TestConfig {

View File

@@ -43,8 +43,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
* @author Spencer Gibb
*/
@RunWith(SpringRunner.class)
@SpringBootTest(
classes = ConsulAutoServiceRegistrationCustomizedAgentAddressTests.TestConfig.class,
@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}",
@@ -63,18 +62,14 @@ public class ConsulAutoServiceRegistrationCustomizedAgentAddressTests {
Service service = services.get("myTestService1-AA");
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();
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(proxyBeanMethods = false)
@EnableAutoConfiguration
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
ConsulAutoConfiguration.class,
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class,
ConsulAutoServiceRegistrationAutoConfiguration.class })
public static class TestConfig {

View File

@@ -42,10 +42,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)
@ContextConfiguration(initializers = ConsulTestcontainers.class)
public class ConsulAutoServiceRegistrationCustomizedDiscoveryPortTests {
@@ -77,9 +75,8 @@ public class ConsulAutoServiceRegistrationCustomizedDiscoveryPortTests {
NewService.Check check = service.getCheck();
assertThat(check).as("check was null").isNotNull();
String httpCheck = String.format("%s://%s:%s%s", this.properties.getScheme(),
this.properties.getHostname(), this.properties.getPort(),
this.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
@@ -87,8 +84,7 @@ public class ConsulAutoServiceRegistrationCustomizedDiscoveryPortTests {
@Configuration(proxyBeanMethods = false)
@EnableAutoConfiguration
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
ConsulAutoConfiguration.class,
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class,
ConsulAutoServiceRegistrationAutoConfiguration.class })
public static class TestConfig {

View File

@@ -44,8 +44,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
* @author Jin Zhang
*/
@RunWith(SpringRunner.class)
@SpringBootTest(
classes = ConsulAutoServiceRegistrationCustomizedInstanceGroupTests.TestConfig.class,
@SpringBootTest(classes = ConsulAutoServiceRegistrationCustomizedInstanceGroupTests.TestConfig.class,
properties = { "spring.application.name=myTestService-WithGroup",
"spring.cloud.consul.discovery.instanceId=myTestService1-WithGroup",
"spring.cloud.consul.discovery.instanceGroup=test" },
@@ -67,10 +66,8 @@ public class ConsulAutoServiceRegistrationCustomizedInstanceGroupTests {
Service service = services.get("myTestService1-WithGroup");
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();
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(this.consul,
// this.properties);
@@ -86,8 +83,7 @@ public class ConsulAutoServiceRegistrationCustomizedInstanceGroupTests {
@Configuration(proxyBeanMethods = false)
@EnableAutoConfiguration
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
ConsulAutoConfiguration.class,
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class,
ConsulAutoServiceRegistrationAutoConfiguration.class })
public static class TestConfig {

View File

@@ -42,8 +42,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
* @author Sixian Liu
*/
@RunWith(SpringRunner.class)
@SpringBootTest(
classes = ConsulAutoServiceRegistrationCustomizedInstanceZoneTests.TestConfig.class,
@SpringBootTest(classes = ConsulAutoServiceRegistrationCustomizedInstanceZoneTests.TestConfig.class,
properties = { "spring.application.name=myTestService-WithZone",
"spring.cloud.consul.discovery.instanceId=myTestService1-WithZone",
"spring.cloud.consul.discovery.instanceZone=zone1",
@@ -62,16 +61,13 @@ public class ConsulAutoServiceRegistrationCustomizedInstanceZoneTests {
Service service = services.get("myTestService1-WithZone");
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.getMeta()).as("service zone was wrong").containsEntry("myZone",
"zone1");
assertThat(service.getId()).as("service id was wrong").isEqualTo("myTestService1-WithZone");
assertThat(service.getMeta()).as("service zone was wrong").containsEntry("myZone", "zone1");
}
@Configuration(proxyBeanMethods = false)
@EnableAutoConfiguration
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
ConsulAutoConfiguration.class,
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class,
ConsulAutoServiceRegistrationAutoConfiguration.class })
public static class TestConfig {

View File

@@ -47,8 +47,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
* @author Lomesh Patel (lomeshpatel)
*/
@RunWith(SpringRunner.class)
@SpringBootTest(
classes = ConsulAutoServiceRegistrationCustomizedManagementServicePortTests.TestConfig.class,
@SpringBootTest(classes = ConsulAutoServiceRegistrationCustomizedManagementServicePortTests.TestConfig.class,
properties = { "spring.application.name=myTestService-GG",
"spring.cloud.consul.discovery.instanceId=myTestService1-GG",
"spring.cloud.consul.discovery.registerHealthCheck=false",
@@ -76,37 +75,30 @@ public class ConsulAutoServiceRegistrationCustomizedManagementServicePortTests {
final Service service = services.get("myTestService1-GG");
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")
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");
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.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")
assertThat(managementService.getAddress())
.as("management service address must equals hostname from discovery properties")
.isEqualTo(this.discoveryProperties.getHostname());
}
@Configuration(proxyBeanMethods = false)
@EnableAutoConfiguration
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
ConsulAutoConfiguration.class,
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class,
ConsulAutoServiceRegistrationAutoConfiguration.class })
public static class TestConfig {

View File

@@ -49,22 +49,15 @@ 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",
"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",
"spring.cloud.consul.discovery.default-zone-metadata-name=mydefaultzonemetadataname",
"spring.cloud.consul.discovery.instance-zone=myzone",
"spring.cloud.consul.discovery.instance-group=mygroup",
"spring.cloud.consul.discovery.tags[0]=mytag",
"spring.cloud.consul.discovery.enableTagOverride=true",
"spring.cloud.consul.discovery.metadata.key1=value1",
"spring.cloud.consul.discovery.metadata.key2=value2" },
@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",
"spring.cloud.consul.discovery.default-zone-metadata-name=mydefaultzonemetadataname",
"spring.cloud.consul.discovery.instance-zone=myzone", "spring.cloud.consul.discovery.instance-group=mygroup",
"spring.cloud.consul.discovery.tags[0]=mytag", "spring.cloud.consul.discovery.enableTagOverride=true",
"spring.cloud.consul.discovery.metadata.key1=value1", "spring.cloud.consul.discovery.metadata.key2=value2" },
webEnvironment = RANDOM_PORT)
@ContextConfiguration(initializers = ConsulTestcontainers.class)
public class ConsulAutoServiceRegistrationCustomizedPropsTests {
@@ -81,22 +74,14 @@ public class ConsulAutoServiceRegistrationCustomizedPropsTests {
Map<String, Service> services = response.getValue();
Service service = services.get("myTestService1-B");
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());
assertThat(service.getEnableTagOverride())
.as("property enableTagOverride was wrong").isTrue();
assertThat(service.getTags()).as("property tags contains the wrong values")
.containsExactly("mytag");
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());
assertThat(service.getEnableTagOverride()).as("property enableTagOverride was wrong").isTrue();
assertThat(service.getTags()).as("property tags contains the wrong values").containsExactly("mytag");
HashMap<String, String> entries = new HashMap<>();
entries.put("key1", "value1");
entries.put("key2", "value2");
@@ -106,23 +91,20 @@ public class ConsulAutoServiceRegistrationCustomizedPropsTests {
assertThat(service.getMeta()).as("property metadata contains the wrong entries")
.containsExactlyInAnyOrderEntriesOf(entries);
Response<List<Check>> checkResponse = this.consul.getHealthChecksForService(
"myTestService-B", HealthChecksForServiceRequest.newBuilder()
.setQueryParams(QueryParams.DEFAULT).build());
Response<List<Check>> checkResponse = this.consul.getHealthChecksForService("myTestService-B",
HealthChecksForServiceRequest.newBuilder().setQueryParams(QueryParams.DEFAULT).build());
List<Check> checks = checkResponse.getValue();
assertThat(checks).as("checks was wrong size").hasSize(0);
}
@Test
public void testFailFastDisabled() {
assertThat(this.properties.isFailFast()).as("property failFast was wrong")
.isFalse();
assertThat(this.properties.isFailFast()).as("property failFast was wrong").isFalse();
}
@Configuration(proxyBeanMethods = false)
@EnableAutoConfiguration
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
ConsulAutoConfiguration.class,
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class,
ConsulAutoServiceRegistrationAutoConfiguration.class })
public static class TestPropsConfig {

View File

@@ -42,8 +42,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
* @author Spencer Gibb
*/
@RunWith(SpringRunner.class)
@SpringBootTest(
classes = ConsulAutoServiceRegistrationCustomizedServiceNameTests.TestConfig.class,
@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}" },
@@ -61,16 +60,13 @@ public class ConsulAutoServiceRegistrationCustomizedServiceNameTests {
Service service = services.get("myTestService1-CC");
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");
assertThat(service.getId()).as("service id was wrong").isEqualTo("myTestService1-CC");
assertThat(service.getService()).as("service name was wrong").isEqualTo("myprefix-myTestService-CC");
}
@Configuration(proxyBeanMethods = false)
@EnableAutoConfiguration
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
ConsulAutoConfiguration.class,
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class,
ConsulAutoServiceRegistrationAutoConfiguration.class })
public static class TestConfig {

View File

@@ -40,8 +40,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
* @author Piotr Wielgolaski
*/
@RunWith(SpringRunner.class)
@SpringBootTest(
classes = ConsulAutoServiceRegistrationCustomizedServletContextTests.TestConfig.class,
@SpringBootTest(classes = ConsulAutoServiceRegistrationCustomizedServletContextTests.TestConfig.class,
properties = { "spring.application.name=myTestService-WithServletContext",
"spring.cloud.consul.discovery.instanceId=myTestService1-WithServletContext",
"server.servlet.context-path=/customContext" },
@@ -59,10 +58,8 @@ public class ConsulAutoServiceRegistrationCustomizedServletContextTests {
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

View File

@@ -41,8 +41,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ConsulAutoServiceRegistrationCustomizedTests.MyTestConfig.class,
properties = { "spring.application.name=testCustomAutoServiceRegistration" },
webEnvironment = RANDOM_PORT)
properties = { "spring.application.name=testCustomAutoServiceRegistration" }, webEnvironment = RANDOM_PORT)
@ContextConfiguration(initializers = ConsulTestcontainers.class)
public class ConsulAutoServiceRegistrationCustomizedTests {
@@ -57,27 +56,24 @@ public class ConsulAutoServiceRegistrationCustomizedTests {
@Test
public void usesCustomConsulLifecycle() {
assertThat(this.registration1.getConfiguration())
.as("configuration is not customized").isEqualTo("customconfiguration");
assertThat(this.registration2.getConfiguration())
.as("configuration is not customized").isEqualTo("customconfiguration");
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,
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class,
ConsulAutoServiceRegistrationAutoConfiguration.class })
public static class MyTestConfig {
@Bean
public CustomAutoRegistration consulAutoServiceRegistration(
ConsulServiceRegistry serviceRegistry,
public CustomAutoRegistration consulAutoServiceRegistration(ConsulServiceRegistry serviceRegistry,
AutoServiceRegistrationProperties autoServiceRegistrationProperties,
ConsulDiscoveryProperties properties,
ConsulAutoRegistration registration) {
return new CustomAutoRegistration(serviceRegistry,
autoServiceRegistrationProperties, properties, registration);
ConsulDiscoveryProperties properties, ConsulAutoRegistration registration) {
return new CustomAutoRegistration(serviceRegistry, autoServiceRegistrationProperties, properties,
registration);
}
}
@@ -87,10 +83,8 @@ public class ConsulAutoServiceRegistrationCustomizedTests {
@Autowired
public CustomAutoRegistration(ConsulServiceRegistry serviceRegistry,
AutoServiceRegistrationProperties autoServiceRegistrationProperties,
ConsulDiscoveryProperties properties,
ConsulAutoRegistration registration) {
super(serviceRegistry, autoServiceRegistrationProperties, properties,
registration);
ConsulDiscoveryProperties properties, ConsulAutoRegistration registration) {
super(serviceRegistry, autoServiceRegistrationProperties, properties, registration);
}
@Override

View File

@@ -42,9 +42,8 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
* @author Spencer Gibb
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ConsulAutoServiceRegistrationDefaultPortTests.TestConfig.class,
properties = { "spring.application.name=myTestService2-DD",
"spring.cloud.consul.discovery.instanceId=myTestService2-DD" },
@SpringBootTest(classes = ConsulAutoServiceRegistrationDefaultPortTests.TestConfig.class, properties = {
"spring.application.name=myTestService2-DD", "spring.cloud.consul.discovery.instanceId=myTestService2-DD" },
webEnvironment = RANDOM_PORT)
@ContextConfiguration(initializers = ConsulTestcontainers.class)
public class ConsulAutoServiceRegistrationDefaultPortTests {
@@ -63,8 +62,7 @@ public class ConsulAutoServiceRegistrationDefaultPortTests {
@Configuration(proxyBeanMethods = false)
@EnableAutoConfiguration
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
ConsulAutoConfiguration.class,
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class,
ConsulAutoServiceRegistrationAutoConfiguration.class })
public static class TestConfig {

View File

@@ -49,29 +49,23 @@ public class ConsulAutoServiceRegistrationDisabledTests {
@Test
public void disabledViaSpringCloudServiceRegistryProperty() {
testAutoRegistrationDisabled("myTestNotRegisteredService4",
"spring.cloud.service-registry.enabled");
testAutoRegistrationDisabled("myTestNotRegisteredService4", "spring.cloud.service-registry.enabled");
}
@Test
public void disabledViaConsulServiceRegistryProperty() {
testAutoRegistrationDisabled("myTestNotRegisteredService5",
"spring.cloud.consul.service-registry.enabled");
testAutoRegistrationDisabled("myTestNotRegisteredService5", "spring.cloud.consul.service-registry.enabled");
}
private void testAutoRegistrationDisabled(String testName, String disableProperty) {
new WebApplicationContextRunner().withUserConfiguration(TestConfig.class)
.withPropertyValues("spring.application.name=" + testName,
disableProperty + "=false", "server.port=0")
.withPropertyValues("spring.application.name=" + testName, disableProperty + "=false", "server.port=0")
.withInitializer(new ConsulTestcontainers()).run(context -> {
assertThat(context)
.doesNotHaveBean(ConsulAutoServiceRegistration.class);
assertThat(context)
.doesNotHaveBean(ConsulAutoServiceRegistrationListener.class);
assertThat(context).doesNotHaveBean(ConsulAutoServiceRegistration.class);
assertThat(context).doesNotHaveBean(ConsulAutoServiceRegistrationListener.class);
assertThat(context).doesNotHaveBean(ConsulAutoRegistration.class);
assertThat(context)
.doesNotHaveBean(ConsulRegistrationCustomizer.class);
assertThat(context).doesNotHaveBean(ConsulRegistrationCustomizer.class);
ConsulClient consul = context.getBean(ConsulClient.class);

View File

@@ -51,17 +51,14 @@ public class ConsulAutoServiceRegistrationFailFastTests {
@Test
public void testFailFastEnabled() {
this.exception.expectCause(isA(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,
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class,
ConsulAutoServiceRegistrationAutoConfiguration.class })
protected static class TestConfig {

View File

@@ -43,12 +43,11 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
* @author Alexey Savchuk (devpreview)
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {
ConsulAutoServiceRegistrationManagementCustomizerTests.TestConfig.class,
ConsulAutoServiceRegistrationManagementCustomizerTests.ManagementConfig.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" },
"spring.cloud.consul.discovery.registerHealthCheck=false", "management.server.port=4453" },
webEnvironment = RANDOM_PORT)
@ContextConfiguration(initializers = ConsulTestcontainers.class)
public class ConsulAutoServiceRegistrationManagementCustomizerTests {
@@ -61,17 +60,11 @@ public class ConsulAutoServiceRegistrationManagementCustomizerTests {
@Test
public void contextLoads() {
ConsulAutoRegistration managementRegistration = this.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());
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();
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(proxyBeanMethods = false)
@@ -105,8 +98,7 @@ public class ConsulAutoServiceRegistrationManagementCustomizerTests {
@Configuration(proxyBeanMethods = false)
@EnableAutoConfiguration
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
ConsulAutoConfiguration.class,
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class,
ConsulAutoServiceRegistrationAutoConfiguration.class })
public static class TestConfig {

View File

@@ -44,13 +44,11 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
* @author Dmitry Zhikharev (jihor)
*/
@RunWith(SpringRunner.class)
@SpringBootTest(
classes = ConsulAutoServiceRegistrationManagementDisabledServiceTests.TestConfig.class,
@SpringBootTest(classes = ConsulAutoServiceRegistrationManagementDisabledServiceTests.TestConfig.class,
properties = { "spring.application.name=myTestService-NM",
"spring.cloud.consul.discovery.instanceId=myTestService1-NM",
"spring.cloud.service-registry.auto-registration.register-management=false",
"spring.cloud.consul.discovery.managementPort=4453",
"management.port=0" },
"spring.cloud.consul.discovery.managementPort=4453", "management.port=0" },
webEnvironment = RANDOM_PORT)
@ContextConfiguration(initializers = ConsulTestcontainers.class)
public class ConsulAutoServiceRegistrationManagementDisabledServiceTests {
@@ -72,22 +70,17 @@ public class ConsulAutoServiceRegistrationManagementDisabledServiceTests {
Service service = services.get("myTestService1-NM");
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")
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());
}
@Configuration(proxyBeanMethods = false)
@EnableAutoConfiguration
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
ConsulAutoConfiguration.class,
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class,
ConsulAutoServiceRegistrationAutoConfiguration.class })
public static class TestConfig {

View File

@@ -45,11 +45,9 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
* @author Lomesh Patel (lomeshpatel)
*/
@RunWith(SpringRunner.class)
@SpringBootTest(
classes = ConsulAutoServiceRegistrationManagementServiceTests.TestConfig.class,
@SpringBootTest(classes = ConsulAutoServiceRegistrationManagementServiceTests.TestConfig.class,
properties = { "spring.application.name=myTestService-EE",
"spring.cloud.consul.discovery.registerHealthCheck=false",
"management.server.port=4452" },
"spring.cloud.consul.discovery.registerHealthCheck=false", "management.server.port=4452" },
webEnvironment = RANDOM_PORT)
@ContextConfiguration(initializers = ConsulTestcontainers.class)
public class ConsulAutoServiceRegistrationManagementServiceTests {
@@ -68,35 +66,29 @@ public class ConsulAutoServiceRegistrationManagementServiceTests {
final Service service = services.get("myTestService-EE-0");
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")
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");
assertThat(managementService).as("management service was null").isNotNull();
assertThat(managementService.getPort().intValue())
.as("management service port was wrong").isEqualTo(4452);
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")
assertThat(managementService.getAddress())
.as("management service address must equals hostname from discovery properties")
.isEqualTo(this.discoveryProperties.getHostname());
}
@Configuration(proxyBeanMethods = false)
@EnableAutoConfiguration
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
ConsulAutoConfiguration.class,
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class,
ConsulAutoServiceRegistrationAutoConfiguration.class })
public static class TestConfig {

View File

@@ -41,8 +41,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ConsulAutoServiceRegistrationNonWebTests.TestConfig.class,
properties = { "spring.application.name=consulNonWebTest", "server.port=32111" },
webEnvironment = NONE)
properties = { "spring.application.name=consulNonWebTest", "server.port=32111" }, webEnvironment = NONE)
@ContextConfiguration(initializers = ConsulTestcontainers.class)
public class ConsulAutoServiceRegistrationNonWebTests {
@@ -54,8 +53,7 @@ public class ConsulAutoServiceRegistrationNonWebTests {
@Test
public void contextLoads() {
assertThat(this.autoServiceRegistration)
.as("ConsulAutoServiceRegistration was created").isNotNull();
assertThat(this.autoServiceRegistration).as("ConsulAutoServiceRegistration was created").isNotNull();
Response<Map<String, Service>> response = this.consul.getAgentServices();
Map<String, Service> services = response.getValue();

Some files were not shown because too many files have changed in this diff Show More