Optimize starter's auto-configuration . (2020) (#395)

pull/399/merge
VOPEN.XYZ 3 years ago committed by GitHub
parent 9dd33db2ef
commit efe9e70fba
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -26,9 +26,10 @@
- [Use jdk constants instead of magic variables](https://github.com/Tencent/spring-cloud-tencent/pull/362)
- [Refator JacksonUtils and JacksonUtilsTest](https://github.com/Tencent/spring-cloud-tencent/pull/366)
- [Feature: support actuator for sct core components](https://github.com/Tencent/spring-cloud-tencent/pull/370)
- [docs: Fix javadoc <br /> error](https://github.com/Tencent/spring-cloud-tencent/pull/375)
- [docs: Fix javadoc <br \/> error](https://github.com/Tencent/spring-cloud-tencent/pull/375)
- [docs: Update Readme.md](https://github.com/Tencent/spring-cloud-tencent/pull/381)
- [docs:optimize example](https://github.com/Tencent/spring-cloud-tencent/pull/386)
- [Feature: support spring cloud gateway routers](https://github.com/Tencent/spring-cloud-tencent/pull/388)
- [Optimize:optimize load balancer code and add testcase](https://github.com/Tencent/spring-cloud-tencent/pull/379)
- [refactor:optimize project and code](https://github.com/Tencent/spring-cloud-tencent/pull/392)
- [Optimize starter's auto-configuration](https://github.com/Tencent/spring-cloud-tencent/pull/395)

@ -39,6 +39,7 @@ import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.lang.NonNull;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;
@ -53,15 +54,15 @@ import static javax.servlet.DispatcherType.REQUEST;
*
* @author Haotian Zhang
*/
@Configuration
@Configuration(proxyBeanMethods = false)
public class MetadataTransferAutoConfiguration {
/**
* Create when web application type is SERVLET.
*/
@Configuration
@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
static class MetadataServletFilterConfig {
protected static class MetadataServletFilterConfig {
@Bean
public FilterRegistrationBean<DecodeTransferMetadataServletFilter> metadataServletFilterRegistrationBean(
@ -84,9 +85,9 @@ public class MetadataTransferAutoConfiguration {
/**
* Create when web application type is REACTIVE.
*/
@Configuration
@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
static class MetadataReactiveFilterConfig {
protected static class MetadataReactiveFilterConfig {
@Bean
public DecodeTransferMetadataReactiveFilter metadataReactiveFilter() {
@ -97,9 +98,9 @@ public class MetadataTransferAutoConfiguration {
/**
* Create when gateway application is SCG.
*/
@Configuration
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(name = "org.springframework.cloud.gateway.filter.GlobalFilter")
static class MetadataTransferScgFilterConfig {
protected static class MetadataTransferScgFilterConfig {
@Bean
public GlobalFilter encodeTransferMedataScgFilter() {
@ -111,9 +112,9 @@ public class MetadataTransferAutoConfiguration {
/**
* Create when Feign exists.
*/
@Configuration
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(name = "feign.Feign")
static class MetadataTransferFeignInterceptorConfig {
protected static class MetadataTransferFeignInterceptorConfig {
@Bean
public EncodeTransferMedataFeignInterceptor encodeTransferMedataFeignInterceptor() {
@ -124,9 +125,9 @@ public class MetadataTransferAutoConfiguration {
/**
* Create when RestTemplate exists.
*/
@Configuration
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(name = "org.springframework.web.client.RestTemplate")
static class MetadataTransferRestTemplateConfig implements ApplicationContextAware {
protected static class MetadataTransferRestTemplateConfig implements ApplicationContextAware {
private ApplicationContext context;
@ -160,7 +161,7 @@ public class MetadataTransferAutoConfiguration {
}
@Override
public void setApplicationContext(ApplicationContext applicationContext)
public void setApplicationContext(@NonNull ApplicationContext applicationContext)
throws BeansException {
this.context = applicationContext;
}
@ -168,7 +169,7 @@ public class MetadataTransferAutoConfiguration {
public static class EncodeTransferMetadataRestTemplatePostProcessor
implements BeanPostProcessor {
private EncodeTransferMedataRestTemplateInterceptor encodeTransferMedataRestTemplateInterceptor;
private final EncodeTransferMedataRestTemplateInterceptor encodeTransferMedataRestTemplateInterceptor;
EncodeTransferMetadataRestTemplatePostProcessor(
EncodeTransferMedataRestTemplateInterceptor encodeTransferMedataRestTemplateInterceptor) {
@ -176,12 +177,12 @@ public class MetadataTransferAutoConfiguration {
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) {
public Object postProcessBeforeInitialization(@NonNull Object bean, @NonNull String beanName) {
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
public Object postProcessAfterInitialization(@NonNull Object bean, @NonNull String beanName) {
if (bean instanceof RestTemplate) {
RestTemplate restTemplate = (RestTemplate) bean;
List<ClientHttpRequestInterceptor> interceptors = restTemplate

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

@ -21,7 +21,6 @@ package com.tencent.cloud.metadata.core;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
@ -40,6 +39,8 @@ import org.springframework.core.annotation.Order;
import org.springframework.util.StringUtils;
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
* SERVLET.
@ -77,7 +78,7 @@ public class DecodeTransferMetadataServletFilter extends OncePerRequestFilter {
String customMetadataStr = httpServletRequest.getHeader(MetadataConstant.HeaderName.CUSTOM_METADATA);
try {
if (StringUtils.hasText(customMetadataStr)) {
customMetadataStr = URLDecoder.decode(customMetadataStr, StandardCharsets.UTF_8.name());
customMetadataStr = URLDecoder.decode(customMetadataStr, UTF_8);
}
}
catch (UnsupportedEncodingException e) {

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

@ -21,7 +21,6 @@ package com.tencent.cloud.metadata.core;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;
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.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
* is RestTemplate.
@ -60,7 +61,7 @@ public class EncodeTransferMedataRestTemplateInterceptor implements ClientHttpRe
String encodedTransitiveMetadata = JacksonUtils.serialize2Json(customMetadata);
try {
httpRequest.getHeaders().set(MetadataConstant.HeaderName.CUSTOM_METADATA,
URLEncoder.encode(encodedTransitiveMetadata, StandardCharsets.UTF_8.name()));
URLEncoder.encode(encodedTransitiveMetadata, UTF_8));
}
catch (UnsupportedEncodingException e) {
httpRequest.getHeaders().set(MetadataConstant.HeaderName.CUSTOM_METADATA, encodedTransitiveMetadata);

@ -20,7 +20,6 @@ package com.tencent.cloud.metadata.core;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;
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.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;
/**
@ -68,8 +68,7 @@ public class EncodeTransferMedataScgFilter implements GlobalFilter, Ordered {
if (!CollectionUtils.isEmpty(customMetadata)) {
String metadataStr = JacksonUtils.serialize2Json(customMetadata);
try {
builder.header(MetadataConstant.HeaderName.CUSTOM_METADATA,
URLEncoder.encode(metadataStr, StandardCharsets.UTF_8.name()));
builder.header(MetadataConstant.HeaderName.CUSTOM_METADATA, URLEncoder.encode(metadataStr, UTF_8));
}
catch (UnsupportedEncodingException e) {
builder.header(MetadataConstant.HeaderName.CUSTOM_METADATA, metadataStr);

@ -19,7 +19,6 @@ package com.tencent.cloud.metadata.core;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;
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.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;
/**
@ -71,7 +71,7 @@ public class EncodeTransferMedataScgFilterTest {
String metadata = exchange.getRequest().getHeaders().getFirst(MetadataConstant.HeaderName.CUSTOM_METADATA);
Assertions.assertThat(metadata).isNotNull();
String decode = URLDecoder.decode(metadata, StandardCharsets.UTF_8.name());
String decode = URLDecoder.decode(metadata, UTF_8);
Map<String, String> transitiveMap = JacksonUtils.deserialize2Map(decode);
Assertions.assertThat(transitiveMap.size()).isEqualTo(1);
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,10 @@ import org.springframework.context.annotation.Configuration;
*
* @author lepdou 2022-03-29
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnPolarisEnabled
@ConditionalOnProperty(value = "spring.cloud.polaris.circuitbreaker.enabled", havingValue = "true",
matchIfMissing = true)
@Configuration(proxyBeanMethods = false)
public class PolarisCircuitBreakerBootstrapConfiguration {
@Bean
@ -66,6 +66,5 @@ public class PolarisCircuitBreakerBootstrapConfiguration {
public int getOrder() {
return ContextConstant.ModifierOrder.CIRCUIT_BREAKER_ORDER;
}
}
}

@ -1,60 +0,0 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.tencent.cloud.polaris.circuitbreaker.config;
import com.tencent.cloud.polaris.circuitbreaker.feign.PolarisFeignBeanPostProcessor;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import com.tencent.polaris.api.core.ConsumerAPI;
import com.tencent.polaris.client.api.SDKContext;
import com.tencent.polaris.factory.api.DiscoveryAPIFactory;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.openfeign.FeignAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import static org.springframework.core.Ordered.HIGHEST_PRECEDENCE;
/**
* Configuration for Polaris {@link feign.Feign} which can automatically bring in the call
* results for reporting.
*
* @author Haotian Zhang
*/
@ConditionalOnProperty(value = "spring.cloud.polaris.circuitbreaker.enabled", havingValue = "true", matchIfMissing = true)
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(name = "org.springframework.cloud.openfeign.FeignAutoConfiguration")
@AutoConfigureAfter(PolarisContextAutoConfiguration.class)
@AutoConfigureBefore(FeignAutoConfiguration.class)
public class PolarisFeignClientAutoConfiguration {
@Bean
public ConsumerAPI consumerAPI(SDKContext context) {
return DiscoveryAPIFactory.createConsumerAPIByContext(context);
}
@Bean
@Order(HIGHEST_PRECEDENCE)
public PolarisFeignBeanPostProcessor polarisFeignBeanPostProcessor(ConsumerAPI consumerAPI) {
return new PolarisFeignBeanPostProcessor(consumerAPI);
}
}

@ -1,58 +0,0 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.tencent.cloud.polaris.circuitbreaker.config;
import com.tencent.cloud.polaris.circuitbreaker.resttemplate.PolarisResponseErrorHandler;
import com.tencent.cloud.polaris.circuitbreaker.resttemplate.PolarisRestTemplateModifier;
import com.tencent.cloud.polaris.circuitbreaker.resttemplate.PolarisRestTemplateResponseErrorHandler;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import com.tencent.polaris.api.core.ConsumerAPI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
/**
* Auto configuration PolarisRestTemplateAutoConfiguration.
*
* @author wh 2022/6/21
*/
@ConditionalOnProperty(value = "spring.cloud.polaris.circuitbreaker.enabled",
havingValue = "true", matchIfMissing = true)
@Configuration(proxyBeanMethods = false)
@AutoConfigureAfter(PolarisContextAutoConfiguration.class)
public class PolarisRestTemplateAutoConfiguration {
@Bean
@ConditionalOnBean(RestTemplate.class)
public PolarisRestTemplateResponseErrorHandler polarisRestTemplateResponseErrorHandler(
ConsumerAPI consumerAPI, @Autowired(required = false) PolarisResponseErrorHandler polarisResponseErrorHandler) {
return new PolarisRestTemplateResponseErrorHandler(consumerAPI, polarisResponseErrorHandler);
}
@Bean
@ConditionalOnBean(RestTemplate.class)
public PolarisRestTemplateModifier polarisRestTemplateBeanPostProcessor(
PolarisRestTemplateResponseErrorHandler restTemplateResponseErrorHandler) {
return new PolarisRestTemplateModifier(restTemplateResponseErrorHandler);
}
}

@ -29,6 +29,7 @@ import org.springframework.cloud.loadbalancer.blocking.client.BlockingLoadBalanc
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.cloud.openfeign.loadbalancer.FeignBlockingLoadBalancerClient;
import org.springframework.cloud.openfeign.loadbalancer.RetryableFeignBlockingLoadBalancerClient;
import org.springframework.lang.NonNull;
/**
* Wrap Spring Bean and decorating proxy for Feign Client.
@ -46,7 +47,7 @@ public class PolarisFeignBeanPostProcessor implements BeanPostProcessor, BeanFac
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
public Object postProcessBeforeInitialization(@NonNull Object bean, @NonNull String beanName) throws BeansException {
return wrapper(bean);
}
@ -83,7 +84,7 @@ public class PolarisFeignBeanPostProcessor implements BeanPostProcessor, BeanFac
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
public void setBeanFactory(@NonNull BeanFactory beanFactory) throws BeansException {
this.factory = beanFactory;
}
}

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

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

@ -18,7 +18,7 @@
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.PolarisRestTemplateResponseErrorHandler;
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;
/**
* Test For {@link PolarisRestTemplateAutoConfiguration} .
* Test For {@link PolarisCircuitBreakerAutoConfiguration} .
*
* @author <a href="mailto:iskp.me@gmail.com">Palmer Xu</a> 2022-06-28
*/
@ -45,7 +45,7 @@ public class PolarisRestTemplateAutoConfigurationTest {
.withConfiguration(AutoConfigurations.of(
PolarisRestTemplateAutoConfigurationTester.class,
PolarisContextAutoConfiguration.class,
PolarisRestTemplateAutoConfiguration.class))
PolarisCircuitBreakerAutoConfiguration.class))
.withPropertyValues("spring.cloud.polaris.circuitbreaker.enabled=true");
@Test
@ -59,7 +59,7 @@ public class PolarisRestTemplateAutoConfigurationTest {
@Configuration
@EnableAutoConfiguration
@AutoConfigureBefore(PolarisRestTemplateAutoConfiguration.class)
@AutoConfigureBefore(PolarisCircuitBreakerAutoConfiguration.class)
static class PolarisRestTemplateAutoConfigurationTester {
@Bean

@ -29,12 +29,10 @@ import com.tencent.polaris.configuration.api.core.ConfigPropertyChangeInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.cloud.context.refresh.ContextRefresher;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.lang.NonNull;
import org.springframework.util.CollectionUtils;
/**
@ -43,8 +41,7 @@ import org.springframework.util.CollectionUtils;
*
* @author lepdou 2022-03-28
*/
public class PolarisPropertySourceAutoRefresher
implements ApplicationListener<ApplicationReadyEvent>, ApplicationContextAware {
public class PolarisPropertySourceAutoRefresher implements ApplicationListener<ApplicationReadyEvent> {
private static final Logger LOGGER = LoggerFactory.getLogger(PolarisPropertySourceAutoRefresher.class);
@ -53,7 +50,6 @@ public class PolarisPropertySourceAutoRefresher
private final PolarisPropertySourceManager polarisPropertySourceManager;
private final ContextRefresher contextRefresher;
private final AtomicBoolean registered = new AtomicBoolean(false);
private ApplicationContext applicationContext;
public PolarisPropertySourceAutoRefresher(PolarisConfigProperties polarisConfigProperties,
PolarisPropertySourceManager polarisPropertySourceManager, ContextRefresher contextRefresher) {
@ -63,12 +59,7 @@ public class PolarisPropertySourceAutoRefresher
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
public void onApplicationEvent(@NonNull ApplicationReadyEvent event) {
registerPolarisConfigPublishEvent();
}

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

@ -17,8 +17,6 @@
*/
package com.tencent.cloud.polaris;
import javax.annotation.PostConstruct;
import com.tencent.cloud.polaris.context.ConditionalOnPolarisEnabled;
import com.tencent.cloud.polaris.discovery.PolarisDiscoveryHandler;
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.factory.api.DiscoveryAPIFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@ -44,16 +41,6 @@ import org.springframework.context.annotation.Import;
@Import({PolarisDiscoveryProperties.class, ConsulContextProperties.class})
public class DiscoveryPropertiesAutoConfiguration {
@Autowired(required = false)
private PolarisDiscoveryProperties polarisDiscoveryProperties;
@Autowired(required = false)
private ConsulContextProperties consulContextProperties;
private boolean registerEnabled = false;
private boolean discoveryEnabled = false;
@Bean
@ConditionalOnMissingBean
public ProviderAPI polarisProvider(SDKContext polarisContext) throws PolarisException {
@ -76,24 +63,4 @@ public class DiscoveryPropertiesAutoConfiguration {
public DiscoveryConfigModifier 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.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
/**
* Properties for Polaris.
@ -107,9 +106,6 @@ public class PolarisDiscoveryProperties {
*/
private Long serviceListRefreshInterval = 60000L;
@Autowired
private Environment environment;
public boolean isHeartbeatEnabled() {
return heartbeatEnabled;
}
@ -232,7 +228,7 @@ public class PolarisDiscoveryProperties {
private static class PolarisDiscoveryConfigModifier implements PolarisConfigModifier {
private final String ID = "polaris";
private static final String ID = "polaris";
@Autowired(required = false)
private PolarisDiscoveryProperties polarisDiscoveryProperties;

@ -31,6 +31,7 @@ import org.springframework.cloud.client.discovery.event.HeartbeatEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.context.ApplicationListener;
import org.springframework.lang.NonNull;
import static com.tencent.cloud.polaris.discovery.refresh.PolarisServiceStatusChangeListener.INDEX;
@ -82,7 +83,7 @@ public class PolarisRefreshApplicationReadyEventListener
}
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
public void setApplicationEventPublisher(@NonNull ApplicationEventPublisher applicationEventPublisher) {
this.publisher = applicationEventPublisher;
}

@ -32,6 +32,7 @@ import org.slf4j.LoggerFactory;
import org.springframework.cloud.client.discovery.event.HeartbeatEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.lang.NonNull;
import org.springframework.util.CollectionUtils;
/**
@ -91,7 +92,7 @@ public class PolarisServiceStatusChangeListener extends AbstractResourceEventLis
}
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
public void setApplicationEventPublisher(@NonNull ApplicationEventPublisher applicationEventPublisher) {
this.publisher = applicationEventPublisher;
}
}

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

@ -24,14 +24,15 @@ import java.util.HashMap;
import java.util.Map;
import com.tencent.cloud.common.metadata.StaticMetadataManager;
import com.tencent.cloud.polaris.DiscoveryPropertiesAutoConfiguration;
import com.tencent.cloud.polaris.PolarisDiscoveryProperties;
import com.tencent.cloud.polaris.extend.consul.ConsulContextProperties;
import com.tencent.polaris.client.api.SDKContext;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.client.DefaultServiceInstance;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.lang.Nullable;
import org.springframework.util.CollectionUtils;
/**
@ -41,13 +42,13 @@ import org.springframework.util.CollectionUtils;
*/
public class PolarisRegistration implements Registration, ServiceInstance {
private final static String METADATA_KEY_IP = "internal-ip";
private final static String METADATA_KEY_ADDRESS = "internal-address";
private final DiscoveryPropertiesAutoConfiguration discoveryPropertiesAutoConfiguration;
private static final String METADATA_KEY_IP = "internal-ip";
private static final String METADATA_KEY_ADDRESS = "internal-address";
private final PolarisDiscoveryProperties polarisDiscoveryProperties;
private final ConsulContextProperties consulContextProperties;
private final SDKContext polarisContext;
private final StaticMetadataManager staticMetadataManager;
@ -57,11 +58,11 @@ public class PolarisRegistration implements Registration, ServiceInstance {
private final String host;
public PolarisRegistration(
DiscoveryPropertiesAutoConfiguration discoveryPropertiesAutoConfiguration,
PolarisDiscoveryProperties polarisDiscoveryProperties, SDKContext context,
StaticMetadataManager staticMetadataManager) {
this.discoveryPropertiesAutoConfiguration = discoveryPropertiesAutoConfiguration;
PolarisDiscoveryProperties polarisDiscoveryProperties,
@Nullable ConsulContextProperties consulContextProperties,
SDKContext context, StaticMetadataManager staticMetadataManager) {
this.polarisDiscoveryProperties = polarisDiscoveryProperties;
this.consulContextProperties = consulContextProperties;
this.polarisContext = context;
this.staticMetadataManager = staticMetadataManager;
@ -121,14 +122,23 @@ public class PolarisRegistration implements Registration, ServiceInstance {
}
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
public String toString() {
return "PolarisRegistration{" +
"discoveryPropertiesAutoConfiguration=" + discoveryPropertiesAutoConfiguration +
", polarisDiscoveryProperties=" + polarisDiscoveryProperties +
"polarisDiscoveryProperties=" + polarisDiscoveryProperties +
", polarisContext=" + polarisContext +
", staticMetadataManager=" + staticMetadataManager +
", metadata=" + metadata +

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

@ -65,9 +65,6 @@ public class DiscoveryPropertiesAutoConfigurationTest {
.withPropertyValues("spring.cloud.consul.discovery.enabled=false");
applicationContextRunner.run(context -> {
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 com.tencent.cloud.common.metadata.StaticMetadataManager;
import com.tencent.cloud.polaris.DiscoveryPropertiesAutoConfiguration;
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.global.APIConfig;
import com.tencent.polaris.api.config.global.GlobalConfig;
@ -51,16 +51,15 @@ public class PolarisRegistrationTest {
@Before
public void setUp() {
// mock DiscoveryPropertiesAutoConfiguration
DiscoveryPropertiesAutoConfiguration discoveryPropertiesAutoConfiguration =
mock(DiscoveryPropertiesAutoConfiguration.class);
doReturn(true).when(discoveryPropertiesAutoConfiguration).isRegisterEnabled();
// mock PolarisDiscoveryProperties
PolarisDiscoveryProperties polarisDiscoveryProperties = mock(PolarisDiscoveryProperties.class);
doReturn(SERVICE_PROVIDER).when(polarisDiscoveryProperties).getService();
doReturn(PORT).when(polarisDiscoveryProperties).getPort();
doReturn("http").when(polarisDiscoveryProperties).getProtocol();
doReturn(true).when(polarisDiscoveryProperties).isRegisterEnabled();
// mock
ConsulContextProperties consulContextProperties = mock(ConsulContextProperties.class);
// mock SDKContext
APIConfig apiConfig = mock(APIConfig.class);
@ -77,8 +76,8 @@ public class PolarisRegistrationTest {
doReturn(Collections.singletonMap("key1", "value1")).when(staticMetadataManager).getMergedStaticMetadata();
doReturn(Collections.singletonMap("key2", "value2")).when(staticMetadataManager).getLocationMetadata();
polarisRegistration = new PolarisRegistration(
discoveryPropertiesAutoConfiguration, polarisDiscoveryProperties, polarisContext, staticMetadataManager);
polarisRegistration = new PolarisRegistration(polarisDiscoveryProperties, consulContextProperties,
polarisContext, staticMetadataManager);
}
@Test

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

@ -60,6 +60,11 @@ public class QuotaCheckServletFilter extends OncePerRequestFilter {
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 PolarisRateLimiterLabelServletResolver labelResolver;

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

@ -19,7 +19,6 @@ package com.tencent.cloud.polaris.router;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
@ -58,6 +57,8 @@ import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import org.springframework.http.HttpHeaders;
import org.springframework.util.CollectionUtils;
import static com.tencent.cloud.common.constant.ContextConstant.UTF_8;
/**
* Service routing entrance.
*
@ -128,10 +129,10 @@ public class PolarisRouterServiceInstanceListSupplier extends DelegatingServiceI
Map<String, String> labelHeaderValuesMap = new HashMap<>();
try {
String labelHeaderValuesContent = labelHeaderValues.stream().findFirst().get();
labelHeaderValuesMap.putAll(JacksonUtils.deserialize2Map(URLDecoder.decode(labelHeaderValuesContent, StandardCharsets.UTF_8.name())));
labelHeaderValuesMap.putAll(JacksonUtils.deserialize2Map(URLDecoder.decode(labelHeaderValuesContent, UTF_8)));
}
catch (UnsupportedEncodingException e) {
throw new RuntimeException("unsupported charset exception " + StandardCharsets.UTF_8.name());
throw new RuntimeException("unsupported charset exception " + UTF_8);
}
routerContext.setLabels(PolarisRouterContext.RULE_ROUTER_LABELS, labelHeaderValuesMap);
return routerContext;

@ -30,7 +30,7 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.Nullable;
@Configuration
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(name = {"feign.RequestInterceptor"})
public class FeignAutoConfiguration {

@ -47,7 +47,7 @@ public class LoadBalancerConfiguration {
*/
private static final int REACTIVE_SERVICE_INSTANCE_SUPPLIER_ORDER = 193827465;
@Configuration
@Configuration(proxyBeanMethods = false)
@ConditionalOnReactiveDiscoveryEnabled
@Order(REACTIVE_SERVICE_INSTANCE_SUPPLIER_ORDER)
static class PolarisReactiveSupportConfiguration {
@ -70,7 +70,7 @@ public class LoadBalancerConfiguration {
}
@Configuration
@Configuration(proxyBeanMethods = false)
@ConditionalOnBlockingDiscoveryEnabled
@Order(REACTIVE_SERVICE_INSTANCE_SUPPLIER_ORDER + 1)
static class PolarisBlockingSupportConfiguration {

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

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

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

@ -22,7 +22,6 @@ import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
@ -51,6 +50,8 @@ import org.springframework.http.client.ClientHttpResponse;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import static com.tencent.cloud.common.constant.ContextConstant.UTF_8;
/**
* PolarisLoadBalancerInterceptor extends LoadBalancerInterceptor capabilities.
* Parses the label from the request and puts it into the RouterContext for routing.
@ -136,10 +137,10 @@ public class PolarisLoadBalancerInterceptor extends LoadBalancerInterceptor {
}
String encodedLabelsContent;
try {
encodedLabelsContent = URLEncoder.encode(JacksonUtils.serialize2Json(labels), StandardCharsets.UTF_8.name());
encodedLabelsContent = URLEncoder.encode(JacksonUtils.serialize2Json(labels), UTF_8);
}
catch (UnsupportedEncodingException e) {
throw new RuntimeException("unsupported charset exception " + StandardCharsets.UTF_8.name());
throw new RuntimeException("unsupported charset exception " + UTF_8);
}
request.getHeaders().set(RouterConstants.ROUTER_LABEL_HEADER, encodedLabelsContent);
}

@ -21,7 +21,6 @@ package com.tencent.cloud.polaris.router.scg;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
@ -66,6 +65,7 @@ import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.CollectionUtils;
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_REQUEST_URL_ATTR;
import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_SCHEME_PREFIX_ATTR;
@ -213,10 +213,10 @@ public class PolarisReactiveLoadBalancerClientFilter extends ReactiveLoadBalance
Map<String, String> routerLabels = genRouterLabels(exchange, peerServiceName);
String encodedLabelsContent;
try {
encodedLabelsContent = URLEncoder.encode(JacksonUtils.serialize2Json(routerLabels), StandardCharsets.UTF_8.name());
encodedLabelsContent = URLEncoder.encode(JacksonUtils.serialize2Json(routerLabels), UTF_8);
}
catch (UnsupportedEncodingException e) {
throw new RuntimeException("unsupported charset exception " + StandardCharsets.UTF_8.name());
throw new RuntimeException("unsupported charset exception " + UTF_8);
}
return encodedLabelsContent;
}

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

@ -20,7 +20,6 @@ package com.tencent.cloud.polaris.router.resttemplate;
import java.net.URI;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
@ -54,6 +53,7 @@ import org.springframework.http.HttpMethod;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpResponse;
import static com.tencent.cloud.common.constant.ContextConstant.UTF_8;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ -187,7 +187,7 @@ public class PolarisLoadBalancerInterceptorTest {
verify(routerLabelResolver).resolve(request, null);
Map<String, String> headers = JacksonUtils.deserialize2Map(URLDecoder.decode(request.getHeaders()
.get(RouterConstants.ROUTER_LABEL_HEADER).get(0), StandardCharsets.UTF_8.name()));
.get(RouterConstants.ROUTER_LABEL_HEADER).get(0), UTF_8));
Assert.assertEquals("v1", headers.get("k1"));
Assert.assertEquals("v22", headers.get("k2"));
Assert.assertEquals("v4", headers.get("k4"));

@ -20,7 +20,6 @@ package com.tencent.cloud.polaris.router.scg;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
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.util.CollectionUtils;
import static com.tencent.cloud.common.constant.ContextConstant.UTF_8;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;
@ -136,7 +136,7 @@ public class PolarisReactiveLoadBalancerClientFilterTest {
List<String> routerHeaders = headers.get(RouterConstants.ROUTER_LABEL_HEADER);
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("zhangsan", routerLabels.get("${http.query.userid}"));
Assert.assertEquals("blue", routerLabels.get("env"));

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

@ -33,7 +33,7 @@ import org.springframework.lang.Nullable;
*
* @author Haotian Zhang
*/
@Configuration
@Configuration(proxyBeanMethods = false)
public class MetadataAutoConfiguration {
/**
@ -54,9 +54,9 @@ public class MetadataAutoConfiguration {
/**
* Create when gateway application is SCG.
*/
@Configuration
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(name = "org.springframework.cloud.gateway.filter.GlobalFilter")
static class MetadataScgFilterConfig {
protected static class MetadataScgFilterConfig {
@Bean
public GlobalFilter metadataFirstScgFilter() {

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

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

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

@ -19,7 +19,6 @@ package com.tencent.cloud.polaris.gateway.example.callee;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import com.tencent.cloud.common.constant.MetadataConstant;
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.RestController;
import static com.tencent.cloud.common.constant.ContextConstant.UTF_8;
/**
* Gateway callee controller.
*
@ -64,8 +65,8 @@ public class GatewayCalleeController {
@RequestMapping("/echo")
public String echoHeader(@RequestHeader(MetadataConstant.HeaderName.CUSTOM_METADATA) String metadataStr)
throws UnsupportedEncodingException {
LOG.info(URLDecoder.decode(metadataStr, StandardCharsets.UTF_8.name()));
return URLDecoder.decode(metadataStr, StandardCharsets.UTF_8.name());
LOG.info(URLDecoder.decode(metadataStr, UTF_8));
return URLDecoder.decode(metadataStr, UTF_8);
}
}

@ -19,7 +19,6 @@ package com.tencent.cloud.polaris.gateway.example.callee;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import com.tencent.cloud.common.constant.MetadataConstant;
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.RestController;
import static com.tencent.cloud.common.constant.ContextConstant.UTF_8;
/**
* Gateway callee controller.
*
@ -64,8 +65,8 @@ public class GatewayCalleeController {
@RequestMapping("/echo")
public String echoHeader(@RequestHeader(MetadataConstant.HeaderName.CUSTOM_METADATA) String metadataStr)
throws UnsupportedEncodingException {
LOG.info(URLDecoder.decode(metadataStr, StandardCharsets.UTF_8.name()));
return URLDecoder.decode(metadataStr, StandardCharsets.UTF_8.name());
LOG.info(URLDecoder.decode(metadataStr, UTF_8));
return URLDecoder.decode(metadataStr, UTF_8);
}
}

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

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

@ -30,7 +30,7 @@ import org.springframework.context.annotation.Configuration;
*
* @author lepdou 2022-06-28
*/
@Configuration
@Configuration(proxyBeanMethods = false)
public class PolarisContextPostConfiguration {
@Bean

@ -67,10 +67,10 @@ public class PolarisLoadBalancerClientConfiguration {
loadBalancerProperties, routerAPI);
}
@Configuration
@Configuration(proxyBeanMethods = false)
@ConditionalOnReactiveDiscoveryEnabled
@Order(REACTIVE_SERVICE_INSTANCE_SUPPLIER_ORDER)
static class PolarisReactiveSupportConfiguration {
protected static class PolarisReactiveSupportConfiguration {
@Bean
@ConditionalOnMissingBean
@ -84,10 +84,10 @@ public class PolarisLoadBalancerClientConfiguration {
}
@Configuration
@Configuration(proxyBeanMethods = false)
@ConditionalOnBlockingDiscoveryEnabled
@Order(REACTIVE_SERVICE_INSTANCE_SUPPLIER_ORDER + 1)
static class PolarisBlockingSupportConfiguration {
protected static class PolarisBlockingSupportConfiguration {
@Bean
@ConditionalOnMissingBean

Loading…
Cancel
Save