Optimize starters auto-configuration. (main) (#391)

pull/398/head
VOPEN.XYZ 2 years ago committed by GitHub
parent d10752a70d
commit 789b1dfdfb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -55,15 +55,15 @@ import static javax.servlet.DispatcherType.REQUEST;
* *
* @author Haotian Zhang * @author Haotian Zhang
*/ */
@Configuration @Configuration(proxyBeanMethods = false)
public class MetadataTransferAutoConfiguration { public class MetadataTransferAutoConfiguration {
/** /**
* Create when web application type is SERVLET. * Create when web application type is SERVLET.
*/ */
@Configuration @Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
static class MetadataServletFilterConfig { protected static class MetadataServletFilterConfig {
@Bean @Bean
public FilterRegistrationBean<DecodeTransferMetadataServletFilter> metadataServletFilterRegistrationBean( public FilterRegistrationBean<DecodeTransferMetadataServletFilter> metadataServletFilterRegistrationBean(
@ -85,9 +85,9 @@ public class MetadataTransferAutoConfiguration {
/** /**
* Create when web application type is REACTIVE. * Create when web application type is REACTIVE.
*/ */
@Configuration @Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE) @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
static class MetadataReactiveFilterConfig { protected static class MetadataReactiveFilterConfig {
@Bean @Bean
public DecodeTransferMetadataReactiveFilter metadataReactiveFilter() { public DecodeTransferMetadataReactiveFilter metadataReactiveFilter() {
@ -99,9 +99,9 @@ public class MetadataTransferAutoConfiguration {
/** /**
* Create when gateway application is Zuul. * Create when gateway application is Zuul.
*/ */
@Configuration @Configuration(proxyBeanMethods = false)
@ConditionalOnClass(name = "com.netflix.zuul.http.ZuulServlet") @ConditionalOnClass(name = "com.netflix.zuul.http.ZuulServlet")
static class MetadataTransferZuulFilterConfig { protected static class MetadataTransferZuulFilterConfig {
@Bean @Bean
public ZuulFilter encodeTransferMetadataZuulFilter() { public ZuulFilter encodeTransferMetadataZuulFilter() {
@ -113,9 +113,9 @@ public class MetadataTransferAutoConfiguration {
/** /**
* Create when gateway application is SCG. * Create when gateway application is SCG.
*/ */
@Configuration @Configuration(proxyBeanMethods = false)
@ConditionalOnClass(name = "org.springframework.cloud.gateway.filter.GlobalFilter") @ConditionalOnClass(name = "org.springframework.cloud.gateway.filter.GlobalFilter")
static class MetadataTransferScgFilterConfig { protected static class MetadataTransferScgFilterConfig {
@Bean @Bean
public GlobalFilter encodeTransferMedataScgFilter() { public GlobalFilter encodeTransferMedataScgFilter() {
@ -127,9 +127,9 @@ public class MetadataTransferAutoConfiguration {
/** /**
* Create when Feign exists. * Create when Feign exists.
*/ */
@Configuration @Configuration(proxyBeanMethods = false)
@ConditionalOnClass(name = "feign.Feign") @ConditionalOnClass(name = "feign.Feign")
static class MetadataTransferFeignInterceptorConfig { protected static class MetadataTransferFeignInterceptorConfig {
@Bean @Bean
public EncodeTransferMedataFeignInterceptor encodeTransferMedataFeignInterceptor() { public EncodeTransferMedataFeignInterceptor encodeTransferMedataFeignInterceptor() {
@ -141,9 +141,9 @@ public class MetadataTransferAutoConfiguration {
/** /**
* Create when RestTemplate exists. * Create when RestTemplate exists.
*/ */
@Configuration @Configuration(proxyBeanMethods = false)
@ConditionalOnClass(name = "org.springframework.web.client.RestTemplate") @ConditionalOnClass(name = "org.springframework.web.client.RestTemplate")
static class MetadataTransferRestTemplateConfig implements ApplicationContextAware { protected static class MetadataTransferRestTemplateConfig implements ApplicationContextAware {
private ApplicationContext context; private ApplicationContext context;
@ -181,7 +181,7 @@ public class MetadataTransferAutoConfiguration {
public static class EncodeTransferMetadataRestTemplatePostProcessor public static class EncodeTransferMetadataRestTemplatePostProcessor
implements BeanPostProcessor { implements BeanPostProcessor {
private EncodeTransferMedataRestTemplateInterceptor encodeTransferMedataRestTemplateInterceptor; private final EncodeTransferMedataRestTemplateInterceptor encodeTransferMedataRestTemplateInterceptor;
EncodeTransferMetadataRestTemplatePostProcessor( EncodeTransferMetadataRestTemplatePostProcessor(
EncodeTransferMedataRestTemplateInterceptor encodeTransferMedataRestTemplateInterceptor) { EncodeTransferMedataRestTemplateInterceptor encodeTransferMedataRestTemplateInterceptor) {

@ -20,7 +20,6 @@ package com.tencent.cloud.metadata.core;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@ -39,6 +38,8 @@ import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter; import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain; import org.springframework.web.server.WebFilterChain;
import static com.tencent.cloud.common.constant.ContextConstant.UTF_8;
/** /**
* Filter used for storing the metadata from upstream temporarily when web application is * Filter used for storing the metadata from upstream temporarily when web application is
* REACTIVE. * REACTIVE.
@ -86,7 +87,7 @@ public class DecodeTransferMetadataReactiveFilter implements WebFilter, Ordered
.getFirst(MetadataConstant.HeaderName.CUSTOM_METADATA); .getFirst(MetadataConstant.HeaderName.CUSTOM_METADATA);
try { try {
if (StringUtils.hasText(customMetadataStr)) { if (StringUtils.hasText(customMetadataStr)) {
customMetadataStr = URLDecoder.decode(customMetadataStr, StandardCharsets.UTF_8.name()); customMetadataStr = URLDecoder.decode(customMetadataStr, UTF_8);
} }
} }
catch (UnsupportedEncodingException e) { catch (UnsupportedEncodingException e) {

@ -21,7 +21,6 @@ package com.tencent.cloud.metadata.core;
import java.io.IOException; import java.io.IOException;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@ -40,6 +39,8 @@ import org.springframework.core.annotation.Order;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter; import org.springframework.web.filter.OncePerRequestFilter;
import static com.tencent.cloud.common.constant.ContextConstant.UTF_8;
/** /**
* Filter used for storing the metadata from upstream temporarily when web application is * Filter used for storing the metadata from upstream temporarily when web application is
* SERVLET. * SERVLET.
@ -77,7 +78,7 @@ public class DecodeTransferMetadataServletFilter extends OncePerRequestFilter {
String customMetadataStr = httpServletRequest.getHeader(MetadataConstant.HeaderName.CUSTOM_METADATA); String customMetadataStr = httpServletRequest.getHeader(MetadataConstant.HeaderName.CUSTOM_METADATA);
try { try {
if (StringUtils.hasText(customMetadataStr)) { if (StringUtils.hasText(customMetadataStr)) {
customMetadataStr = URLDecoder.decode(customMetadataStr, StandardCharsets.UTF_8.name()); customMetadataStr = URLDecoder.decode(customMetadataStr, UTF_8);
} }
} }
catch (UnsupportedEncodingException e) { catch (UnsupportedEncodingException e) {

@ -20,7 +20,6 @@ package com.tencent.cloud.metadata.core;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map; import java.util.Map;
import com.tencent.cloud.common.constant.MetadataConstant; import com.tencent.cloud.common.constant.MetadataConstant;
@ -35,6 +34,7 @@ import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered; import org.springframework.core.Ordered;
import org.springframework.util.CollectionUtils; import org.springframework.util.CollectionUtils;
import static com.tencent.cloud.common.constant.ContextConstant.UTF_8;
import static com.tencent.cloud.common.constant.MetadataConstant.HeaderName.CUSTOM_METADATA; import static com.tencent.cloud.common.constant.MetadataConstant.HeaderName.CUSTOM_METADATA;
/** /**
@ -63,7 +63,7 @@ public class EncodeTransferMedataFeignInterceptor implements RequestInterceptor,
requestTemplate.removeHeader(CUSTOM_METADATA); requestTemplate.removeHeader(CUSTOM_METADATA);
try { try {
requestTemplate.header(CUSTOM_METADATA, requestTemplate.header(CUSTOM_METADATA,
URLEncoder.encode(encodedTransitiveMetadata, StandardCharsets.UTF_8.name())); URLEncoder.encode(encodedTransitiveMetadata, UTF_8));
} }
catch (UnsupportedEncodingException e) { catch (UnsupportedEncodingException e) {
LOG.error("Set header failed.", e); LOG.error("Set header failed.", e);

@ -21,7 +21,6 @@ package com.tencent.cloud.metadata.core;
import java.io.IOException; import java.io.IOException;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map; import java.util.Map;
import com.tencent.cloud.common.constant.MetadataConstant; import com.tencent.cloud.common.constant.MetadataConstant;
@ -34,8 +33,11 @@ import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution; import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor; import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse; import org.springframework.http.client.ClientHttpResponse;
import org.springframework.lang.NonNull;
import org.springframework.util.CollectionUtils; import org.springframework.util.CollectionUtils;
import static com.tencent.cloud.common.constant.ContextConstant.UTF_8;
/** /**
* Interceptor used for adding the metadata in http headers from context when web client * Interceptor used for adding the metadata in http headers from context when web client
* is RestTemplate. * is RestTemplate.
@ -50,8 +52,8 @@ public class EncodeTransferMedataRestTemplateInterceptor implements ClientHttpRe
} }
@Override @Override
public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, public ClientHttpResponse intercept(@NonNull HttpRequest httpRequest, @NonNull byte[] bytes,
ClientHttpRequestExecution clientHttpRequestExecution) throws IOException { @NonNull ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {
// get metadata of current thread // get metadata of current thread
MetadataContext metadataContext = MetadataContextHolder.get(); MetadataContext metadataContext = MetadataContextHolder.get();
Map<String, String> customMetadata = metadataContext.getFragmentContext(MetadataContext.FRAGMENT_TRANSITIVE); Map<String, String> customMetadata = metadataContext.getFragmentContext(MetadataContext.FRAGMENT_TRANSITIVE);
@ -60,7 +62,7 @@ public class EncodeTransferMedataRestTemplateInterceptor implements ClientHttpRe
String encodedTransitiveMetadata = JacksonUtils.serialize2Json(customMetadata); String encodedTransitiveMetadata = JacksonUtils.serialize2Json(customMetadata);
try { try {
httpRequest.getHeaders().set(MetadataConstant.HeaderName.CUSTOM_METADATA, httpRequest.getHeaders().set(MetadataConstant.HeaderName.CUSTOM_METADATA,
URLEncoder.encode(encodedTransitiveMetadata, StandardCharsets.UTF_8.name())); URLEncoder.encode(encodedTransitiveMetadata, UTF_8));
} }
catch (UnsupportedEncodingException e) { catch (UnsupportedEncodingException e) {
httpRequest.getHeaders().set(MetadataConstant.HeaderName.CUSTOM_METADATA, httpRequest.getHeaders().set(MetadataConstant.HeaderName.CUSTOM_METADATA,

@ -20,7 +20,6 @@ package com.tencent.cloud.metadata.core;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map; import java.util.Map;
import com.tencent.cloud.common.constant.MetadataConstant; import com.tencent.cloud.common.constant.MetadataConstant;
@ -36,6 +35,7 @@ import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.CollectionUtils; import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.ServerWebExchange;
import static com.tencent.cloud.common.constant.ContextConstant.UTF_8;
import static org.springframework.cloud.gateway.filter.LoadBalancerClientFilter.LOAD_BALANCER_CLIENT_FILTER_ORDER; import static org.springframework.cloud.gateway.filter.LoadBalancerClientFilter.LOAD_BALANCER_CLIENT_FILTER_ORDER;
/** /**
@ -69,7 +69,7 @@ public class EncodeTransferMedataScgFilter implements GlobalFilter, Ordered {
String metadataStr = JacksonUtils.serialize2Json(customMetadata); String metadataStr = JacksonUtils.serialize2Json(customMetadata);
try { try {
builder.header(MetadataConstant.HeaderName.CUSTOM_METADATA, builder.header(MetadataConstant.HeaderName.CUSTOM_METADATA,
URLEncoder.encode(metadataStr, StandardCharsets.UTF_8.name())); URLEncoder.encode(metadataStr, UTF_8));
} }
catch (UnsupportedEncodingException e) { catch (UnsupportedEncodingException e) {
builder.header(MetadataConstant.HeaderName.CUSTOM_METADATA, metadataStr); builder.header(MetadataConstant.HeaderName.CUSTOM_METADATA, metadataStr);

@ -20,7 +20,6 @@ package com.tencent.cloud.metadata.core;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map; import java.util.Map;
import com.netflix.zuul.ZuulFilter; import com.netflix.zuul.ZuulFilter;
@ -32,6 +31,7 @@ import com.tencent.cloud.common.util.JacksonUtils;
import org.springframework.util.CollectionUtils; import org.springframework.util.CollectionUtils;
import static com.tencent.cloud.common.constant.ContextConstant.UTF_8;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.RIBBON_ROUTING_FILTER_ORDER; import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.RIBBON_ROUTING_FILTER_ORDER;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.ROUTE_TYPE; import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.ROUTE_TYPE;
@ -71,7 +71,7 @@ public class EncodeTransferMetadataZuulFilter extends ZuulFilter {
String metadataStr = JacksonUtils.serialize2Json(customMetadata); String metadataStr = JacksonUtils.serialize2Json(customMetadata);
try { try {
requestContext.addZuulRequestHeader(MetadataConstant.HeaderName.CUSTOM_METADATA, requestContext.addZuulRequestHeader(MetadataConstant.HeaderName.CUSTOM_METADATA,
URLEncoder.encode(metadataStr, StandardCharsets.UTF_8.name())); URLEncoder.encode(metadataStr, UTF_8));
} }
catch (UnsupportedEncodingException e) { catch (UnsupportedEncodingException e) {
requestContext.addZuulRequestHeader(MetadataConstant.HeaderName.CUSTOM_METADATA, metadataStr); requestContext.addZuulRequestHeader(MetadataConstant.HeaderName.CUSTOM_METADATA, metadataStr);

@ -13,13 +13,13 @@
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * 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 * CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License. * specific language governing permissions and limitations under the License.
*
*/ */
package com.tencent.cloud.metadata.core; package com.tencent.cloud.metadata.core;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Map; import java.util.Map;
import com.tencent.cloud.common.constant.MetadataConstant; import com.tencent.cloud.common.constant.MetadataConstant;
@ -38,11 +38,10 @@ import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.mock.web.server.MockServerWebExchange;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit4.SpringRunner;
import static com.tencent.cloud.common.constant.ContextConstant.UTF_8;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
/** /**
* Test for {@link EncodeTransferMedataScgFilter}.
*
* @author quan * @author quan
*/ */
@RunWith(SpringRunner.class) @RunWith(SpringRunner.class)
@ -71,7 +70,7 @@ public class EncodeTransferMedataScgFilterTest {
String metadata = exchange.getRequest().getHeaders().getFirst(MetadataConstant.HeaderName.CUSTOM_METADATA); String metadata = exchange.getRequest().getHeaders().getFirst(MetadataConstant.HeaderName.CUSTOM_METADATA);
Assertions.assertThat(metadata).isNotNull(); Assertions.assertThat(metadata).isNotNull();
String decode = URLDecoder.decode(metadata, StandardCharsets.UTF_8.name()); String decode = URLDecoder.decode(metadata, UTF_8);
Map<String, String> transitiveMap = JacksonUtils.deserialize2Map(decode); Map<String, String> transitiveMap = JacksonUtils.deserialize2Map(decode);
Assertions.assertThat(transitiveMap.size()).isEqualTo(1); Assertions.assertThat(transitiveMap.size()).isEqualTo(1);
Assertions.assertThat(transitiveMap.get("b")).isEqualTo("2"); Assertions.assertThat(transitiveMap.get("b")).isEqualTo("2");

@ -20,7 +20,6 @@ package com.tencent.cloud.metadata.core;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Map; import java.util.Map;
import com.netflix.zuul.context.RequestContext; import com.netflix.zuul.context.RequestContext;
@ -38,6 +37,7 @@ import org.springframework.context.ApplicationContext;
import org.springframework.mock.web.MockMultipartHttpServletRequest; import org.springframework.mock.web.MockMultipartHttpServletRequest;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit4.SpringRunner;
import static com.tencent.cloud.common.constant.ContextConstant.UTF_8;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
/** /**
@ -72,7 +72,7 @@ public class EncodeTransferMetadataZuulFilterTest {
String metadata = zuulRequestHeaders.get(MetadataConstant.HeaderName.CUSTOM_METADATA.toLowerCase()); String metadata = zuulRequestHeaders.get(MetadataConstant.HeaderName.CUSTOM_METADATA.toLowerCase());
Assertions.assertThat(metadata).isNotNull(); Assertions.assertThat(metadata).isNotNull();
String decode = URLDecoder.decode(metadata, StandardCharsets.UTF_8.name()); String decode = URLDecoder.decode(metadata, UTF_8);
Map<String, String> transitiveMap = JacksonUtils.deserialize2Map(decode); Map<String, String> transitiveMap = JacksonUtils.deserialize2Map(decode);
Assertions.assertThat(transitiveMap.size()).isEqualTo(1); Assertions.assertThat(transitiveMap.size()).isEqualTo(1);
Assertions.assertThat(transitiveMap.get("b")).isEqualTo("2"); Assertions.assertThat(transitiveMap.get("b")).isEqualTo("2");

@ -0,0 +1,100 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* 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 com.tencent.cloud.polaris.circuitbreaker.config;
import com.tencent.cloud.polaris.circuitbreaker.feign.PolarisFeignBeanPostProcessor;
import com.tencent.cloud.polaris.circuitbreaker.resttemplate.PolarisResponseErrorHandler;
import com.tencent.cloud.polaris.circuitbreaker.resttemplate.PolarisRestTemplateModifier;
import com.tencent.cloud.polaris.circuitbreaker.resttemplate.PolarisRestTemplateResponseErrorHandler;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import com.tencent.polaris.api.core.ConsumerAPI;
import com.tencent.polaris.client.api.SDKContext;
import com.tencent.polaris.factory.api.DiscoveryAPIFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.openfeign.FeignAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.web.client.RestTemplate;
import static org.springframework.core.Ordered.HIGHEST_PRECEDENCE;
/**
* Auto Configuration for Polaris {@link feign.Feign} OR {@link RestTemplate} which can automatically bring in the call
* results for reporting.
*
* @author <a href="mailto:iskp.me@gmail.com">Palmer.Xu</a> 2022-06-29
*/
@Configuration(proxyBeanMethods = false)
public class PolarisCircuitBreakerAutoConfiguration {
/**
* Configuration for Polaris {@link feign.Feign} which can automatically bring in the call
* results for reporting.
*
* @author Haotian Zhang
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(name = "org.springframework.cloud.openfeign.FeignAutoConfiguration")
@AutoConfigureAfter(PolarisContextAutoConfiguration.class)
@AutoConfigureBefore(FeignAutoConfiguration.class)
@ConditionalOnProperty(value = "spring.cloud.polaris.circuitbreaker.enabled", havingValue = "true", matchIfMissing = true)
protected static class PolarisFeignClientAutoConfiguration {
@Bean
public ConsumerAPI consumerAPI(SDKContext context) {
return DiscoveryAPIFactory.createConsumerAPIByContext(context);
}
@Bean
@Order(HIGHEST_PRECEDENCE)
public PolarisFeignBeanPostProcessor polarisFeignBeanPostProcessor(ConsumerAPI consumerAPI) {
return new PolarisFeignBeanPostProcessor(consumerAPI);
}
}
/**
* Configuration for Polaris {@link RestTemplate} which can automatically bring in the call
* results for reporting.
*
* @author wh 2022/6/21
*/
@Configuration(proxyBeanMethods = false)
@AutoConfigureAfter(PolarisContextAutoConfiguration.class)
@ConditionalOnClass(RestTemplate.class)
@ConditionalOnProperty(value = "spring.cloud.polaris.circuitbreaker.enabled", havingValue = "true", matchIfMissing = true)
protected static class PolarisRestTemplateAutoConfiguration {
@Bean
public PolarisRestTemplateResponseErrorHandler polarisRestTemplateResponseErrorHandler(
ConsumerAPI consumerAPI, @Autowired(required = false) PolarisResponseErrorHandler polarisResponseErrorHandler) {
return new PolarisRestTemplateResponseErrorHandler(consumerAPI, polarisResponseErrorHandler);
}
@Bean
public PolarisRestTemplateModifier polarisRestTemplateBeanPostProcessor(
PolarisRestTemplateResponseErrorHandler restTemplateResponseErrorHandler) {
return new PolarisRestTemplateModifier(restTemplateResponseErrorHandler);
}
}
}

@ -33,10 +33,9 @@ import org.springframework.context.annotation.Configuration;
* *
* @author lepdou 2022-03-29 * @author lepdou 2022-03-29
*/ */
@ConditionalOnPolarisEnabled
@ConditionalOnProperty(value = "spring.cloud.polaris.circuitbreaker.enabled",
havingValue = "true", matchIfMissing = true)
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
@ConditionalOnPolarisEnabled
@ConditionalOnProperty(value = "spring.cloud.polaris.circuitbreaker.enabled", havingValue = "true", matchIfMissing = true)
public class PolarisCircuitBreakerBootstrapConfiguration { public class PolarisCircuitBreakerBootstrapConfiguration {
@Bean @Bean

@ -1,61 +0,0 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* 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 com.tencent.cloud.polaris.circuitbreaker.config;
import com.tencent.cloud.polaris.circuitbreaker.feign.PolarisFeignBeanPostProcessor;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import com.tencent.polaris.api.core.ConsumerAPI;
import com.tencent.polaris.client.api.SDKContext;
import com.tencent.polaris.factory.api.DiscoveryAPIFactory;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.openfeign.FeignAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import static org.springframework.core.Ordered.HIGHEST_PRECEDENCE;
/**
* Configuration for Polaris {@link feign.Feign} which can automatically bring in the call
* results for reporting.
*
* @author Haotian Zhang
*/
@ConditionalOnProperty(value = "spring.cloud.polaris.circuitbreaker.enabled",
havingValue = "true", matchIfMissing = true)
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(name = "org.springframework.cloud.openfeign.FeignAutoConfiguration")
@AutoConfigureAfter(PolarisContextAutoConfiguration.class)
@AutoConfigureBefore(FeignAutoConfiguration.class)
public class PolarisFeignClientAutoConfiguration {
@Bean
public ConsumerAPI consumerAPI(SDKContext context) {
return DiscoveryAPIFactory.createConsumerAPIByContext(context);
}
@Bean
@Order(HIGHEST_PRECEDENCE)
public PolarisFeignBeanPostProcessor polarisFeignBeanPostProcessor(ConsumerAPI consumerAPI) {
return new PolarisFeignBeanPostProcessor(consumerAPI);
}
}

@ -1,58 +0,0 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* 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 com.tencent.cloud.polaris.circuitbreaker.config;
import com.tencent.cloud.polaris.circuitbreaker.resttemplate.PolarisResponseErrorHandler;
import com.tencent.cloud.polaris.circuitbreaker.resttemplate.PolarisRestTemplateModifier;
import com.tencent.cloud.polaris.circuitbreaker.resttemplate.PolarisRestTemplateResponseErrorHandler;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import com.tencent.polaris.api.core.ConsumerAPI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
/**
* Auto configuration PolarisRestTemplateAutoConfiguration .
*
* @author wh 2022/6/21
*/
@ConditionalOnProperty(value = "spring.cloud.polaris.circuitbreaker.enabled",
havingValue = "true", matchIfMissing = true)
@Configuration(proxyBeanMethods = false)
@AutoConfigureAfter(PolarisContextAutoConfiguration.class)
public class PolarisRestTemplateAutoConfiguration {
@Bean
@ConditionalOnBean(RestTemplate.class)
public PolarisRestTemplateResponseErrorHandler polarisRestTemplateResponseErrorHandler(
ConsumerAPI consumerAPI, @Autowired(required = false) PolarisResponseErrorHandler polarisResponseErrorHandler) {
return new PolarisRestTemplateResponseErrorHandler(consumerAPI, polarisResponseErrorHandler);
}
@Bean
@ConditionalOnBean(RestTemplate.class)
public PolarisRestTemplateModifier polarisRestTemplateBeanPostProcessor(
PolarisRestTemplateResponseErrorHandler restTemplateResponseErrorHandler) {
return new PolarisRestTemplateModifier(restTemplateResponseErrorHandler);
}
}

@ -1,6 +1,5 @@
org.springframework.cloud.bootstrap.BootstrapConfiguration=\ org.springframework.cloud.bootstrap.BootstrapConfiguration=\
com.tencent.cloud.polaris.circuitbreaker.config.PolarisCircuitBreakerBootstrapConfiguration com.tencent.cloud.polaris.circuitbreaker.config.PolarisCircuitBreakerBootstrapConfiguration
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.tencent.cloud.polaris.circuitbreaker.config.PolarisFeignClientAutoConfiguration,\ com.tencent.cloud.polaris.circuitbreaker.config.PolarisCircuitBreakerAutoConfiguration
com.tencent.cloud.polaris.circuitbreaker.config.PolarisRestTemplateAutoConfiguration

@ -17,7 +17,7 @@
package com.tencent.cloud.polaris.circuitbreaker; package com.tencent.cloud.polaris.circuitbreaker;
import com.tencent.cloud.polaris.circuitbreaker.config.PolarisFeignClientAutoConfiguration; import com.tencent.cloud.polaris.circuitbreaker.config.PolarisCircuitBreakerAutoConfiguration;
import com.tencent.cloud.polaris.circuitbreaker.feign.PolarisFeignBeanPostProcessor; import com.tencent.cloud.polaris.circuitbreaker.feign.PolarisFeignBeanPostProcessor;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration; import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import com.tencent.polaris.api.core.ConsumerAPI; import com.tencent.polaris.api.core.ConsumerAPI;
@ -29,16 +29,17 @@ import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
/** /**
* Test for {@link PolarisFeignClientAutoConfiguration}. * Test for {@link PolarisCircuitBreakerAutoConfiguration}.
* *
* @author Haotian Zhang * @author Haotian Zhang
*/ */
public class PolarisFeignClientAutoConfigurationTest { public class PolarisFeignClientAutoConfigurationTest {
private ApplicationContextRunner contextRunner = new ApplicationContextRunner() private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of( .withConfiguration(
PolarisContextAutoConfiguration.class, AutoConfigurations.of(
PolarisFeignClientAutoConfiguration.class)) PolarisContextAutoConfiguration.class,
PolarisCircuitBreakerAutoConfiguration.class))
.withPropertyValues("spring.cloud.polaris.circuitbreaker.enabled=true"); .withPropertyValues("spring.cloud.polaris.circuitbreaker.enabled=true");
@Test @Test

@ -18,7 +18,7 @@
package com.tencent.cloud.polaris.circuitbreaker; package com.tencent.cloud.polaris.circuitbreaker;
import com.tencent.cloud.polaris.circuitbreaker.config.PolarisRestTemplateAutoConfiguration; import com.tencent.cloud.polaris.circuitbreaker.config.PolarisCircuitBreakerAutoConfiguration;
import com.tencent.cloud.polaris.circuitbreaker.resttemplate.PolarisRestTemplateModifier; import com.tencent.cloud.polaris.circuitbreaker.resttemplate.PolarisRestTemplateModifier;
import com.tencent.cloud.polaris.circuitbreaker.resttemplate.PolarisRestTemplateResponseErrorHandler; import com.tencent.cloud.polaris.circuitbreaker.resttemplate.PolarisRestTemplateResponseErrorHandler;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration; import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
@ -35,7 +35,7 @@ import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
/** /**
* Test For {@link PolarisRestTemplateAutoConfiguration} . * Test For {@link PolarisCircuitBreakerAutoConfiguration} .
* *
* @author <a href="mailto:iskp.me@gmail.com">Palmer Xu</a> 2022-06-28 * @author <a href="mailto:iskp.me@gmail.com">Palmer Xu</a> 2022-06-28
*/ */
@ -45,7 +45,7 @@ public class PolarisRestTemplateAutoConfigurationTest {
.withConfiguration(AutoConfigurations.of( .withConfiguration(AutoConfigurations.of(
PolarisRestTemplateAutoConfigurationTester.class, PolarisRestTemplateAutoConfigurationTester.class,
PolarisContextAutoConfiguration.class, PolarisContextAutoConfiguration.class,
PolarisRestTemplateAutoConfiguration.class)) PolarisCircuitBreakerAutoConfiguration.class))
.withPropertyValues("spring.cloud.polaris.circuitbreaker.enabled=true"); .withPropertyValues("spring.cloud.polaris.circuitbreaker.enabled=true");
@Test @Test
@ -59,7 +59,7 @@ public class PolarisRestTemplateAutoConfigurationTest {
@Configuration @Configuration
@EnableAutoConfiguration @EnableAutoConfiguration
@AutoConfigureBefore(PolarisRestTemplateAutoConfiguration.class) @AutoConfigureBefore(PolarisCircuitBreakerAutoConfiguration.class)
static class PolarisRestTemplateAutoConfigurationTester { static class PolarisRestTemplateAutoConfigurationTester {
@Bean @Bean

@ -37,8 +37,7 @@ import org.springframework.context.annotation.Configuration;
*/ */
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
@ConditionalOnPolarisEnabled @ConditionalOnPolarisEnabled
@ConditionalOnProperty(value = "spring.cloud.polaris.config.enabled", @ConditionalOnProperty(value = "spring.cloud.polaris.config.enabled", matchIfMissing = true)
matchIfMissing = true)
public class PolarisConfigAutoConfiguration { public class PolarisConfigAutoConfiguration {
@Bean @Bean

@ -18,10 +18,13 @@
package com.tencent.cloud.polaris.config.listener; package com.tencent.cloud.polaris.config.listener;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
import com.tencent.cloud.polaris.config.annotation.PolarisConfigKVFileChangeListener; import com.tencent.cloud.polaris.config.annotation.PolarisConfigKVFileChangeListener;
import com.tencent.polaris.configuration.api.core.ConfigPropertyChangeInfo; import com.tencent.polaris.configuration.api.core.ConfigPropertyChangeInfo;
import org.junit.Assert; import org.assertj.core.api.Assertions;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
@ -55,10 +58,12 @@ public class ConfigChangeListenerTest {
@Autowired @Autowired
private TestApplication.TestConfig testConfig; private TestApplication.TestConfig testConfig;
private static final CountDownLatch hits = new CountDownLatch(2);
@Test @Test
public void test() throws InterruptedException { public void test() throws InterruptedException {
//before change //before change
Assert.assertEquals(1000, testConfig.getTimeout()); Assertions.assertThat(testConfig.getTimeout()).isEqualTo(1000);
//submit change event //submit change event
System.setProperty("timeout", "2000"); System.setProperty("timeout", "2000");
@ -66,12 +71,14 @@ public class ConfigChangeListenerTest {
Sets.newHashSet("timeout")); Sets.newHashSet("timeout"));
applicationEventPublisher.publishEvent(event); applicationEventPublisher.publishEvent(event);
Thread.sleep(200);
//after change //after change
Assert.assertEquals(2, testConfig.getChangeCnt()); boolean ret = hits.await(2, TimeUnit.SECONDS);
Assert.assertEquals(2000, testConfig.getTimeout()); Assertions.assertThat(ret).isEqualTo(true);
}
Assertions.assertThat(testConfig.getChangeCnt()).isEqualTo(2);
Assertions.assertThat(testConfig.getTimeout()).isEqualTo(2000);
}
@SpringBootApplication @SpringBootApplication
protected static class TestApplication { protected static class TestApplication {
@ -101,6 +108,7 @@ public class ConfigChangeListenerTest {
ConfigPropertyChangeInfo changeInfo = event.getChange("timeout"); ConfigPropertyChangeInfo changeInfo = event.getChange("timeout");
timeout = Integer.parseInt(changeInfo.getNewValue()); timeout = Integer.parseInt(changeInfo.getNewValue());
changeCnt++; changeCnt++;
hits.countDown();
} }
@PolarisConfigKVFileChangeListener(interestedKeyPrefixes = {"timeout"}) @PolarisConfigKVFileChangeListener(interestedKeyPrefixes = {"timeout"})
@ -108,6 +116,7 @@ public class ConfigChangeListenerTest {
ConfigPropertyChangeInfo changeInfo = event.getChange("timeout"); ConfigPropertyChangeInfo changeInfo = event.getChange("timeout");
timeout = Integer.parseInt(changeInfo.getNewValue()); timeout = Integer.parseInt(changeInfo.getNewValue());
changeCnt++; changeCnt++;
hits.countDown();
} }
} }

@ -15,9 +15,8 @@
* specific language governing permissions and limitations under the License. * specific language governing permissions and limitations under the License.
* *
*/ */
package com.tencent.cloud.polaris;
import javax.annotation.PostConstruct; package com.tencent.cloud.polaris;
import com.tencent.cloud.polaris.context.ConditionalOnPolarisEnabled; import com.tencent.cloud.polaris.context.ConditionalOnPolarisEnabled;
import com.tencent.cloud.polaris.discovery.PolarisDiscoveryHandler; import com.tencent.cloud.polaris.discovery.PolarisDiscoveryHandler;
@ -28,7 +27,6 @@ import com.tencent.polaris.api.exception.PolarisException;
import com.tencent.polaris.client.api.SDKContext; import com.tencent.polaris.client.api.SDKContext;
import com.tencent.polaris.factory.api.DiscoveryAPIFactory; import com.tencent.polaris.factory.api.DiscoveryAPIFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
@ -41,19 +39,9 @@ import org.springframework.context.annotation.Import;
*/ */
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
@ConditionalOnPolarisEnabled @ConditionalOnPolarisEnabled
@Import({ PolarisDiscoveryProperties.class, ConsulContextProperties.class }) @Import({PolarisDiscoveryProperties.class, ConsulContextProperties.class})
public class DiscoveryPropertiesAutoConfiguration { public class DiscoveryPropertiesAutoConfiguration {
@Autowired(required = false)
private PolarisDiscoveryProperties polarisDiscoveryProperties;
@Autowired(required = false)
private ConsulContextProperties consulContextProperties;
private boolean registerEnabled = false;
private boolean discoveryEnabled = false;
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public ProviderAPI polarisProvider(SDKContext polarisContext) throws PolarisException { public ProviderAPI polarisProvider(SDKContext polarisContext) throws PolarisException {
@ -76,24 +64,4 @@ public class DiscoveryPropertiesAutoConfiguration {
public DiscoveryConfigModifier discoveryConfigModifier() { public DiscoveryConfigModifier discoveryConfigModifier() {
return new DiscoveryConfigModifier(); return new DiscoveryConfigModifier();
} }
@PostConstruct
public void init() {
if (null != polarisDiscoveryProperties) {
registerEnabled |= polarisDiscoveryProperties.isRegisterEnabled();
discoveryEnabled |= polarisDiscoveryProperties.isEnabled();
}
if (null != consulContextProperties && consulContextProperties.isEnabled()) {
registerEnabled |= consulContextProperties.isRegister();
discoveryEnabled |= consulContextProperties.isDiscoveryEnabled();
}
}
public boolean isRegisterEnabled() {
return registerEnabled;
}
public boolean isDiscoveryEnabled() {
return discoveryEnabled;
}
} }

@ -29,7 +29,6 @@ import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
/** /**
* Properties for Polaris. * Properties for Polaris.
@ -107,9 +106,6 @@ public class PolarisDiscoveryProperties {
*/ */
private Long serviceListRefreshInterval = 60000L; private Long serviceListRefreshInterval = 60000L;
@Autowired
private Environment environment;
public boolean isHeartbeatEnabled() { public boolean isHeartbeatEnabled() {
return heartbeatEnabled; return heartbeatEnabled;
} }
@ -232,7 +228,7 @@ public class PolarisDiscoveryProperties {
private static class PolarisDiscoveryConfigModifier implements PolarisConfigModifier { private static class PolarisDiscoveryConfigModifier implements PolarisConfigModifier {
private final String ID = "polaris"; private static final String ID = "polaris";
@Autowired(required = false) @Autowired(required = false)
private PolarisDiscoveryProperties polarisDiscoveryProperties; private PolarisDiscoveryProperties polarisDiscoveryProperties;

@ -113,7 +113,7 @@ public class ConsulContextProperties {
private static class ConsulConfigModifier implements PolarisConfigModifier { private static class ConsulConfigModifier implements PolarisConfigModifier {
private final String ID = "consul"; private static final String ID = "consul";
@Autowired(required = false) @Autowired(required = false)
private ConsulContextProperties consulContextProperties; private ConsulContextProperties consulContextProperties;

@ -24,42 +24,46 @@ import java.util.HashMap;
import java.util.Map; import java.util.Map;
import com.tencent.cloud.common.metadata.StaticMetadataManager; import com.tencent.cloud.common.metadata.StaticMetadataManager;
import com.tencent.cloud.polaris.DiscoveryPropertiesAutoConfiguration;
import com.tencent.cloud.polaris.PolarisDiscoveryProperties; import com.tencent.cloud.polaris.PolarisDiscoveryProperties;
import com.tencent.cloud.polaris.extend.consul.ConsulContextProperties;
import com.tencent.polaris.client.api.SDKContext; import com.tencent.polaris.client.api.SDKContext;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.client.DefaultServiceInstance; import org.springframework.cloud.client.DefaultServiceInstance;
import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.serviceregistry.Registration; import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.lang.Nullable;
import org.springframework.util.CollectionUtils; import org.springframework.util.CollectionUtils;
/** /**
* Registration object of Polaris. * Registration object of Polaris.
* *
* @author Haotian Zhang, Andrew Shan, Jie Cheng * @author Haotian Zhang, Andrew Shan, Jie Cheng, Palmer.Xu
*/ */
public class PolarisRegistration implements Registration, ServiceInstance { public class PolarisRegistration implements Registration, ServiceInstance {
private final static String METADATA_KEY_IP = "internal-ip"; private final static String METADATA_KEY_IP = "internal-ip";
private final static String METADATA_KEY_ADDRESS = "internal-address";
private final DiscoveryPropertiesAutoConfiguration discoveryPropertiesAutoConfiguration; private final static String METADATA_KEY_ADDRESS = "internal-address";
private final PolarisDiscoveryProperties polarisDiscoveryProperties; private final PolarisDiscoveryProperties polarisDiscoveryProperties;
private final ConsulContextProperties consulContextProperties;
private final SDKContext polarisContext; private final SDKContext polarisContext;
private final StaticMetadataManager staticMetadataManager; private final StaticMetadataManager staticMetadataManager;
private final String host;
private Map<String, String> metadata; private Map<String, String> metadata;
private final String host;
public PolarisRegistration( public PolarisRegistration(
DiscoveryPropertiesAutoConfiguration discoveryPropertiesAutoConfiguration, PolarisDiscoveryProperties polarisDiscoveryProperties,
PolarisDiscoveryProperties polarisDiscoveryProperties, SDKContext context, @Nullable ConsulContextProperties consulContextProperties,
StaticMetadataManager staticMetadataManager) { SDKContext context, StaticMetadataManager staticMetadataManager) {
this.discoveryPropertiesAutoConfiguration = discoveryPropertiesAutoConfiguration;
this.polarisDiscoveryProperties = polarisDiscoveryProperties; this.polarisDiscoveryProperties = polarisDiscoveryProperties;
this.consulContextProperties = consulContextProperties;
this.polarisContext = context; this.polarisContext = context;
this.staticMetadataManager = staticMetadataManager; this.staticMetadataManager = staticMetadataManager;
@ -119,14 +123,23 @@ public class PolarisRegistration implements Registration, ServiceInstance {
} }
public boolean isRegisterEnabled() { public boolean isRegisterEnabled() {
return discoveryPropertiesAutoConfiguration.isRegisterEnabled();
boolean registerEnabled = false;
if (null != polarisDiscoveryProperties) {
registerEnabled |= polarisDiscoveryProperties.isRegisterEnabled();
}
if (null != consulContextProperties && consulContextProperties.isEnabled()) {
registerEnabled |= consulContextProperties.isRegister();
}
return registerEnabled;
} }
@Override @Override
public String toString() { public String toString() {
return "PolarisRegistration{" + return "PolarisRegistration{" +
"discoveryPropertiesAutoConfiguration=" + discoveryPropertiesAutoConfiguration + "polarisDiscoveryProperties=" + polarisDiscoveryProperties +
", polarisDiscoveryProperties=" + polarisDiscoveryProperties +
", polarisContext=" + polarisContext + ", polarisContext=" + polarisContext +
", staticMetadataManager=" + staticMetadataManager + ", staticMetadataManager=" + staticMetadataManager +
", metadata=" + metadata + ", metadata=" + metadata +

@ -19,12 +19,13 @@
package com.tencent.cloud.polaris.registry; package com.tencent.cloud.polaris.registry;
import com.tencent.cloud.common.metadata.StaticMetadataManager; import com.tencent.cloud.common.metadata.StaticMetadataManager;
import com.tencent.cloud.polaris.DiscoveryPropertiesAutoConfiguration;
import com.tencent.cloud.polaris.PolarisDiscoveryProperties; import com.tencent.cloud.polaris.PolarisDiscoveryProperties;
import com.tencent.cloud.polaris.discovery.PolarisDiscoveryAutoConfiguration; import com.tencent.cloud.polaris.discovery.PolarisDiscoveryAutoConfiguration;
import com.tencent.cloud.polaris.discovery.PolarisDiscoveryHandler; import com.tencent.cloud.polaris.discovery.PolarisDiscoveryHandler;
import com.tencent.cloud.polaris.extend.consul.ConsulContextProperties;
import com.tencent.polaris.client.api.SDKContext; import com.tencent.polaris.client.api.SDKContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
@ -59,11 +60,10 @@ public class PolarisServiceRegistryAutoConfiguration {
@Bean @Bean
@ConditionalOnBean(AutoServiceRegistrationProperties.class) @ConditionalOnBean(AutoServiceRegistrationProperties.class)
public PolarisRegistration polarisRegistration( public PolarisRegistration polarisRegistration(
DiscoveryPropertiesAutoConfiguration discoveryPropertiesAutoConfiguration, PolarisDiscoveryProperties polarisDiscoveryProperties,
PolarisDiscoveryProperties polarisDiscoveryProperties, SDKContext context, @Autowired(required = false) ConsulContextProperties consulContextProperties,
StaticMetadataManager staticMetadataManager) { SDKContext context, StaticMetadataManager staticMetadataManager) {
return new PolarisRegistration(discoveryPropertiesAutoConfiguration, return new PolarisRegistration(polarisDiscoveryProperties, consulContextProperties, context, staticMetadataManager);
polarisDiscoveryProperties, context, staticMetadataManager);
} }
@Bean @Bean

@ -24,14 +24,12 @@ import com.tencent.cloud.polaris.discovery.PolarisDiscoveryHandler;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/** /**
* Configuration of server list. * Configuration of server list.
* *
* @author Haotian Zhang, Andrew Shan, Jie Cheng * @author Haotian Zhang, Andrew Shan, Jie Cheng
*/ */
@Configuration
public class PolarisRibbonServerListConfiguration { public class PolarisRibbonServerListConfiguration {
@Bean @Bean

@ -67,10 +67,6 @@ public class DiscoveryPropertiesAutoConfigurationTest {
.withPropertyValues("spring.cloud.consul.discovery.enabled=false"); .withPropertyValues("spring.cloud.consul.discovery.enabled=false");
applicationContextRunner.run(context -> { applicationContextRunner.run(context -> {
assertThat(context).hasSingleBean(DiscoveryPropertiesAutoConfiguration.class); assertThat(context).hasSingleBean(DiscoveryPropertiesAutoConfiguration.class);
DiscoveryPropertiesAutoConfiguration discoveryPropertiesAutoConfiguration =
context.getBean(DiscoveryPropertiesAutoConfiguration.class);
assertThat(discoveryPropertiesAutoConfiguration.isRegisterEnabled()).isFalse();
assertThat(discoveryPropertiesAutoConfiguration.isDiscoveryEnabled()).isFalse();
}); });
} }

@ -21,8 +21,8 @@ import java.util.Collections;
import java.util.Map; import java.util.Map;
import com.tencent.cloud.common.metadata.StaticMetadataManager; import com.tencent.cloud.common.metadata.StaticMetadataManager;
import com.tencent.cloud.polaris.DiscoveryPropertiesAutoConfiguration;
import com.tencent.cloud.polaris.PolarisDiscoveryProperties; import com.tencent.cloud.polaris.PolarisDiscoveryProperties;
import com.tencent.cloud.polaris.extend.consul.ConsulContextProperties;
import com.tencent.polaris.api.config.Configuration; import com.tencent.polaris.api.config.Configuration;
import com.tencent.polaris.api.config.global.APIConfig; import com.tencent.polaris.api.config.global.APIConfig;
import com.tencent.polaris.api.config.global.GlobalConfig; import com.tencent.polaris.api.config.global.GlobalConfig;
@ -51,16 +51,15 @@ public class PolarisRegistrationTest {
@Before @Before
public void setUp() { public void setUp() {
// mock DiscoveryPropertiesAutoConfiguration
DiscoveryPropertiesAutoConfiguration discoveryPropertiesAutoConfiguration =
mock(DiscoveryPropertiesAutoConfiguration.class);
doReturn(true).when(discoveryPropertiesAutoConfiguration).isRegisterEnabled();
// mock PolarisDiscoveryProperties // mock PolarisDiscoveryProperties
PolarisDiscoveryProperties polarisDiscoveryProperties = mock(PolarisDiscoveryProperties.class); PolarisDiscoveryProperties polarisDiscoveryProperties = mock(PolarisDiscoveryProperties.class);
doReturn(SERVICE_PROVIDER).when(polarisDiscoveryProperties).getService(); doReturn(SERVICE_PROVIDER).when(polarisDiscoveryProperties).getService();
doReturn(PORT).when(polarisDiscoveryProperties).getPort(); doReturn(PORT).when(polarisDiscoveryProperties).getPort();
doReturn("http").when(polarisDiscoveryProperties).getProtocol(); doReturn("http").when(polarisDiscoveryProperties).getProtocol();
doReturn(true).when(polarisDiscoveryProperties).isRegisterEnabled();
// mock
ConsulContextProperties consulContextProperties = mock(ConsulContextProperties.class);
// mock SDKContext // mock SDKContext
APIConfig apiConfig = mock(APIConfig.class); APIConfig apiConfig = mock(APIConfig.class);
@ -77,8 +76,8 @@ public class PolarisRegistrationTest {
doReturn(Collections.singletonMap("key1", "value1")).when(staticMetadataManager).getMergedStaticMetadata(); doReturn(Collections.singletonMap("key1", "value1")).when(staticMetadataManager).getMergedStaticMetadata();
doReturn(Collections.singletonMap("key2", "value2")).when(staticMetadataManager).getLocationMetadata(); doReturn(Collections.singletonMap("key2", "value2")).when(staticMetadataManager).getLocationMetadata();
polarisRegistration = new PolarisRegistration( polarisRegistration = new PolarisRegistration(polarisDiscoveryProperties, consulContextProperties,
discoveryPropertiesAutoConfiguration, polarisDiscoveryProperties, polarisContext, staticMetadataManager); polarisContext, staticMetadataManager);
} }
@Test @Test

@ -40,6 +40,7 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.lang.Nullable; import org.springframework.lang.Nullable;
import static com.tencent.cloud.polaris.ratelimit.filter.QuotaCheckServletFilter.QUOTA_FILTER_BEAN_NAME;
import static javax.servlet.DispatcherType.ASYNC; import static javax.servlet.DispatcherType.ASYNC;
import static javax.servlet.DispatcherType.ERROR; import static javax.servlet.DispatcherType.ERROR;
import static javax.servlet.DispatcherType.FORWARD; import static javax.servlet.DispatcherType.FORWARD;
@ -51,7 +52,7 @@ import static javax.servlet.DispatcherType.REQUEST;
* *
* @author Haotian Zhang * @author Haotian Zhang
*/ */
@Configuration @Configuration(proxyBeanMethods = false)
@ConditionalOnPolarisEnabled @ConditionalOnPolarisEnabled
@AutoConfigureAfter(PolarisContextAutoConfiguration.class) @AutoConfigureAfter(PolarisContextAutoConfiguration.class)
@ConditionalOnProperty(name = "spring.cloud.polaris.ratelimit.enabled", matchIfMissing = true) @ConditionalOnProperty(name = "spring.cloud.polaris.ratelimit.enabled", matchIfMissing = true)
@ -71,9 +72,9 @@ public class PolarisRateLimitAutoConfiguration {
/** /**
* Create when web application type is SERVLET. * Create when web application type is SERVLET.
*/ */
@Configuration @Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
static class QuotaCheckFilterConfig { protected static class QuotaCheckFilterConfig {
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
@ -91,7 +92,7 @@ public class PolarisRateLimitAutoConfiguration {
FilterRegistrationBean<QuotaCheckServletFilter> registrationBean = new FilterRegistrationBean<>( FilterRegistrationBean<QuotaCheckServletFilter> registrationBean = new FilterRegistrationBean<>(
quotaCheckServletFilter); quotaCheckServletFilter);
registrationBean.setDispatcherTypes(ASYNC, ERROR, FORWARD, INCLUDE, REQUEST); registrationBean.setDispatcherTypes(ASYNC, ERROR, FORWARD, INCLUDE, REQUEST);
registrationBean.setName("quotaFilterRegistrationBean"); registrationBean.setName(QUOTA_FILTER_BEAN_NAME);
registrationBean.setOrder(RateLimitConstant.FILTER_ORDER); registrationBean.setOrder(RateLimitConstant.FILTER_ORDER);
return registrationBean; return registrationBean;
} }
@ -100,9 +101,9 @@ public class PolarisRateLimitAutoConfiguration {
/** /**
* Create when web application type is REACTIVE. * Create when web application type is REACTIVE.
*/ */
@Configuration @Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE) @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
static class MetadataReactiveFilterConfig { protected static class MetadataReactiveFilterConfig {
@Bean @Bean
public QuotaCheckReactiveFilter quotaCheckReactiveFilter(LimitAPI limitAPI, public QuotaCheckReactiveFilter quotaCheckReactiveFilter(LimitAPI limitAPI,

@ -28,7 +28,7 @@ import com.tencent.polaris.factory.config.ConfigurationImpl;
*/ */
public class RateLimitConfigModifier implements PolarisConfigModifier { public class RateLimitConfigModifier implements PolarisConfigModifier {
private PolarisRateLimitProperties polarisRateLimitProperties; private final PolarisRateLimitProperties polarisRateLimitProperties;
public RateLimitConfigModifier(PolarisRateLimitProperties polarisRateLimitProperties) { public RateLimitConfigModifier(PolarisRateLimitProperties polarisRateLimitProperties) {
this.polarisRateLimitProperties = polarisRateLimitProperties; this.polarisRateLimitProperties = polarisRateLimitProperties;

@ -60,6 +60,11 @@ public class QuotaCheckServletFilter extends OncePerRequestFilter {
private static final Logger LOG = LoggerFactory.getLogger(QuotaCheckServletFilter.class); private static final Logger LOG = LoggerFactory.getLogger(QuotaCheckServletFilter.class);
/**
* Default Filter Registration Bean Name Defined .
*/
public static final String QUOTA_FILTER_BEAN_NAME = "quotaFilterRegistrationBean";
private final LimitAPI limitAPI; private final LimitAPI limitAPI;
private final PolarisRateLimiterLabelServletResolver labelResolver; private final PolarisRateLimiterLabelServletResolver labelResolver;

@ -36,7 +36,6 @@ public final class RateLimitUtils {
private static final Logger LOG = LoggerFactory.getLogger(RateLimitUtils.class); private static final Logger LOG = LoggerFactory.getLogger(RateLimitUtils.class);
private RateLimitUtils() { private RateLimitUtils() {
} }
public static String getRejectTips(PolarisRateLimitProperties polarisRateLimitProperties) { public static String getRejectTips(PolarisRateLimitProperties polarisRateLimitProperties) {

@ -43,8 +43,7 @@ public class PolarisRateLimitAutoConfigurationTest {
private final WebApplicationContextRunner webApplicationContextRunner = new WebApplicationContextRunner(); private final WebApplicationContextRunner webApplicationContextRunner = new WebApplicationContextRunner();
private final ReactiveWebApplicationContextRunner reactiveWebApplicationContextRunner = private final ReactiveWebApplicationContextRunner reactiveWebApplicationContextRunner = new ReactiveWebApplicationContextRunner();
new ReactiveWebApplicationContextRunner();
@Test @Test
public void testNoWebApplication() { public void testNoWebApplication() {

@ -33,6 +33,7 @@ import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient; import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.gateway.config.LoadBalancerProperties; import org.springframework.cloud.gateway.config.LoadBalancerProperties;
import org.springframework.cloud.gateway.filter.LoadBalancerClientFilter; import org.springframework.cloud.gateway.filter.LoadBalancerClientFilter;
import org.springframework.lang.NonNull;
/** /**
* Replace LoadBalancerClientFilter with PolarisLoadBalancerClientFilter. * Replace LoadBalancerClientFilter with PolarisLoadBalancerClientFilter.
@ -44,12 +45,12 @@ public class LoadBalancerClientFilterBeanPostProcessor implements BeanPostProces
private BeanFactory factory; private BeanFactory factory;
@Override @Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException { public void setBeanFactory(@NonNull BeanFactory beanFactory) throws BeansException {
this.factory = beanFactory; this.factory = beanFactory;
} }
@Override @Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { public Object postProcessBeforeInitialization(@NonNull Object bean, @NonNull String beanName) throws BeansException {
if (bean instanceof LoadBalancerClientFilter) { if (bean instanceof LoadBalancerClientFilter) {
// Support spring cloud gateway router. // Support spring cloud gateway router.
// Replaces the default LoadBalancerClientFilter implementation and returns a custom PolarisLoadBalancerClientFilter // Replaces the default LoadBalancerClientFilter implementation and returns a custom PolarisLoadBalancerClientFilter

@ -33,6 +33,7 @@ import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient; import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerInterceptor; import org.springframework.cloud.client.loadbalancer.LoadBalancerInterceptor;
import org.springframework.cloud.client.loadbalancer.LoadBalancerRequestFactory; import org.springframework.cloud.client.loadbalancer.LoadBalancerRequestFactory;
import org.springframework.lang.NonNull;
/** /**
* Replace LoadBalancerInterceptor with PolarisLoadBalancerInterceptor. * Replace LoadBalancerInterceptor with PolarisLoadBalancerInterceptor.
@ -45,12 +46,12 @@ public class LoadBalancerInterceptorBeanPostProcessor implements BeanPostProcess
private BeanFactory factory; private BeanFactory factory;
@Override @Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException { public void setBeanFactory(@NonNull BeanFactory beanFactory) throws BeansException {
this.factory = beanFactory; this.factory = beanFactory;
} }
@Override @Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { public Object postProcessBeforeInitialization(@NonNull Object bean, @NonNull String beanName) throws BeansException {
if (bean instanceof LoadBalancerInterceptor) { if (bean instanceof LoadBalancerInterceptor) {
// Support rest template router. // Support rest template router.
// Replaces the default LoadBalancerInterceptor implementation and returns a custom PolarisLoadBalancerInterceptor // Replaces the default LoadBalancerInterceptor implementation and returns a custom PolarisLoadBalancerInterceptor

@ -39,7 +39,7 @@ import org.springframework.lang.Nullable;
* *
* @author lepdou 2022-06-10 * @author lepdou 2022-06-10
*/ */
@Configuration @Configuration(proxyBeanMethods = false)
@ConditionalOnClass(name = {"org.springframework.cloud.openfeign.ribbon.FeignLoadBalancer"}) @ConditionalOnClass(name = {"org.springframework.cloud.openfeign.ribbon.FeignLoadBalancer"})
@RibbonClients(defaultConfiguration = {FeignLoadBalancerConfiguration.class}) @RibbonClients(defaultConfiguration = {FeignLoadBalancerConfiguration.class})
public class FeignAutoConfiguration { public class FeignAutoConfiguration {

@ -40,7 +40,7 @@ import static org.springframework.core.Ordered.HIGHEST_PRECEDENCE;
* *
* @author lepdou 2022-05-11 * @author lepdou 2022-05-11
*/ */
@Configuration @Configuration(proxyBeanMethods = false)
@RibbonClients(defaultConfiguration = {RibbonConfiguration.class}) @RibbonClients(defaultConfiguration = {RibbonConfiguration.class})
@Import({PolarisNearByRouterProperties.class, PolarisMetadataRouterProperties.class, PolarisRuleBasedRouterProperties.class}) @Import({PolarisNearByRouterProperties.class, PolarisMetadataRouterProperties.class, PolarisRuleBasedRouterProperties.class})
public class RouterAutoConfiguration { public class RouterAutoConfiguration {

@ -78,7 +78,6 @@ public final class FeignExpressionLabelUtils {
public static String getHeaderValue(RequestTemplate request, String key) { public static String getHeaderValue(RequestTemplate request, String key) {
Map<String, Collection<String>> headers = request.headers(); Map<String, Collection<String>> headers = request.headers();
return ExpressionLabelUtils.getFirstValue(headers, key); return ExpressionLabelUtils.getFirstValue(headers, key);
} }
public static String getQueryValue(RequestTemplate request, String key) { public static String getQueryValue(RequestTemplate request, String key) {

@ -20,10 +20,10 @@ package com.tencent.cloud.polaris.router.feign;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Collection; import java.util.Collection;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Optional;
import com.netflix.client.config.IClientConfig; import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.ILoadBalancer; import com.netflix.loadbalancer.ILoadBalancer;
@ -38,6 +38,8 @@ import org.springframework.cloud.netflix.ribbon.ServerIntrospector;
import org.springframework.cloud.openfeign.ribbon.FeignLoadBalancer; import org.springframework.cloud.openfeign.ribbon.FeignLoadBalancer;
import org.springframework.util.CollectionUtils; import org.springframework.util.CollectionUtils;
import static com.tencent.cloud.common.constant.ContextConstant.UTF_8;
/** /**
* In order to pass router context for {@link com.tencent.cloud.polaris.router.PolarisLoadBalancerCompositeRule}. * In order to pass router context for {@link com.tencent.cloud.polaris.router.PolarisLoadBalancerCompositeRule}.
* *
@ -74,11 +76,15 @@ public class PolarisFeignLoadBalancer extends FeignLoadBalancer {
Map<String, String> labelHeaderValuesMap = new HashMap<>(); Map<String, String> labelHeaderValuesMap = new HashMap<>();
try { try {
String labelHeaderValuesContent = labelHeaderValues.stream().findFirst().get(); Optional<String> opt = labelHeaderValues.stream().findFirst();
labelHeaderValuesMap.putAll(JacksonUtils.deserialize2Map(URLDecoder.decode(labelHeaderValuesContent, StandardCharsets.UTF_8.name()))); if (opt.isPresent()) {
String labelHeaderValuesContent = opt.get();
Map<String, String> labels = JacksonUtils.deserialize2Map(URLDecoder.decode(labelHeaderValuesContent, UTF_8));
labelHeaderValuesMap.putAll(labels);
}
} }
catch (UnsupportedEncodingException e) { catch (UnsupportedEncodingException e) {
throw new RuntimeException("unsupported charset exception " + StandardCharsets.UTF_8.name()); throw new RuntimeException("unsupported charset exception " + UTF_8);
} }
routerContext.setLabels(PolarisRouterContext.RULE_ROUTER_LABELS, labelHeaderValuesMap); routerContext.setLabels(PolarisRouterContext.RULE_ROUTER_LABELS, labelHeaderValuesMap);

@ -20,7 +20,6 @@ package com.tencent.cloud.polaris.router.feign;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Collections; import java.util.Collections;
import java.util.Comparator; import java.util.Comparator;
import java.util.HashMap; import java.util.HashMap;
@ -43,6 +42,8 @@ import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered; import org.springframework.core.Ordered;
import org.springframework.util.CollectionUtils; import org.springframework.util.CollectionUtils;
import static com.tencent.cloud.common.constant.ContextConstant.UTF_8;
/** /**
* Resolver labels from request. * Resolver labels from request.
* *
@ -112,10 +113,10 @@ public class RouterLabelFeignInterceptor implements RequestInterceptor, Ordered
String encodedLabelsContent; String encodedLabelsContent;
try { try {
encodedLabelsContent = URLEncoder.encode(JacksonUtils.serialize2Json(labels), StandardCharsets.UTF_8.name()); encodedLabelsContent = URLEncoder.encode(JacksonUtils.serialize2Json(labels), UTF_8);
} }
catch (UnsupportedEncodingException e) { catch (UnsupportedEncodingException e) {
throw new RuntimeException("unsupported charset exception " + StandardCharsets.UTF_8.name()); throw new RuntimeException("unsupported charset exception " + UTF_8);
} }
requestTemplate.header(RouterConstants.ROUTER_LABEL_HEADER, encodedLabelsContent); requestTemplate.header(RouterConstants.ROUTER_LABEL_HEADER, encodedLabelsContent);
} }

@ -20,7 +20,6 @@ package com.tencent.cloud.polaris.router.feign;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
@ -46,6 +45,7 @@ import org.mockito.MockedStatic;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.MockitoJUnitRunner;
import static com.tencent.cloud.common.constant.ContextConstant.UTF_8;
import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
@ -122,10 +122,10 @@ public class RouterLabelFeignInterceptorTest {
try { try {
String routerLabelContent = routerLabels.stream().findFirst().get(); String routerLabelContent = routerLabels.stream().findFirst().get();
routerLabelsMap.putAll(JacksonUtils.deserialize2Map( routerLabelsMap.putAll(JacksonUtils.deserialize2Map(
URLDecoder.decode(routerLabelContent, StandardCharsets.UTF_8.name()))); URLDecoder.decode(routerLabelContent, UTF_8)));
} }
catch (UnsupportedEncodingException e) { catch (UnsupportedEncodingException e) {
throw new RuntimeException("unsupported charset exception " + StandardCharsets.UTF_8.name()); throw new RuntimeException("unsupported charset exception " + UTF_8);
} }
Assert.assertNotNull(routerLabelsMap); Assert.assertNotNull(routerLabelsMap);
for (String value : routerLabelsMap.values()) { for (String value : routerLabelsMap.values()) {

@ -17,6 +17,8 @@
package com.tencent.cloud.common.constant; package com.tencent.cloud.common.constant;
import java.nio.charset.StandardCharsets;
/** /**
* Constant for Context. * Constant for Context.
* *
@ -29,6 +31,11 @@ public final class ContextConstant {
*/ */
public static final String POLARIS = "POLARIS"; public static final String POLARIS = "POLARIS";
/**
* SCT Default Charset .
*/
public static final String UTF_8 = StandardCharsets.UTF_8.name();
private ContextConstant() { private ContextConstant() {
} }

@ -33,7 +33,7 @@ import org.springframework.lang.Nullable;
* *
* @author Haotian Zhang * @author Haotian Zhang
*/ */
@Configuration @Configuration(proxyBeanMethods = false)
public class MetadataAutoConfiguration { public class MetadataAutoConfiguration {
/** /**

@ -35,7 +35,6 @@ public final class AddressUtils {
private static final String ADDRESS_SEPARATOR = ","; private static final String ADDRESS_SEPARATOR = ",";
private AddressUtils() { private AddressUtils() {
} }
public static List<String> parseAddressList(String addressInfo) { public static List<String> parseAddressList(String addressInfo) {

@ -20,6 +20,7 @@ package com.tencent.cloud.common.util;
import org.springframework.beans.BeansException; import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware; import org.springframework.context.ApplicationContextAware;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
/** /**
@ -41,7 +42,7 @@ public class ApplicationContextAwareUtils implements ApplicationContextAware {
} }
@Override @Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
ApplicationContextAwareUtils.applicationContext = applicationContext; ApplicationContextAwareUtils.applicationContext = applicationContext;
} }

@ -66,6 +66,7 @@ public final class JacksonUtils {
* @param jsonStr Json String * @param jsonStr Json String
* @return Map * @return Map
*/ */
@SuppressWarnings("unchecked")
public static Map<String, String> deserialize2Map(String jsonStr) { public static Map<String, String> deserialize2Map(String jsonStr) {
try { try {
if (StringUtils.hasText(jsonStr)) { if (StringUtils.hasText(jsonStr)) {

@ -27,7 +27,6 @@ import java.lang.reflect.Field;
public final class ReflectionUtils { public final class ReflectionUtils {
private ReflectionUtils() { private ReflectionUtils() {
} }
public static Object getFieldValue(Object instance, String fieldName) { public static Object getFieldValue(Object instance, String fieldName) {

@ -19,7 +19,6 @@ package com.tencent.cloud.polaris.gateway.example.callee;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import com.tencent.cloud.common.constant.MetadataConstant; import com.tencent.cloud.common.constant.MetadataConstant;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -30,6 +29,8 @@ import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import static com.tencent.cloud.common.constant.ContextConstant.UTF_8;
/** /**
* Gateway callee controller. * Gateway callee controller.
* *
@ -65,8 +66,8 @@ public class GatewayCalleeController {
public String echoHeader( public String echoHeader(
@RequestHeader(MetadataConstant.HeaderName.CUSTOM_METADATA) String metadataStr) @RequestHeader(MetadataConstant.HeaderName.CUSTOM_METADATA) String metadataStr)
throws UnsupportedEncodingException { throws UnsupportedEncodingException {
LOG.info(URLDecoder.decode(metadataStr, StandardCharsets.UTF_8.name())); LOG.info(URLDecoder.decode(metadataStr, UTF_8));
return URLDecoder.decode(metadataStr, StandardCharsets.UTF_8.name()); return URLDecoder.decode(metadataStr, UTF_8);
} }
} }

@ -19,7 +19,6 @@ package com.tencent.cloud.polaris.gateway.example.callee;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import com.tencent.cloud.common.constant.MetadataConstant; import com.tencent.cloud.common.constant.MetadataConstant;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -30,6 +29,8 @@ import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import static com.tencent.cloud.common.constant.ContextConstant.UTF_8;
/** /**
* Gateway callee controller. * Gateway callee controller.
* *
@ -65,8 +66,8 @@ public class GatewayCalleeController {
public String echoHeader( public String echoHeader(
@RequestHeader(MetadataConstant.HeaderName.CUSTOM_METADATA) String metadataStr) @RequestHeader(MetadataConstant.HeaderName.CUSTOM_METADATA) String metadataStr)
throws UnsupportedEncodingException { throws UnsupportedEncodingException {
LOG.info(URLDecoder.decode(metadataStr, StandardCharsets.UTF_8.name())); LOG.info(URLDecoder.decode(metadataStr, UTF_8));
return URLDecoder.decode(metadataStr, StandardCharsets.UTF_8.name()); return URLDecoder.decode(metadataStr, UTF_8);
} }
} }

@ -27,12 +27,14 @@ import com.tencent.polaris.client.api.SDKContext;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/** /**
* Autoconfiguration for Polaris {@link SDKContext}. * Autoconfiguration for Polaris {@link SDKContext}.
* *
* @author Haotian Zhang * @author Haotian Zhang
*/ */
@Configuration(proxyBeanMethods = false)
@ConditionalOnPolarisEnabled @ConditionalOnPolarisEnabled
@EnableConfigurationProperties({PolarisContextProperties.class}) @EnableConfigurationProperties({PolarisContextProperties.class})
public class PolarisContextAutoConfiguration { public class PolarisContextAutoConfiguration {

@ -21,6 +21,7 @@ package com.tencent.cloud.polaris.context.config;
import com.tencent.polaris.client.api.SDKContext; import com.tencent.polaris.client.api.SDKContext;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Import;
/** /**
@ -28,6 +29,7 @@ import org.springframework.context.annotation.Import;
* *
* @author Haotian Zhang * @author Haotian Zhang
*/ */
@Configuration(proxyBeanMethods = false)
@ConditionalOnProperty("spring.cloud.polaris.enabled") @ConditionalOnProperty("spring.cloud.polaris.enabled")
@Import(PolarisContextAutoConfiguration.class) @Import(PolarisContextAutoConfiguration.class)
public class PolarisContextBootstrapAutoConfiguration { public class PolarisContextBootstrapAutoConfiguration {

@ -28,14 +28,12 @@ import com.tencent.cloud.polaris.loadbalancer.PolarisLoadBalancer;
import com.tencent.polaris.api.core.ConsumerAPI; import com.tencent.polaris.api.core.ConsumerAPI;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/** /**
* Configuration of ribbon client of Polaris. * Configuration of ribbon client of Polaris.
* *
* @author Haotian Zhang * @author Haotian Zhang
*/ */
@Configuration
public class PolarisRibbonClientConfiguration { public class PolarisRibbonClientConfiguration {
@Bean @Bean

Loading…
Cancel
Save