Optimize starter's auto-configuration . (2021) (#396)

pull/403/head
VOPEN.XYZ 2 years ago committed by GitHub
parent 1ce6336f51
commit 8334f5015a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -24,6 +24,8 @@
- [Use jdk constants instead of magic variables](https://github.com/Tencent/spring-cloud-tencent/pull/361) - [Use jdk constants instead of magic variables](https://github.com/Tencent/spring-cloud-tencent/pull/361)
- [Refator JacksonUtils and JacksonUtilsTest](https://github.com/Tencent/spring-cloud-tencent/pull/367) - [Refator JacksonUtils and JacksonUtilsTest](https://github.com/Tencent/spring-cloud-tencent/pull/367)
- [Feature: support actuator for sct core components](https://github.com/Tencent/spring-cloud-tencent/pull/369) - [Feature: support actuator for sct core components](https://github.com/Tencent/spring-cloud-tencent/pull/369)
- [docs: Fix javadoc <br /> error](https://github.com/Tencent/spring-cloud-tencent/pull/376) - [docs: Fix javadoc <br \/> error](https://github.com/Tencent/spring-cloud-tencent/pull/376)
- [docs:optimize example](https://github.com/Tencent/spring-cloud-tencent/pull/387) - [docs:optimize example](https://github.com/Tencent/spring-cloud-tencent/pull/387)
- [Feature: support spring cloud gateway routers](https://github.com/Tencent/spring-cloud-tencent/pull/390) - [Feature: support spring cloud gateway routers](https://github.com/Tencent/spring-cloud-tencent/pull/390)
- [Optimize starter's auto-configuration](https://github.com/Tencent/spring-cloud-tencent/pull/396)

@ -39,6 +39,7 @@ import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestInterceptor; import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.lang.NonNull;
import org.springframework.util.CollectionUtils; import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate; import org.springframework.web.client.RestTemplate;
@ -53,15 +54,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(
@ -79,57 +80,53 @@ public class MetadataTransferAutoConfiguration {
public DecodeTransferMetadataServletFilter metadataServletFilter() { public DecodeTransferMetadataServletFilter metadataServletFilter() {
return new DecodeTransferMetadataServletFilter(); return new DecodeTransferMetadataServletFilter();
} }
} }
/** /**
* 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() {
return new DecodeTransferMetadataReactiveFilter(); return new DecodeTransferMetadataReactiveFilter();
} }
} }
/** /**
* 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() {
return new EncodeTransferMedataScgFilter(); return new EncodeTransferMedataScgFilter();
} }
} }
/** /**
* 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() {
return new EncodeTransferMedataFeignInterceptor(); return new EncodeTransferMedataFeignInterceptor();
} }
} }
/** /**
* 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;
@ -163,15 +160,14 @@ public class MetadataTransferAutoConfiguration {
} }
@Override @Override
public void setApplicationContext(ApplicationContext applicationContext) public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
throws BeansException {
this.context = applicationContext; this.context = applicationContext;
} }
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) {
@ -179,12 +175,12 @@ public class MetadataTransferAutoConfiguration {
} }
@Override @Override
public Object postProcessBeforeInitialization(Object bean, String beanName) { public Object postProcessBeforeInitialization(@NonNull Object bean, @NonNull String beanName) {
return bean; return bean;
} }
@Override @Override
public Object postProcessAfterInitialization(Object bean, String beanName) { public Object postProcessAfterInitialization(@NonNull Object bean, @NonNull String beanName) {
if (bean instanceof RestTemplate) { if (bean instanceof RestTemplate) {
RestTemplate restTemplate = (RestTemplate) bean; RestTemplate restTemplate = (RestTemplate) bean;
List<ClientHttpRequestInterceptor> interceptors = restTemplate List<ClientHttpRequestInterceptor> interceptors = restTemplate
@ -197,9 +193,6 @@ public class MetadataTransferAutoConfiguration {
} }
return bean; return bean;
} }
} }
} }
} }

@ -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.
@ -81,11 +82,10 @@ public class DecodeTransferMetadataReactiveFilter implements WebFilter, Ordered
private Map<String, String> getIntervalTransitiveMetadata(ServerHttpRequest serverHttpRequest) { private Map<String, String> getIntervalTransitiveMetadata(ServerHttpRequest serverHttpRequest) {
HttpHeaders httpHeaders = serverHttpRequest.getHeaders(); HttpHeaders httpHeaders = serverHttpRequest.getHeaders();
String customMetadataStr = httpHeaders String customMetadataStr = httpHeaders.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) {
@ -95,5 +95,4 @@ public class DecodeTransferMetadataReactiveFilter implements WebFilter, Ordered
return JacksonUtils.deserialize2Map(customMetadataStr); return JacksonUtils.deserialize2Map(customMetadataStr);
} }
} }

@ -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);
@ -71,5 +71,4 @@ public class EncodeTransferMedataFeignInterceptor implements RequestInterceptor,
} }
} }
} }
} }

@ -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;
@ -36,6 +35,8 @@ import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse; import org.springframework.http.client.ClientHttpResponse;
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.
@ -60,7 +61,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, encodedTransitiveMetadata); httpRequest.getHeaders().set(MetadataConstant.HeaderName.CUSTOM_METADATA, encodedTransitiveMetadata);
@ -68,5 +69,4 @@ public class EncodeTransferMedataRestTemplateInterceptor implements ClientHttpRe
} }
return clientHttpRequestExecution.execute(httpRequest, bytes); return clientHttpRequestExecution.execute(httpRequest, bytes);
} }
} }

@ -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.ReactiveLoadBalancerClientFilter.LOAD_BALANCER_CLIENT_FILTER_ORDER; import static org.springframework.cloud.gateway.filter.ReactiveLoadBalancerClientFilter.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);

@ -97,9 +97,6 @@ public class EncodeTransferMedataFeignInterceptorTest {
template.header(MetadataConstant.HeaderName.CUSTOM_METADATA, template.header(MetadataConstant.HeaderName.CUSTOM_METADATA,
"{\"a\":\"11\",\"b\":\"22\",\"c\":\"33\"}"); "{\"a\":\"11\",\"b\":\"22\",\"c\":\"33\"}");
} }
} }
} }
} }

@ -19,7 +19,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.tencent.cloud.common.constant.MetadataConstant; import com.tencent.cloud.common.constant.MetadataConstant;
@ -38,6 +37,7 @@ 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;
/** /**
@ -48,7 +48,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
@RunWith(SpringRunner.class) @RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = RANDOM_PORT, @SpringBootTest(webEnvironment = RANDOM_PORT,
classes = EncodeTransferMedataScgFilterTest.TestApplication.class, classes = EncodeTransferMedataScgFilterTest.TestApplication.class,
properties = { "spring.config.location = classpath:application-test.yml", "spring.main.web-application-type = reactive" }) properties = {"spring.config.location = classpath:application-test.yml", "spring.main.web-application-type = reactive"})
public class EncodeTransferMedataScgFilterTest { public class EncodeTransferMedataScgFilterTest {
@Autowired @Autowired
@ -64,7 +64,7 @@ public class EncodeTransferMedataScgFilterTest {
MockServerWebExchange exchange = MockServerWebExchange.from(builder); MockServerWebExchange exchange = MockServerWebExchange.from(builder);
filter.filter(exchange, chain); filter.filter(exchange, chain);
String metadataStr = exchange.getRequest().getHeaders().getFirst(MetadataConstant.HeaderName.CUSTOM_METADATA); String metadataStr = exchange.getRequest().getHeaders().getFirst(MetadataConstant.HeaderName.CUSTOM_METADATA);
String decode = URLDecoder.decode(metadataStr, StandardCharsets.UTF_8.name()); String decode = URLDecoder.decode(metadataStr, 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
@ -66,7 +65,5 @@ public class PolarisCircuitBreakerBootstrapConfiguration {
public int getOrder() { public int getOrder() {
return ContextConstant.ModifierOrder.CIRCUIT_BREAKER_ORDER; return ContextConstant.ModifierOrder.CIRCUIT_BREAKER_ORDER;
} }
} }
} }

@ -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,59 +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);
}
}

@ -34,5 +34,4 @@ public class PolarisFeignBlockingLoadBalancerClient extends FeignBlockingLoadBal
LoadBalancerClientFactory loadBalancerClientFactory) { LoadBalancerClientFactory loadBalancerClientFactory) {
super(delegate, loadBalancerClient, loadBalancerClientFactory); super(delegate, loadBalancerClient, loadBalancerClientFactory);
} }
} }

@ -1,5 +1,4 @@
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,17 +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( .withConfiguration(
AutoConfigurations.of( AutoConfigurations.of(
PolarisContextAutoConfiguration.class, PolarisContextAutoConfiguration.class,
PolarisFeignClientAutoConfiguration.class)) PolarisCircuitBreakerAutoConfiguration.class))
.withPropertyValues("spring.cloud.polaris.circuitbreaker.enabled=true"); .withPropertyValues("spring.cloud.polaris.circuitbreaker.enabled=true");
@Test @Test
@ -49,5 +49,4 @@ public class PolarisFeignClientAutoConfigurationTest {
assertThat(context).hasSingleBean(PolarisFeignBeanPostProcessor.class); assertThat(context).hasSingleBean(PolarisFeignBeanPostProcessor.class);
}); });
} }
} }

@ -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
*/ */
@ -46,7 +46,7 @@ public class PolarisRestTemplateAutoConfigurationTest {
AutoConfigurations.of( 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
@ -60,7 +60,7 @@ public class PolarisRestTemplateAutoConfigurationTest {
@Configuration @Configuration
@EnableAutoConfiguration @EnableAutoConfiguration
@AutoConfigureBefore(PolarisRestTemplateAutoConfiguration.class) @AutoConfigureBefore(PolarisCircuitBreakerAutoConfiguration.class)
static class PolarisRestTemplateAutoConfigurationTester { static class PolarisRestTemplateAutoConfigurationTester {
@Bean @Bean
@ -68,5 +68,4 @@ public class PolarisRestTemplateAutoConfigurationTest {
return new RestTemplate(); return new RestTemplate();
} }
} }
} }

@ -57,5 +57,4 @@ public class PolarisConfigAutoConfiguration {
public PolarisConfigChangeEventListener polarisConfigChangeEventListener() { public PolarisConfigChangeEventListener polarisConfigChangeEventListener() {
return new PolarisConfigChangeEventListener(); return new PolarisConfigChangeEventListener();
} }
} }

@ -79,5 +79,4 @@ public class PolarisConfigBootstrapAutoConfiguration {
PolarisContextProperties polarisContextProperties) { PolarisContextProperties polarisContextProperties) {
return new ConfigurationModifier(polarisConfigProperties, polarisContextProperties); return new ConfigurationModifier(polarisConfigProperties, polarisContextProperties);
} }
} }

@ -94,5 +94,4 @@ public class PolarisConfigProperties {
public void setGroups(List<ConfigFileGroup> groups) { public void setGroups(List<ConfigFileGroup> groups) {
this.groups = groups; this.groups = groups;
} }
} }

@ -36,8 +36,7 @@ import org.springframework.context.annotation.Configuration;
**/ **/
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
@ConditionalOnClass(Endpoint.class) @ConditionalOnClass(Endpoint.class)
@ConditionalOnProperty(value = "spring.cloud.polaris.config.enabled", @ConditionalOnProperty(value = "spring.cloud.polaris.config.enabled", matchIfMissing = true)
matchIfMissing = true)
public class PolarisConfigEndpointAutoConfiguration { public class PolarisConfigEndpointAutoConfiguration {
@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;
@ -39,13 +42,13 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
/** /**
* Integration testing for change listener. * Integration testing for change listener.
*@author lepdou 2022-06-11 *
* @author lepdou 2022-06-11
*/ */
@RunWith(SpringRunner.class) @RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = DEFINED_PORT, @SpringBootTest(webEnvironment = DEFINED_PORT,
classes = ConfigChangeListenerTest.TestApplication.class, classes = ConfigChangeListenerTest.TestApplication.class,
properties = {"server.port=8081", properties = {"server.port=8081", "spring.config.location = classpath:application-test.yml"})
"spring.config.location = classpath:application-test.yml"})
public class ConfigChangeListenerTest { public class ConfigChangeListenerTest {
@Autowired @Autowired
@ -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();
} }
} }
@ -120,5 +129,4 @@ public class ConfigChangeListenerTest {
} }
} }
} }
} }

@ -17,8 +17,6 @@
*/ */
package com.tencent.cloud.polaris; package com.tencent.cloud.polaris;
import javax.annotation.PostConstruct;
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;
import com.tencent.cloud.polaris.extend.consul.ConsulContextProperties; import com.tencent.cloud.polaris.extend.consul.ConsulContextProperties;
@ -28,7 +26,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 +38,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,25 +63,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,8 +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 +229,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;
@ -256,7 +253,5 @@ public class PolarisDiscoveryProperties {
public int getOrder() { public int getOrder() {
return ContextConstant.ModifierOrder.LAST; return ContextConstant.ModifierOrder.LAST;
} }
} }
} }

@ -43,5 +43,4 @@ public class PolarisDiscoveryAutoConfiguration {
PolarisDiscoveryHandler polarisDiscoveryHandler) { PolarisDiscoveryHandler polarisDiscoveryHandler) {
return new PolarisServiceDiscovery(polarisDiscoveryHandler); return new PolarisServiceDiscovery(polarisDiscoveryHandler);
} }
} }

@ -41,5 +41,4 @@ public class PolarisDiscoveryClientConfiguration {
public DiscoveryClient polarisDiscoveryClient(PolarisServiceDiscovery polarisServiceDiscovery) { public DiscoveryClient polarisDiscoveryClient(PolarisServiceDiscovery polarisServiceDiscovery) {
return new PolarisDiscoveryClient(polarisServiceDiscovery); return new PolarisDiscoveryClient(polarisServiceDiscovery);
} }
} }

@ -38,9 +38,9 @@ import org.springframework.cloud.client.discovery.ReactiveDiscoveryClient;
*/ */
public class PolarisReactiveDiscoveryClient implements ReactiveDiscoveryClient { public class PolarisReactiveDiscoveryClient implements ReactiveDiscoveryClient {
private static final Logger log = LoggerFactory.getLogger(PolarisReactiveDiscoveryClient.class); private static final Logger LOGGER = LoggerFactory.getLogger(PolarisReactiveDiscoveryClient.class);
private PolarisServiceDiscovery polarisServiceDiscovery; private final PolarisServiceDiscovery polarisServiceDiscovery;
public PolarisReactiveDiscoveryClient(PolarisServiceDiscovery polarisServiceDiscovery) { public PolarisReactiveDiscoveryClient(PolarisServiceDiscovery polarisServiceDiscovery) {
this.polarisServiceDiscovery = polarisServiceDiscovery; this.polarisServiceDiscovery = polarisServiceDiscovery;
@ -64,7 +64,7 @@ public class PolarisReactiveDiscoveryClient implements ReactiveDiscoveryClient {
return Flux.fromIterable(polarisServiceDiscovery.getInstances(serviceId)); return Flux.fromIterable(polarisServiceDiscovery.getInstances(serviceId));
} }
catch (PolarisException e) { catch (PolarisException e) {
log.error("get service instance[{}] from polaris error!", serviceId, e); LOGGER.error("get service instance[{}] from polaris error!", serviceId, e);
return Flux.empty(); return Flux.empty();
} }
}; };
@ -77,10 +77,9 @@ public class PolarisReactiveDiscoveryClient implements ReactiveDiscoveryClient {
return Flux.fromIterable(polarisServiceDiscovery.getServices()); return Flux.fromIterable(polarisServiceDiscovery.getServices());
} }
catch (Exception e) { catch (Exception e) {
log.error("get services from polaris server fail,", e); LOGGER.error("get services from polaris server fail,", e);
return Flux.empty(); return Flux.empty();
} }
}).subscribeOn(Schedulers.boundedElastic()); }).subscribeOn(Schedulers.boundedElastic());
} }
} }

@ -47,5 +47,4 @@ public class PolarisReactiveDiscoveryClientConfiguration {
PolarisServiceDiscovery polarisServiceDiscovery) { PolarisServiceDiscovery polarisServiceDiscovery) {
return new PolarisReactiveDiscoveryClient(polarisServiceDiscovery); return new PolarisReactiveDiscoveryClient(polarisServiceDiscovery);
} }
} }

@ -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;
@ -164,7 +164,5 @@ public class ConsulContextProperties {
public int getOrder() { public int getOrder() {
return ModifierOrder.LAST; return ModifierOrder.LAST;
} }
} }
} }

@ -33,7 +33,7 @@ import org.springframework.util.StringUtils;
*/ */
public class PolarisAutoServiceRegistration extends AbstractAutoServiceRegistration<Registration> { public class PolarisAutoServiceRegistration extends AbstractAutoServiceRegistration<Registration> {
private static final Logger log = LoggerFactory.getLogger(PolarisAutoServiceRegistration.class); private static final Logger LOGGER = LoggerFactory.getLogger(PolarisAutoServiceRegistration.class);
private final PolarisRegistration registration; private final PolarisRegistration registration;
@ -59,7 +59,7 @@ public class PolarisAutoServiceRegistration extends AbstractAutoServiceRegistrat
@Override @Override
protected void register() { protected void register() {
if (!this.registration.isRegisterEnabled()) { if (!this.registration.isRegisterEnabled()) {
log.debug("Registration disabled."); LOGGER.debug("Registration disabled.");
return; return;
} }
if (this.registration.getPort() <= 0) { if (this.registration.getPort() <= 0) {
@ -74,7 +74,6 @@ public class PolarisAutoServiceRegistration extends AbstractAutoServiceRegistrat
return; return;
} }
super.registerManagement(); super.registerManagement();
} }
@Override @Override
@ -93,5 +92,4 @@ public class PolarisAutoServiceRegistration extends AbstractAutoServiceRegistrat
String appName = registration.getPolarisProperties().getService(); String appName = registration.getPolarisProperties().getService();
return StringUtils.isEmpty(appName) ? super.getAppName() : appName; return StringUtils.isEmpty(appName) ? super.getAppName() : appName;
} }
} }

@ -24,14 +24,15 @@ 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;
/** /**
@ -41,13 +42,13 @@ import org.springframework.util.CollectionUtils;
*/ */
public class PolarisRegistration implements Registration, ServiceInstance { public class PolarisRegistration implements Registration, ServiceInstance {
private final static String METADATA_KEY_IP = "internal-ip"; private static final String METADATA_KEY_IP = "internal-ip";
private final static String METADATA_KEY_ADDRESS = "internal-address"; private static final String METADATA_KEY_ADDRESS = "internal-address";
private final DiscoveryPropertiesAutoConfiguration discoveryPropertiesAutoConfiguration;
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;
@ -57,11 +58,11 @@ public class PolarisRegistration implements Registration, ServiceInstance {
private final String host; 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;
@ -121,14 +122,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 +

@ -51,9 +51,9 @@ import static org.springframework.util.ReflectionUtils.rethrowRuntimeException;
*/ */
public class PolarisServiceRegistry implements ServiceRegistry<Registration> { public class PolarisServiceRegistry implements ServiceRegistry<Registration> {
private static final Logger log = LoggerFactory.getLogger(PolarisServiceRegistry.class); private static final Logger LOGGER = LoggerFactory.getLogger(PolarisServiceRegistry.class);
private static final int ttl = 5; private static final int TTL = 5;
private final PolarisDiscoveryProperties polarisDiscoveryProperties; private final PolarisDiscoveryProperties polarisDiscoveryProperties;
@ -83,7 +83,7 @@ public class PolarisServiceRegistry implements ServiceRegistry<Registration> {
public void register(Registration registration) { public void register(Registration registration) {
if (StringUtils.isBlank(registration.getServiceId())) { if (StringUtils.isBlank(registration.getServiceId())) {
log.warn("No service to register for polaris client..."); LOGGER.warn("No service to register for polaris client...");
return; return;
} }
// Register instance. // Register instance.
@ -98,7 +98,7 @@ public class PolarisServiceRegistry implements ServiceRegistry<Registration> {
instanceRegisterRequest.setZone(staticMetadataManager.getZone()); instanceRegisterRequest.setZone(staticMetadataManager.getZone());
instanceRegisterRequest.setCampus(staticMetadataManager.getCampus()); instanceRegisterRequest.setCampus(staticMetadataManager.getCampus());
if (null != heartbeatExecutor) { if (null != heartbeatExecutor) {
instanceRegisterRequest.setTtl(ttl); instanceRegisterRequest.setTtl(TTL);
} }
instanceRegisterRequest.setMetadata(registration.getMetadata()); instanceRegisterRequest.setMetadata(registration.getMetadata());
instanceRegisterRequest.setProtocol(polarisDiscoveryProperties.getProtocol()); instanceRegisterRequest.setProtocol(polarisDiscoveryProperties.getProtocol());
@ -106,7 +106,7 @@ public class PolarisServiceRegistry implements ServiceRegistry<Registration> {
try { try {
ProviderAPI providerClient = polarisDiscoveryHandler.getProviderAPI(); ProviderAPI providerClient = polarisDiscoveryHandler.getProviderAPI();
providerClient.register(instanceRegisterRequest); providerClient.register(instanceRegisterRequest);
log.info("polaris registry, {} {} {}:{} {} register finished", polarisDiscoveryProperties.getNamespace(), LOGGER.info("polaris registry, {} {} {}:{} {} register finished", polarisDiscoveryProperties.getNamespace(),
registration.getServiceId(), registration.getHost(), registration.getPort(), registration.getServiceId(), registration.getHost(), registration.getPort(),
staticMetadataManager.getMergedStaticMetadata()); staticMetadataManager.getMergedStaticMetadata());
@ -118,7 +118,7 @@ public class PolarisServiceRegistry implements ServiceRegistry<Registration> {
} }
} }
catch (Exception e) { catch (Exception e) {
log.error("polaris registry, {} register failed...{},", registration.getServiceId(), registration, e); LOGGER.error("polaris registry, {} register failed...{},", registration.getServiceId(), registration, e);
rethrowRuntimeException(e); rethrowRuntimeException(e);
} }
} }
@ -126,10 +126,10 @@ public class PolarisServiceRegistry implements ServiceRegistry<Registration> {
@Override @Override
public void deregister(Registration registration) { public void deregister(Registration registration) {
log.info("De-registering from Polaris Server now..."); LOGGER.info("De-registering from Polaris Server now...");
if (StringUtils.isEmpty(registration.getServiceId())) { if (StringUtils.isEmpty(registration.getServiceId())) {
log.warn("No dom to de-register for polaris client..."); LOGGER.warn("No dom to de-register for polaris client...");
return; return;
} }
@ -145,24 +145,22 @@ public class PolarisServiceRegistry implements ServiceRegistry<Registration> {
providerClient.deRegister(deRegisterRequest); providerClient.deRegister(deRegisterRequest);
} }
catch (Exception e) { catch (Exception e) {
log.error("ERR_POLARIS_DEREGISTER, de-register failed...{},", registration, e); LOGGER.error("ERR_POLARIS_DEREGISTER, de-register failed...{},", registration, e);
} }
finally { finally {
if (null != heartbeatExecutor) { if (null != heartbeatExecutor) {
heartbeatExecutor.shutdown(); heartbeatExecutor.shutdown();
} }
} }
log.info("De-registration finished."); LOGGER.info("De-registration finished.");
} }
@Override @Override
public void close() { public void close() {
} }
@Override @Override
public void setStatus(Registration registration, String status) { public void setStatus(Registration registration, String status) {
} }
@Override @Override
@ -204,7 +202,7 @@ public class PolarisServiceRegistry implements ServiceRegistry<Registration> {
heartbeatRequest.getPort(), healthCheckEndpoint); heartbeatRequest.getPort(), healthCheckEndpoint);
if (!OkHttpUtil.get(healthCheckUrl, null)) { if (!OkHttpUtil.get(healthCheckUrl, null)) {
log.error("backend service health check failed. health check endpoint = {}", LOGGER.error("backend service health check failed. health check endpoint = {}",
healthCheckEndpoint); healthCheckEndpoint);
return; return;
} }
@ -213,12 +211,11 @@ public class PolarisServiceRegistry implements ServiceRegistry<Registration> {
polarisDiscoveryHandler.getProviderAPI().heartbeat(heartbeatRequest); polarisDiscoveryHandler.getProviderAPI().heartbeat(heartbeatRequest);
} }
catch (PolarisException e) { catch (PolarisException e) {
log.error("polaris heartbeat[{}]", e.getCode(), e); LOGGER.error("polaris heartbeat[{}]", e.getCode(), e);
} }
catch (Exception e) { catch (Exception e) {
log.error("polaris heartbeat runtime error", e); LOGGER.error("polaris heartbeat runtime error", e);
} }
}, ttl, ttl, TimeUnit.SECONDS); }, TTL, TTL, TimeUnit.SECONDS);
} }
} }

@ -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;
@ -58,11 +59,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

@ -36,7 +36,7 @@ public final class OkHttpUtil {
/** /**
* Logger. * Logger.
*/ */
public final static Logger logger = LoggerFactory.getLogger(OkHttpUtil.class); public final static Logger LOGGER = LoggerFactory.getLogger(OkHttpUtil.class);
/** /**
* client. * client.
@ -62,12 +62,12 @@ public final class OkHttpUtil {
if (response.isSuccessful() && Objects.nonNull(response.body())) { if (response.isSuccessful() && Objects.nonNull(response.body())) {
String result = response.body().string(); String result = response.body().string();
logger.debug("exec get request, url: {} successresponse data: {}", url, result); LOGGER.debug("exec get request, url: {} successresponse data: {}", url, result);
return true; return true;
} }
} }
catch (Exception e) { catch (Exception e) {
logger.error("exec get requesturl: {} failed!", url, e); LOGGER.error("exec get requesturl: {} failed!", url, e);
} }
return false; return false;
} }
@ -86,5 +86,4 @@ public final class OkHttpUtil {
}); });
} }
} }
} }

@ -65,9 +65,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,19 +92,18 @@ 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;
} }
} }
/** /**
* 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,
@ -113,7 +113,5 @@ public class PolarisRateLimitAutoConfiguration {
return new QuotaCheckReactiveFilter(limitAPI, labelResolver, return new QuotaCheckReactiveFilter(limitAPI, labelResolver,
polarisRateLimitProperties, rateLimitRuleLabelResolver); polarisRateLimitProperties, rateLimitRuleLabelResolver);
} }
} }
} }

@ -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;
@ -45,5 +45,4 @@ public class RateLimitConfigModifier implements PolarisConfigModifier {
public int getOrder() { public int getOrder() {
return ContextConstant.ModifierOrder.CIRCUIT_BREAKER_ORDER; return ContextConstant.ModifierOrder.CIRCUIT_BREAKER_ORDER;
} }
} }

@ -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;

@ -39,11 +39,11 @@ import static org.assertj.core.api.Assertions.assertThat;
*/ */
public class PolarisRateLimitAutoConfigurationTest { public class PolarisRateLimitAutoConfigurationTest {
private ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner(); private final ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner();
private WebApplicationContextRunner webApplicationContextRunner = new WebApplicationContextRunner(); private final WebApplicationContextRunner webApplicationContextRunner = new WebApplicationContextRunner();
private ReactiveWebApplicationContextRunner reactiveWebApplicationContextRunner = new ReactiveWebApplicationContextRunner(); private final ReactiveWebApplicationContextRunner reactiveWebApplicationContextRunner = new ReactiveWebApplicationContextRunner();
@Test @Test
public void testNoWebApplication() { public void testNoWebApplication() {

@ -51,7 +51,7 @@ import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class) @RunWith(MockitoJUnitRunner.class)
public class PolarisRateLimitRuleEndpointTests { public class PolarisRateLimitRuleEndpointTests {
private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.withConfiguration(AutoConfigurations.of( .withConfiguration(AutoConfigurations.of(
PolarisRateLimitRuleEndpointTests.PolarisRateLimitAutoConfiguration.class, PolarisRateLimitRuleEndpointTests.PolarisRateLimitAutoConfiguration.class,
PolarisRateLimitRuleEndpointAutoConfiguration.class, PolarisRateLimitRuleEndpointAutoConfiguration.class,

@ -34,7 +34,7 @@ import org.springframework.lang.Nullable;
* Auto configuration for feign components. * Auto configuration for feign components.
* @author lepdou 2022-07-04 * @author lepdou 2022-07-04
*/ */
@Configuration @Configuration(proxyBeanMethods = false)
@ConditionalOnClass(name = {"feign.RequestInterceptor"}) @ConditionalOnClass(name = {"feign.RequestInterceptor"})
public class FeignAutoConfiguration { public class FeignAutoConfiguration {
@ -44,5 +44,4 @@ public class FeignAutoConfiguration {
RouterRuleLabelResolver routerRuleLabelResolver) { RouterRuleLabelResolver routerRuleLabelResolver) {
return new RouterLabelFeignInterceptor(routerLabelResolvers, metadataLocalProperties, routerRuleLabelResolver); return new RouterLabelFeignInterceptor(routerLabelResolvers, metadataLocalProperties, routerRuleLabelResolver);
} }
} }

@ -46,10 +46,10 @@ public class LoadBalancerConfiguration {
*/ */
private static final int REACTIVE_SERVICE_INSTANCE_SUPPLIER_ORDER = 193827465; private static final int REACTIVE_SERVICE_INSTANCE_SUPPLIER_ORDER = 193827465;
@Configuration @Configuration(proxyBeanMethods = false)
@ConditionalOnReactiveDiscoveryEnabled @ConditionalOnReactiveDiscoveryEnabled
@Order(REACTIVE_SERVICE_INSTANCE_SUPPLIER_ORDER) @Order(REACTIVE_SERVICE_INSTANCE_SUPPLIER_ORDER)
static class PolarisReactiveSupportConfiguration { protected static class PolarisReactiveSupportConfiguration {
@Bean @Bean
@ConditionalOnBean(ReactiveDiscoveryClient.class) @ConditionalOnBean(ReactiveDiscoveryClient.class)
@ -69,10 +69,10 @@ public class LoadBalancerConfiguration {
} }
@Configuration @Configuration(proxyBeanMethods = false)
@ConditionalOnBlockingDiscoveryEnabled @ConditionalOnBlockingDiscoveryEnabled
@Order(REACTIVE_SERVICE_INSTANCE_SUPPLIER_ORDER + 1) @Order(REACTIVE_SERVICE_INSTANCE_SUPPLIER_ORDER + 1)
static class PolarisBlockingSupportConfiguration { protected static class PolarisBlockingSupportConfiguration {
@Bean @Bean
@ConditionalOnBean(DiscoveryClient.class) @ConditionalOnBean(DiscoveryClient.class)

@ -44,5 +44,4 @@ public class PolarisRuleBasedRouterProperties {
"enabled=" + enabled + "enabled=" + enabled +
'}'; '}';
} }
} }

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

@ -21,7 +21,6 @@ package com.tencent.cloud.polaris.router.scg;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.net.URI; import java.net.URI;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
@ -65,6 +64,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.support.ServerWebExchangeUtils.GATEWAY_LOADBALANCER_RESPONSE_ATTR; import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_LOADBALANCER_RESPONSE_ATTR;
import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR; import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR;
import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_SCHEME_PREFIX_ATTR; import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_SCHEME_PREFIX_ATTR;
@ -76,7 +76,7 @@ import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.a
*@author lepdou 2022-06-20 *@author lepdou 2022-06-20
*/ */
public class PolarisReactiveLoadBalancerClientFilter extends ReactiveLoadBalancerClientFilter { public class PolarisReactiveLoadBalancerClientFilter extends ReactiveLoadBalancerClientFilter {
private static final Logger log = LoggerFactory.getLogger(PolarisReactiveLoadBalancerClientFilter.class); private static final Logger LOGGER = LoggerFactory.getLogger(PolarisReactiveLoadBalancerClientFilter.class);
private final LoadBalancerClientFactory clientFactory; private final LoadBalancerClientFactory clientFactory;
private final GatewayLoadBalancerProperties gatewayLoadBalancerProperties; private final GatewayLoadBalancerProperties gatewayLoadBalancerProperties;
@ -114,8 +114,8 @@ public class PolarisReactiveLoadBalancerClientFilter extends ReactiveLoadBalance
// preserve the original url // preserve the original url
addOriginalRequestUrl(exchange, url); addOriginalRequestUrl(exchange, url);
if (log.isTraceEnabled()) { if (LOGGER.isTraceEnabled()) {
log.trace(ReactiveLoadBalancerClientFilter.class.getSimpleName() + " url before: " + url); LOGGER.trace(ReactiveLoadBalancerClientFilter.class.getSimpleName() + " url before: " + url);
} }
URI requestUri = exchange.getAttribute(GATEWAY_REQUEST_URL_ATTR); URI requestUri = exchange.getAttribute(GATEWAY_REQUEST_URL_ATTR);
@ -158,8 +158,8 @@ public class PolarisReactiveLoadBalancerClientFilter extends ReactiveLoadBalance
URI requestUrl = reconstructURI(serviceInstance, uri); URI requestUrl = reconstructURI(serviceInstance, uri);
if (log.isTraceEnabled()) { if (LOGGER.isTraceEnabled()) {
log.trace("LoadBalancerClientFilter url chosen: " + requestUrl); LOGGER.trace("LoadBalancerClientFilter url chosen: " + requestUrl);
} }
exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, requestUrl); exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, requestUrl);
exchange.getAttributes().put(GATEWAY_LOADBALANCER_RESPONSE_ATTR, response); exchange.getAttributes().put(GATEWAY_LOADBALANCER_RESPONSE_ATTR, response);
@ -210,10 +210,10 @@ public class PolarisReactiveLoadBalancerClientFilter extends ReactiveLoadBalance
Map<String, String> routerLabels = genRouterLabels(exchange, peerServiceName); Map<String, String> routerLabels = genRouterLabels(exchange, peerServiceName);
String encodedLabelsContent; String encodedLabelsContent;
try { try {
encodedLabelsContent = URLEncoder.encode(JacksonUtils.serialize2Json(routerLabels), StandardCharsets.UTF_8.name()); encodedLabelsContent = URLEncoder.encode(JacksonUtils.serialize2Json(routerLabels), 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);
} }
return encodedLabelsContent; return encodedLabelsContent;
} }
@ -238,7 +238,7 @@ public class PolarisReactiveLoadBalancerClientFilter extends ReactiveLoadBalance
} }
} }
catch (Throwable t) { catch (Throwable t) {
log.error("[SCT][Router] revoke RouterLabelResolver occur some exception. ", t); LOGGER.error("[SCT][Router] revoke RouterLabelResolver occur some exception. ", t);
} }
}); });
} }

@ -20,7 +20,6 @@ package com.tencent.cloud.polaris.router.scg;
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.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -54,6 +53,7 @@ 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.util.CollectionUtils; import org.springframework.util.CollectionUtils;
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;
@ -135,7 +135,7 @@ public class PolarisReactiveLoadBalancerClientFilterTest {
List<String> routerHeaders = headers.get(RouterConstants.ROUTER_LABEL_HEADER); List<String> routerHeaders = headers.get(RouterConstants.ROUTER_LABEL_HEADER);
Assert.assertFalse(CollectionUtils.isEmpty(routerHeaders)); Assert.assertFalse(CollectionUtils.isEmpty(routerHeaders));
Map<String, String> routerLabels = JacksonUtils.deserialize2Map(URLDecoder.decode(routerHeaders.get(0), StandardCharsets.UTF_8.name())); Map<String, String> routerLabels = JacksonUtils.deserialize2Map(URLDecoder.decode(routerHeaders.get(0), UTF_8));
Assert.assertEquals("v1", routerLabels.get("${http.header.k1}")); Assert.assertEquals("v1", routerLabels.get("${http.header.k1}"));
Assert.assertEquals("zhangsan", routerLabels.get("${http.query.userid}")); Assert.assertEquals("zhangsan", routerLabels.get("${http.query.userid}"));
Assert.assertEquals("blue", routerLabels.get("env")); Assert.assertEquals("blue", routerLabels.get("env"));

@ -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 {
/** /**
@ -54,15 +54,13 @@ public class MetadataAutoConfiguration {
/** /**
* 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 MetadataScgFilterConfig { protected static class MetadataScgFilterConfig {
@Bean @Bean
public GlobalFilter metadataFirstScgFilter() { public GlobalFilter metadataFirstScgFilter() {
return new MetadataFirstScgFilter(); return new MetadataFirstScgFilter();
} }
} }
} }

@ -64,5 +64,4 @@ public class MetadataLocalProperties {
public void setTransitive(List<String> transitive) { public void setTransitive(List<String> transitive) {
this.transitive = transitive; this.transitive = transitive;
} }
} }

@ -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) {
@ -50,5 +49,4 @@ public final class AddressUtils {
} }
return addressList; return addressList;
} }
} }

@ -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;
} }
@ -63,5 +64,4 @@ public class ApplicationContextAwareUtils implements ApplicationContextAware {
public static String getProperties(String key, String defaultValue) { public static String getProperties(String key, String defaultValue) {
return applicationContext.getEnvironment().getProperty(key, defaultValue); return applicationContext.getEnvironment().getProperty(key, defaultValue);
} }
} }

@ -42,7 +42,6 @@ public final class JacksonUtils {
private static final Logger LOG = LoggerFactory.getLogger(JacksonUtils.class); private static final Logger LOG = LoggerFactory.getLogger(JacksonUtils.class);
private JacksonUtils() { private JacksonUtils() {
} }
/** /**
@ -84,5 +83,4 @@ public final class JacksonUtils {
throw new RuntimeException("Json to map failed.", e); throw new RuntimeException("Json to map failed.", e);
} }
} }
} }

@ -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) {
@ -48,5 +47,4 @@ public final class ReflectionUtils {
} }
return null; return null;
} }
} }

@ -46,5 +46,4 @@ public final class ResourceFileUtils {
} }
return ""; return "";
} }
} }

@ -54,5 +54,4 @@ public class Person {
public String toString() { public String toString() {
return "User{" + "name='" + name + '\'' + ", age=" + age + '}'; return "User{" + "name='" + name + '\'' + ", age=" + age + '}';
} }
} }

@ -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.
* *
@ -64,8 +65,8 @@ public class GatewayCalleeController {
@RequestMapping("/echo") @RequestMapping("/echo")
public String echoHeader(@RequestHeader(MetadataConstant.HeaderName.CUSTOM_METADATA) String metadataStr) public String echoHeader(@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.
* *
@ -64,8 +65,8 @@ public class GatewayCalleeController {
@RequestMapping("/echo") @RequestMapping("/echo")
public String echoHeader(@RequestHeader(MetadataConstant.HeaderName.CUSTOM_METADATA) String metadataStr) public String echoHeader(@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);
} }
} }

@ -29,7 +29,7 @@ import org.springframework.context.annotation.Configuration;
* Post-initialization operations after the application initialization phase is completed. * Post-initialization operations after the application initialization phase is completed.
*@author lepdou 2022-06-28 *@author lepdou 2022-06-28
*/ */
@Configuration @Configuration(proxyBeanMethods = false)
public class PolarisContextPostConfiguration { public class PolarisContextPostConfiguration {
@Bean @Bean

@ -132,5 +132,4 @@ public class PolarisContextProperties {
public void setService(String service) { public void setService(String service) {
this.service = service; this.service = service;
} }
} }

@ -53,7 +53,7 @@ import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
*/ */
public class PolarisLoadBalancer extends RoundRobinLoadBalancer { public class PolarisLoadBalancer extends RoundRobinLoadBalancer {
private static final Logger log = LoggerFactory.getLogger(PolarisLoadBalancer.class); private static final Logger LOGGER = LoggerFactory.getLogger(PolarisLoadBalancer.class);
private final String serviceId; private final String serviceId;
@ -61,7 +61,7 @@ public class PolarisLoadBalancer extends RoundRobinLoadBalancer {
private final RouterAPI routerAPI; private final RouterAPI routerAPI;
private ObjectProvider<ServiceInstanceListSupplier> supplierObjectProvider; private final ObjectProvider<ServiceInstanceListSupplier> supplierObjectProvider;
public PolarisLoadBalancer(String serviceId, ObjectProvider<ServiceInstanceListSupplier> supplierObjectProvider, public PolarisLoadBalancer(String serviceId, ObjectProvider<ServiceInstanceListSupplier> supplierObjectProvider,
PolarisLoadBalancerProperties loadBalancerProperties, RouterAPI routerAPI) { PolarisLoadBalancerProperties loadBalancerProperties, RouterAPI routerAPI) {
@ -92,7 +92,7 @@ public class PolarisLoadBalancer extends RoundRobinLoadBalancer {
private Response<ServiceInstance> getInstanceResponse(List<ServiceInstance> serviceInstances) { private Response<ServiceInstance> getInstanceResponse(List<ServiceInstance> serviceInstances) {
if (serviceInstances.isEmpty()) { if (serviceInstances.isEmpty()) {
log.warn("No servers available for service: " + this.serviceId); LOGGER.warn("No servers available for service: " + this.serviceId);
return new EmptyResponse(); return new EmptyResponse();
} }
@ -106,9 +106,8 @@ public class PolarisLoadBalancer extends RoundRobinLoadBalancer {
return new DefaultResponse(new PolarisServiceInstance(response.getTargetInstance())); return new DefaultResponse(new PolarisServiceInstance(response.getTargetInstance()));
} }
catch (Exception e) { catch (Exception e) {
log.warn("PolarisRoutingLoadbalancer error", e); LOGGER.warn("PolarisRoutingLoadbalancer error", e);
return new EmptyResponse(); return new EmptyResponse();
} }
} }
} }

@ -67,10 +67,10 @@ public class PolarisLoadBalancerClientConfiguration {
loadBalancerProperties, routerAPI); loadBalancerProperties, routerAPI);
} }
@Configuration @Configuration(proxyBeanMethods = false)
@ConditionalOnReactiveDiscoveryEnabled @ConditionalOnReactiveDiscoveryEnabled
@Order(REACTIVE_SERVICE_INSTANCE_SUPPLIER_ORDER) @Order(REACTIVE_SERVICE_INSTANCE_SUPPLIER_ORDER)
static class PolarisReactiveSupportConfiguration { protected static class PolarisReactiveSupportConfiguration {
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
@ -84,10 +84,10 @@ public class PolarisLoadBalancerClientConfiguration {
} }
@Configuration @Configuration(proxyBeanMethods = false)
@ConditionalOnBlockingDiscoveryEnabled @ConditionalOnBlockingDiscoveryEnabled
@Order(REACTIVE_SERVICE_INSTANCE_SUPPLIER_ORDER + 1) @Order(REACTIVE_SERVICE_INSTANCE_SUPPLIER_ORDER + 1)
static class PolarisBlockingSupportConfiguration { protected static class PolarisBlockingSupportConfiguration {
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
@ -98,7 +98,5 @@ public class PolarisLoadBalancerClientConfiguration {
return new PolarisServiceInstanceListSupplier( return new PolarisServiceInstanceListSupplier(
ServiceInstanceListSupplier.builder().withBlockingDiscoveryClient().build(context)); ServiceInstanceListSupplier.builder().withBlockingDiscoveryClient().build(context));
} }
} }
} }

@ -73,5 +73,4 @@ public class PolarisLoadBalancerProperties {
return "PolarisLoadBalancerProperties{" + "loadbalancerEnabled=" + enabled + ", strategy='" + strategy + '\'' return "PolarisLoadBalancerProperties{" + "loadbalancerEnabled=" + enabled + ", strategy='" + strategy + '\''
+ '}'; + '}';
} }
} }

@ -37,7 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat;
*/ */
public class PolarisLoadBalancerAutoConfigurationTest { public class PolarisLoadBalancerAutoConfigurationTest {
private ApplicationContextRunner contextRunner = new ApplicationContextRunner() private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(PolarisRibbonTest.class, .withConfiguration(AutoConfigurations.of(PolarisRibbonTest.class,
PolarisLoadBalancerAutoConfiguration.class, PolarisContextAutoConfiguration.class)) PolarisLoadBalancerAutoConfiguration.class, PolarisContextAutoConfiguration.class))
.withPropertyValues("spring.application.name=" + SERVICE_PROVIDER).withPropertyValues("server.port=" + PORT) .withPropertyValues("spring.application.name=" + SERVICE_PROVIDER).withPropertyValues("server.port=" + PORT)

@ -84,5 +84,4 @@ public class PolarisRouterAutoConfigurationTest {
static class PolarisLoadBalancerTest { static class PolarisLoadBalancerTest {
} }
} }

Loading…
Cancel
Save