Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support Spring RestClient as TransportClientFactory #4281

Merged
merged 23 commits into from
Nov 4, 2024
Merged
Show file tree
Hide file tree
Changes from 18 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions docs/modules/ROOT/pages/spring-cloud-netflix.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -270,9 +270,9 @@ It is initialized in a `SmartLifecycle` (with `phase=0`), so the earliest you ca

==== Underlying HTTP clients

`EurekaClient` uses either `RestTemplate`, `WebClient` or `JerseyClient` under the hood. In order to use the `EurekaClient`, you need to have one of the supported HTTP clients on your classpath.
`EurekaClient` uses either `RestClient`, `RestTemplate`, `WebClient` or `JerseyClient` under the hood. In order to use the `EurekaClient`, you need to have one of the supported HTTP clients on your classpath.

To use `RestTemplate`, add `spring-boot-starter-web` to your dependencies. To use `WebClient`, add `spring-boot-starter-webflux` to your dependencies. If both `RestTemplate` and `WebClient` are on the classpath when `eureka.client.webclient.enabled` is set to `true`, `WebClient` is used. Otherwise, `RestTemplate` is used.
To use `RestTemplate` or `RestClient`, add `spring-boot-starter-web` to your dependencies. To use `WebClient`, add `spring-boot-starter-webflux` to your dependencies. If both `spring-boot-starter-web` and `spring-boot-starter-webflux` are included in the dependencies and the `eureka.client.webclient.enabled` flag is set to `true`, then `WebClient` will be used. If that's not the case and `eureka.client.restclient.enabled` is set to true, the `RestClient` will be used. Otherwise, the `RestTemplate` will be used.

If you wish to use Jersey instead, you need to add the Jersey dependencies to your classpath.
The following example shows the dependencies you need to add:
Expand Down
211 changes: 106 additions & 105 deletions docs/modules/ROOT/partials/_configprops.adoc

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,6 @@
import org.apache.commons.logging.LogFactory;

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.AllNestedConditions;
import org.springframework.boot.autoconfigure.condition.AnyNestedCondition;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
Expand All @@ -42,19 +40,23 @@
import org.springframework.cloud.netflix.eureka.RestTemplateTimeoutProperties;
import org.springframework.cloud.netflix.eureka.http.DefaultEurekaClientHttpRequestFactorySupplier;
import org.springframework.cloud.netflix.eureka.http.EurekaClientHttpRequestFactorySupplier;
import org.springframework.cloud.netflix.eureka.http.RestClientDiscoveryClientOptionalArgs;
import org.springframework.cloud.netflix.eureka.http.RestClientTransportClientFactories;
import org.springframework.cloud.netflix.eureka.http.RestTemplateDiscoveryClientOptionalArgs;
import org.springframework.cloud.netflix.eureka.http.RestTemplateTransportClientFactories;
import org.springframework.cloud.netflix.eureka.http.WebClientDiscoveryClientOptionalArgs;
import org.springframework.cloud.netflix.eureka.http.WebClientTransportClientFactories;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestClient;
import org.springframework.web.reactive.function.client.WebClient;

/**
* @author Daniel Lavoie
* @author Armin Krezovic
* @author Olga Maciaszek-Sharma
* @author Wonchul Heo
*/
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(RestTemplateTimeoutProperties.class)
Expand All @@ -70,14 +72,14 @@ public TlsProperties tlsProperties() {

@Bean
@ConditionalOnClass(name = "org.springframework.web.client.RestTemplate")
@Conditional(JerseyClientNotPresentOrNotEnabledCondition.class)
heowc marked this conversation as resolved.
Show resolved Hide resolved
@Conditional(RestTemplateEnabledCondition.class)
@ConditionalOnMissingBean(value = { AbstractDiscoveryClientOptionalArgs.class }, search = SearchStrategy.CURRENT)
@ConditionalOnProperty(prefix = "eureka.client", name = "webclient.enabled", matchIfMissing = true,
heowc marked this conversation as resolved.
Show resolved Hide resolved
heowc marked this conversation as resolved.
Show resolved Hide resolved
havingValue = "false")
public RestTemplateDiscoveryClientOptionalArgs restTemplateDiscoveryClientOptionalArgs(TlsProperties tlsProperties,
EurekaClientHttpRequestFactorySupplier eurekaClientHttpRequestFactorySupplier,
ObjectProvider<RestTemplateBuilder> restTemplateBuilders) throws GeneralSecurityException, IOException {
logger.info("Eureka HTTP Client uses RestTemplate.");
if (logger.isInfoEnabled()) {
logger.info("Eureka HTTP Client uses RestTemplate.");
}
RestTemplateDiscoveryClientOptionalArgs result = new RestTemplateDiscoveryClientOptionalArgs(
eurekaClientHttpRequestFactorySupplier, restTemplateBuilders::getIfAvailable);
setupTLS(result, tlsProperties);
Expand Down Expand Up @@ -112,13 +114,15 @@ private static void setupTLS(AbstractDiscoveryClientOptionalArgs<?> args, TlsPro
}

@Configuration(proxyBeanMethods = false)
@Conditional(JerseyClientPresentAndEnabledCondition.class)
@Conditional(RestTemplateEnabledCondition.class)
@ConditionalOnBean(value = AbstractDiscoveryClientOptionalArgs.class, search = SearchStrategy.CURRENT)
heowc marked this conversation as resolved.
Show resolved Hide resolved
static class DiscoveryClientOptionalArgsTlsConfiguration {

DiscoveryClientOptionalArgsTlsConfiguration(TlsProperties tlsProperties,
AbstractDiscoveryClientOptionalArgs optionalArgs) throws GeneralSecurityException, IOException {
logger.info("Eureka HTTP Client uses Jersey");
if (logger.isInfoEnabled()) {
logger.info("Eureka HTTP Client uses Jersey");
}
setupTLS(optionalArgs, tlsProperties);
}

Expand All @@ -129,16 +133,15 @@ static class DiscoveryClientOptionalArgsTlsConfiguration {
@ConditionalOnProperty(prefix = "eureka.client", name = "webclient.enabled", havingValue = "true")
protected static class WebClientConfiguration {

@Autowired
private TlsProperties tlsProperties;

@Bean
@ConditionalOnMissingBean(
value = { AbstractDiscoveryClientOptionalArgs.class, RestTemplateDiscoveryClientOptionalArgs.class },
search = SearchStrategy.CURRENT)
public WebClientDiscoveryClientOptionalArgs webClientDiscoveryClientOptionalArgs(
public WebClientDiscoveryClientOptionalArgs webClientDiscoveryClientOptionalArgs(TlsProperties tlsProperties,
ObjectProvider<WebClient.Builder> builder) throws GeneralSecurityException, IOException {
logger.info("Eureka HTTP Client uses WebClient.");
if (logger.isInfoEnabled()) {
logger.info("Eureka HTTP Client uses WebClient.");
}
WebClientDiscoveryClientOptionalArgs result = new WebClientDiscoveryClientOptionalArgs(
builder::getIfAvailable);
setupTLS(result, tlsProperties);
Expand Down Expand Up @@ -168,19 +171,27 @@ public WebClientNotFoundConfiguration() {

}

static class JerseyClientPresentAndEnabledCondition extends AllNestedConditions {
static class RestTemplateEnabledCondition extends AnyNestedCondition {

JerseyClientPresentAndEnabledCondition() {
RestTemplateEnabledCondition() {
super(ConfigurationPhase.REGISTER_BEAN);
}

@ConditionalOnClass(name = "org.glassfish.jersey.client.JerseyClient")
static class OnJerseyClientPresent {
heowc marked this conversation as resolved.
Show resolved Hide resolved
@ConditionalOnProperty(value = "eureka.client.jersey.enabled", matchIfMissing = true)
static class OnJerseyClientEnabled {

}

@ConditionalOnProperty(value = "eureka.client.jersey.enabled", matchIfMissing = true)
static class OnJerseyClientEnabled {
@ConditionalOnProperty(prefix = "eureka.client", name = "webclient.enabled", matchIfMissing = true,
havingValue = "false")
static class OnWebClientDisabled {

}

@ConditionalOnProperty(prefix = "eureka.client", name = "restclient.enabled", matchIfMissing = true,
havingValue = "false")
static class OnRestClientDisabled {

}

Expand All @@ -204,4 +215,32 @@ static class OnJerseyClientDisabled {

}

@ConditionalOnMissingClass("org.glassfish.jersey.client.JerseyClient")
heowc marked this conversation as resolved.
Show resolved Hide resolved
@ConditionalOnClass(name = "org.springframework.web.client.RestClient")
@ConditionalOnProperty(prefix = "eureka.client", name = "restclient.enabled", havingValue = "true")
heowc marked this conversation as resolved.
Show resolved Hide resolved
heowc marked this conversation as resolved.
Show resolved Hide resolved
protected static class RestClientConfiguration {
heowc marked this conversation as resolved.
Show resolved Hide resolved
heowc marked this conversation as resolved.
Show resolved Hide resolved

@Bean
@ConditionalOnMissingBean(value = { AbstractDiscoveryClientOptionalArgs.class },
search = SearchStrategy.CURRENT)
public RestClientDiscoveryClientOptionalArgs restClientDiscoveryClientOptionalArgs(TlsProperties tlsProperties,
ObjectProvider<RestClient.Builder> builder) throws GeneralSecurityException, IOException {
if (logger.isInfoEnabled()) {
logger.info("Eureka HTTP Client uses RestClient.");
}
RestClientDiscoveryClientOptionalArgs result = new RestClientDiscoveryClientOptionalArgs(
builder::getIfAvailable);
setupTLS(result, tlsProperties);
return result;
}

@Bean
@ConditionalOnMissingBean(value = TransportClientFactories.class, search = SearchStrategy.CURRENT)
public RestClientTransportClientFactories restClientTransportClientFactories(
ObjectProvider<RestClient.Builder> builder) {
return new RestClientTransportClientFactories(builder::getIfAvailable);
}

}

}
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.SearchStrategy;
import org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfiguration;
import org.springframework.boot.autoconfigure.web.client.RestClientAutoConfiguration;
import org.springframework.boot.autoconfigure.web.reactive.function.client.WebClientAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.client.RestTemplateBuilder;
Expand All @@ -37,6 +38,8 @@
import org.springframework.cloud.netflix.eureka.RestTemplateTimeoutProperties;
import org.springframework.cloud.netflix.eureka.http.DefaultEurekaClientHttpRequestFactorySupplier;
import org.springframework.cloud.netflix.eureka.http.EurekaClientHttpRequestFactorySupplier;
import org.springframework.cloud.netflix.eureka.http.RestClientEurekaHttpClient;
import org.springframework.cloud.netflix.eureka.http.RestClientTransportClientFactory;
import org.springframework.cloud.netflix.eureka.http.RestTemplateEurekaHttpClient;
import org.springframework.cloud.netflix.eureka.http.RestTemplateTransportClientFactory;
import org.springframework.cloud.netflix.eureka.http.WebClientEurekaHttpClient;
Expand All @@ -46,6 +49,7 @@
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.lang.Nullable;
import org.springframework.web.client.RestClient;
import org.springframework.web.reactive.function.client.WebClient;

/**
Expand All @@ -54,6 +58,7 @@
*
* @author Dave Syer
* @author Armin Krezovic
* @author Wonchul Heo
*/
@ConditionalOnClass(ConfigServicePropertySourceLocator.class)
@Conditional(EurekaConfigServerBootstrapConfiguration.EurekaConfigServerBootstrapCondition.class)
Expand Down Expand Up @@ -109,6 +114,22 @@ public WebClientEurekaHttpClient configDiscoveryWebClientEurekaHttpClient(Eureka

}

@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(name = "org.springframework.web.client.RestClient")
@ConditionalOnProperty(prefix = "eureka.client", name = "restclient.enabled", havingValue = "true")
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

After some more consideration, I actually think we could switch to using RestClient by default in case of the non-blocking stack, so let's add matchIfMissing=true and @ConditionalOnProperty(prefix = "eureka.client", name = "restclient.enabled", havingValue = "false") to the RestTemplate-based configuration. Sorry for the confusion.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added related conditions while changing JerseyClientNotPresentOrNotEnabledCondition to RestTemplateEnabledCondition. Is this what you intended? 🤔

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, the logic after your changes has been modified - please take a look at the review comments.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

스크린샷 2024-10-27 오후 10 53 08

I think I understood it a little differently, but I think you should change JerseyClientNotPresentOrNotEnabledCondition to RestTemplateEnabledCondition for the same issue. Don't you think so??

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If there is something I misunderstood, please let me know.

  1. Modify the eureka.client.restclient.enabled annotation I added as follows.
@ConditionalOnProperty(prefix = "eureka.client", name = "restclient.enabled", havingValue = "true")

->

@ConditionalOnProperty(prefix = "eureka.client", name = "restclient.enabled", havingValue = "true", matchIfMissing = true)
  1. Then, set the following annotation to the configuration beans that are set based on RestTemplate.
@ConditionalOnProperty(prefix = "eureka.client", name = "restclient.enabled", havingValue = "false")

However, if I set it like this, some tests will fail. The reason is that matchIfMissing is changed so that it should default to RestTemplate, but it changes to RestClient, or even RestTemplate is not set, so the bean is not configured.

@ImportAutoConfiguration(RestClientAutoConfiguration.class)
protected static class RestClientConfiguration {

@Bean
@ConditionalOnMissingBean(EurekaHttpClient.class)
public RestClientEurekaHttpClient configDiscoveryRestClientEurekaHttpClient(EurekaClientConfigBean config,
ObjectProvider<RestClient.Builder> builder, Environment env) {
return (RestClientEurekaHttpClient) new RestClientTransportClientFactory(builder::getIfAvailable)
.newClient(HostnameBasedUrlRandomizer.randomEndpoint(config, env));
}

}

static class EurekaConfigServerBootstrapCondition extends AllNestedConditions {

EurekaConfigServerBootstrapCondition() {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
/*
* Copyright 2017-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.springframework.cloud.netflix.eureka.http;

import java.net.URI;
import java.net.URISyntaxException;

import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;
import com.fasterxml.jackson.databind.ser.std.BeanSerializerBase;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.converters.jackson.mixin.ApplicationsJsonMixIn;
import com.netflix.discovery.converters.jackson.mixin.InstanceInfoJsonMixIn;
import com.netflix.discovery.converters.jackson.serializer.InstanceInfoJsonBeanSerializer;
import com.netflix.discovery.shared.Applications;
import com.netflix.discovery.shared.transport.EurekaHttpClient;

import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.lang.Nullable;

/**
* Utility class for dealing with {@link EurekaHttpClient}.
*
* @author Daniel Lavoie
* @author Wonchul Heo
* @since 4.2.0
*/
final class EurekaHttpClientUtils {

private EurekaHttpClientUtils() {
throw new AssertionError("Must not instantiate constant utility class");
}

/**
* Provides the serialization configurations required by the Eureka Server. JSON
* content exchanged with eureka requires a root node matching the entity being
* serialized or deserialized. Achieved with
* {@link SerializationFeature#WRAP_ROOT_VALUE} and
* {@link DeserializationFeature#UNWRAP_ROOT_VALUE}.
* {@link PropertyNamingStrategies.SnakeCaseStrategy} is applied to the underlying
* {@link ObjectMapper}.
* @return a {@link MappingJackson2HttpMessageConverter} object
*/
static MappingJackson2HttpMessageConverter mappingJacksonHttpMessageConverter() {
final MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setObjectMapper(objectMapper());
return converter;
}

/**
* Provides the serialization configurations required by the Eureka Server. JSON
* content exchanged with eureka requires a root node matching the entity being
* serialized or deserialized. Achieved with
* {@link SerializationFeature#WRAP_ROOT_VALUE} and
* {@link DeserializationFeature#UNWRAP_ROOT_VALUE}.
* {@link PropertyNamingStrategies.SnakeCaseStrategy} is applied to the underlying
* {@link ObjectMapper}.
* @return a {@link ObjectMapper} object
*/
static ObjectMapper objectMapper() {
final ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE);

final SimpleModule jsonModule = new SimpleModule();
jsonModule.setSerializerModifier(createJsonSerializerModifier());
objectMapper.registerModule(jsonModule);

objectMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
objectMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
objectMapper.addMixIn(Applications.class, ApplicationsJsonMixIn.class);
objectMapper.addMixIn(InstanceInfo.class, InstanceInfoJsonMixIn.class);

return objectMapper;
}

private static BeanSerializerModifier createJsonSerializerModifier() {
return new BeanSerializerModifier() {
@Override
public JsonSerializer<?> modifySerializer(SerializationConfig config, BeanDescription beanDesc,
JsonSerializer<?> serializer) {
if (beanDesc.getBeanClass().isAssignableFrom(InstanceInfo.class)) {
return new InstanceInfoJsonBeanSerializer((BeanSerializerBase) serializer, false);
}
return serializer;
}
};
}

@Nullable
static UserInfo extractUserInfo(String serviceUrl) {
heowc marked this conversation as resolved.
Show resolved Hide resolved
try {
final URI serviceURI = new URI(serviceUrl);
if (serviceURI.getUserInfo() != null) {
final String[] credentials = serviceURI.getUserInfo().split(":");
if (credentials.length == 2) {
return new UserInfo(credentials[0], credentials[1]);
}
}
}
catch (URISyntaxException ignore) {
}
return null;
}

record UserInfo(String username, String password) {
}

}
Loading