refactor:optimize project and code (#368)

* refactor:optimize project and code

* refactor:optimize project and code

* refactor:optimize project and code
pull/385/head
Haotian Zhang 2 years ago committed by GitHub
parent cffdd56f7c
commit e5f7a75e09
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -32,8 +32,7 @@
- [fix: shutdown thread pool before the container closes](https://github.com/Tencent/spring-cloud-tencent/pull/353)
- [docs:update logo in README.](https://github.com/Tencent/spring-cloud-tencent/pull/358)
- [Refator JacksonUtils and JacksonUtilsTest](https://github.com/Tencent/spring-cloud-tencent/pull/365)
- [refactor:optimize project and code.](https://github.com/Tencent/spring-cloud-tencent/pull/368)
- [docs: Fix javadoc <br /> error](https://github.com/Tencent/spring-cloud-tencent/pull/371)
- [UT: add Polaris LoadBalancer unit test](https://github.com/Tencent/spring-cloud-tencent/pull/373)
- [docs:update docs](https://github.com/Tencent/spring-cloud-tencent/pull/378)

@ -0,0 +1,4 @@
# Change Log
---
- [fix not load application.yml bug & fix guava version conflict bug](https://github.com/Tencent/spring-cloud-tencent/pull/284)

@ -68,12 +68,10 @@ public class MetadataTransferAutoConfiguration {
@Bean
public FilterRegistrationBean<DecodeTransferMetadataServletFilter> metadataServletFilterRegistrationBean(
DecodeTransferMetadataServletFilter decodeTransferMetadataServletFilter) {
FilterRegistrationBean<DecodeTransferMetadataServletFilter> filterRegistrationBean = new FilterRegistrationBean<>(
decodeTransferMetadataServletFilter);
filterRegistrationBean.setDispatcherTypes(ASYNC, ERROR, FORWARD, INCLUDE,
REQUEST);
filterRegistrationBean
.setOrder(MetadataConstant.OrderConstant.WEB_FILTER_ORDER);
FilterRegistrationBean<DecodeTransferMetadataServletFilter> filterRegistrationBean =
new FilterRegistrationBean<>(decodeTransferMetadataServletFilter);
filterRegistrationBean.setDispatcherTypes(ASYNC, ERROR, FORWARD, INCLUDE, REQUEST);
filterRegistrationBean.setOrder(MetadataConstant.OrderConstant.WEB_FILTER_ORDER);
return filterRegistrationBean;
}
@ -158,15 +156,13 @@ public class MetadataTransferAutoConfiguration {
BeanPostProcessor encodeTransferMetadataRestTemplatePostProcessor(
EncodeTransferMedataRestTemplateInterceptor encodeTransferMedataRestTemplateInterceptor) {
// Coping with multiple bean injection scenarios
Map<String, RestTemplate> beans = this.context
.getBeansOfType(RestTemplate.class);
Map<String, RestTemplate> beans = this.context.getBeansOfType(RestTemplate.class);
// If the restTemplate has been created when the
// MetadataRestTemplatePostProcessor Bean
// is initialized, then manually set the interceptor.
if (!CollectionUtils.isEmpty(beans)) {
for (RestTemplate restTemplate : beans.values()) {
List<ClientHttpRequestInterceptor> interceptors = restTemplate
.getInterceptors();
List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors();
// Avoid setting interceptor repeatedly.
if (!interceptors.contains(encodeTransferMedataRestTemplateInterceptor)) {
interceptors.add(encodeTransferMedataRestTemplateInterceptor);
@ -174,13 +170,11 @@ public class MetadataTransferAutoConfiguration {
}
}
}
return new EncodeTransferMetadataRestTemplatePostProcessor(
encodeTransferMedataRestTemplateInterceptor);
return new EncodeTransferMetadataRestTemplatePostProcessor(encodeTransferMedataRestTemplateInterceptor);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.context = applicationContext;
}
@ -203,8 +197,7 @@ public class MetadataTransferAutoConfiguration {
public Object postProcessAfterInitialization(Object bean, String beanName) {
if (bean instanceof RestTemplate) {
RestTemplate restTemplate = (RestTemplate) bean;
List<ClientHttpRequestInterceptor> interceptors = restTemplate
.getInterceptors();
List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors();
// Avoid setting interceptor repeatedly.
if (!interceptors.contains(encodeTransferMedataRestTemplateInterceptor)) {
interceptors.add(this.encodeTransferMedataRestTemplateInterceptor);
@ -213,9 +206,6 @@ public class MetadataTransferAutoConfiguration {
}
return bean;
}
}
}
}

@ -33,12 +33,15 @@ import org.springframework.web.server.ServerWebExchange;
/**
* Resolve custom transitive metadata from request.
*
* @author lepdou 2022-05-20
*/
public class CustomTransitiveMetadataResolver {
public final class CustomTransitiveMetadataResolver {
private static final String TRANSITIVE_HEADER_PREFIX = "X-SCT-Metadata-Transitive-";
private static final int TRANSITIVE_HEADER_PREFIX_LENGTH = TRANSITIVE_HEADER_PREFIX.length();
private CustomTransitiveMetadataResolver() {
}
public static Map<String, String> resolve(ServerWebExchange exchange) {
Map<String, String> result = new HashMap<>();
@ -46,11 +49,9 @@ public class CustomTransitiveMetadataResolver {
HttpHeaders headers = exchange.getRequest().getHeaders();
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
String key = entry.getKey();
if (StringUtils.isNotBlank(key) &&
StringUtils.startsWithIgnoreCase(key, TRANSITIVE_HEADER_PREFIX)
if (StringUtils.isNotBlank(key)
&& StringUtils.startsWithIgnoreCase(key, TRANSITIVE_HEADER_PREFIX)
&& !CollectionUtils.isEmpty(entry.getValue())) {
String sourceKey = StringUtils.substring(key, TRANSITIVE_HEADER_PREFIX_LENGTH);
result.put(sourceKey, entry.getValue().get(0));
}
@ -66,10 +67,9 @@ public class CustomTransitiveMetadataResolver {
while (headers.hasMoreElements()) {
String key = headers.nextElement();
if (StringUtils.isNotBlank(key) &&
StringUtils.startsWithIgnoreCase(key, TRANSITIVE_HEADER_PREFIX)
if (StringUtils.isNotBlank(key)
&& StringUtils.startsWithIgnoreCase(key, TRANSITIVE_HEADER_PREFIX)
&& StringUtils.isNotBlank(request.getHeader(key))) {
String sourceKey = StringUtils.substring(key, TRANSITIVE_HEADER_PREFIX_LENGTH);
result.put(sourceKey, request.getHeader(key));
}

@ -47,8 +47,7 @@ import org.springframework.web.server.WebFilterChain;
*/
public class DecodeTransferMetadataReactiveFilter implements WebFilter, Ordered {
private static final Logger LOG = LoggerFactory
.getLogger(DecodeTransferMetadataReactiveFilter.class);
private static final Logger LOG = LoggerFactory.getLogger(DecodeTransferMetadataReactiveFilter.class);
@Override
public int getOrder() {

@ -49,8 +49,7 @@ import org.springframework.web.filter.OncePerRequestFilter;
@Order(MetadataConstant.OrderConstant.WEB_FILTER_ORDER)
public class DecodeTransferMetadataServletFilter extends OncePerRequestFilter {
private static final Logger LOG = LoggerFactory
.getLogger(DecodeTransferMetadataServletFilter.class);
private static final Logger LOG = LoggerFactory.getLogger(DecodeTransferMetadataServletFilter.class);
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest,
@ -75,8 +74,7 @@ public class DecodeTransferMetadataServletFilter extends OncePerRequestFilter {
private Map<String, String> getInternalTransitiveMetadata(HttpServletRequest httpServletRequest) {
// Get custom metadata string from http header.
String customMetadataStr = httpServletRequest
.getHeader(MetadataConstant.HeaderName.CUSTOM_METADATA);
String customMetadataStr = httpServletRequest.getHeader(MetadataConstant.HeaderName.CUSTOM_METADATA);
try {
if (StringUtils.hasText(customMetadataStr)) {
customMetadataStr = URLDecoder.decode(customMetadataStr, StandardCharsets.UTF_8.name());
@ -90,5 +88,4 @@ public class DecodeTransferMetadataServletFilter extends OncePerRequestFilter {
// create custom metadata.
return JacksonUtils.deserialize2Map(customMetadataStr);
}
}

@ -45,8 +45,7 @@ import static com.tencent.cloud.common.constant.MetadataConstant.HeaderName.CUST
*/
public class EncodeTransferMedataFeignInterceptor implements RequestInterceptor, Ordered {
private static final Logger LOG = LoggerFactory
.getLogger(EncodeTransferMedataFeignInterceptor.class);
private static final Logger LOG = LoggerFactory.getLogger(EncodeTransferMedataFeignInterceptor.class);
@Override
public int getOrder() {

@ -42,8 +42,7 @@ import org.springframework.util.CollectionUtils;
*
* @author Haotian Zhang
*/
public class EncodeTransferMedataRestTemplateInterceptor
implements ClientHttpRequestInterceptor, Ordered {
public class EncodeTransferMedataRestTemplateInterceptor implements ClientHttpRequestInterceptor, Ordered {
@Override
public int getOrder() {
@ -71,5 +70,4 @@ public class EncodeTransferMedataRestTemplateInterceptor
return clientHttpRequestExecution.execute(httpRequest, bytes);
}
}

@ -45,8 +45,7 @@ import static org.springframework.cloud.gateway.filter.LoadBalancerClientFilter.
*/
public class EncodeTransferMedataScgFilter implements GlobalFilter, Ordered {
private static final int METADATA_SCG_FILTER_ORDER = LOAD_BALANCER_CLIENT_FILTER_ORDER
+ 1;
private static final int METADATA_SCG_FILTER_ORDER = LOAD_BALANCER_CLIENT_FILTER_ORDER + 1;
@Override
public int getOrder() {
@ -59,8 +58,7 @@ public class EncodeTransferMedataScgFilter implements GlobalFilter, Ordered {
ServerHttpRequest.Builder builder = exchange.getRequest().mutate();
// get metadata of current thread
MetadataContext metadataContext = exchange
.getAttribute(MetadataConstant.HeaderName.METADATA_CONTEXT);
MetadataContext metadataContext = exchange.getAttribute(MetadataConstant.HeaderName.METADATA_CONTEXT);
// add new metadata and cover old
if (metadataContext == null) {
@ -80,5 +78,4 @@ public class EncodeTransferMedataScgFilter implements GlobalFilter, Ordered {
return chain.filter(exchange.mutate().request(builder.build()).build());
}
}

@ -70,13 +70,11 @@ public class EncodeTransferMetadataZuulFilter extends ZuulFilter {
if (!CollectionUtils.isEmpty(customMetadata)) {
String metadataStr = JacksonUtils.serialize2Json(customMetadata);
try {
requestContext.addZuulRequestHeader(
MetadataConstant.HeaderName.CUSTOM_METADATA,
requestContext.addZuulRequestHeader(MetadataConstant.HeaderName.CUSTOM_METADATA,
URLEncoder.encode(metadataStr, StandardCharsets.UTF_8.name()));
}
catch (UnsupportedEncodingException e) {
requestContext.addZuulRequestHeader(
MetadataConstant.HeaderName.CUSTOM_METADATA, metadataStr);
requestContext.addZuulRequestHeader(MetadataConstant.HeaderName.CUSTOM_METADATA, metadataStr);
}
}
return null;

@ -55,7 +55,9 @@ public class MetadataTransferAutoConfigurationTest {
Assertions.assertThat(context).hasSingleBean(
EncodeTransferMedataRestTemplateInterceptor.class);
Assertions.assertThat(context).hasSingleBean(
MetadataTransferAutoConfiguration.MetadataTransferRestTemplateConfig.EncodeTransferMetadataRestTemplatePostProcessor.class);
MetadataTransferAutoConfiguration
.MetadataTransferRestTemplateConfig
.EncodeTransferMetadataRestTemplatePostProcessor.class);
Assertions.assertThat(context).hasSingleBean(
MetadataTransferAutoConfiguration.MetadataTransferZuulFilterConfig.class);
Assertions.assertThat(context)
@ -65,5 +67,4 @@ public class MetadataTransferAutoConfigurationTest {
Assertions.assertThat(context).hasSingleBean(GlobalFilter.class);
});
}
}

@ -80,5 +80,4 @@ public class DecodeTransferMetadataReactiveFilterTest {
.isEqualTo("2");
Assertions.assertThat(metadataLocalProperties.getContent().get("c")).isNull();
}
}

@ -68,10 +68,8 @@ public class DecodeTransferMetadataServletFilterTest {
request.addHeader(MetadataConstant.HeaderName.CUSTOM_METADATA, "{\"c\": \"3\"}");
MockHttpServletResponse response = new MockHttpServletResponse();
metadataServletFilter.doFilter(request, response, filterChain);
Assertions.assertThat(metadataLocalProperties.getContent().get("a"))
.isEqualTo("1");
Assertions.assertThat(metadataLocalProperties.getContent().get("b"))
.isEqualTo("2");
Assertions.assertThat(metadataLocalProperties.getContent().get("a")).isEqualTo("1");
Assertions.assertThat(metadataLocalProperties.getContent().get("b")).isEqualTo("2");
Assertions.assertThat(metadataLocalProperties.getContent().get("c")).isNull();
}
@ -79,5 +77,4 @@ public class DecodeTransferMetadataServletFilterTest {
protected static class TestApplication {
}
}

@ -36,7 +36,6 @@ import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@ -66,10 +65,8 @@ public class EncodeTransferMedataFeignInterceptorTest {
public void testTransitiveMetadataFromApplicationConfig() {
String metadata = testFeign.test();
Assertions.assertThat(metadata).isEqualTo("2");
Assertions.assertThat(metadataLocalProperties.getContent().get("a"))
.isEqualTo("1");
Assertions.assertThat(metadataLocalProperties.getContent().get("b"))
.isEqualTo("2");
Assertions.assertThat(metadataLocalProperties.getContent().get("a")).isEqualTo("1");
Assertions.assertThat(metadataLocalProperties.getContent().get("b")).isEqualTo("2");
}
@SpringBootApplication
@ -78,9 +75,7 @@ public class EncodeTransferMedataFeignInterceptorTest {
protected static class TestApplication {
@RequestMapping("/test")
public String test(
@RequestHeader(MetadataConstant.HeaderName.CUSTOM_METADATA) String customMetadataStr)
throws UnsupportedEncodingException {
public String test() throws UnsupportedEncodingException {
return MetadataContextHolder.get().getContext(MetadataContext.FRAGMENT_TRANSITIVE, "b");
}
@ -89,7 +84,6 @@ public class EncodeTransferMedataFeignInterceptorTest {
@RequestMapping("/test")
String test();
}
@Configuration
@ -100,9 +94,6 @@ public class EncodeTransferMedataFeignInterceptorTest {
template.header(MetadataConstant.HeaderName.CUSTOM_METADATA,
"{\"a\":\"11\",\"b\":\"22\",\"c\":\"33\"}");
}
}
}
}

@ -19,7 +19,6 @@ package com.tencent.cloud.metadata.core;
import java.io.UnsupportedEncodingException;
import com.tencent.cloud.common.constant.MetadataConstant;
import com.tencent.cloud.common.metadata.MetadataContext;
import com.tencent.cloud.common.metadata.MetadataContextHolder;
import org.assertj.core.api.Assertions;
@ -35,7 +34,6 @@ import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@ -50,7 +48,8 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = RANDOM_PORT,
classes = EncodeTransferMedataRestTemplateInterceptorTest.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 EncodeTransferMedataRestTemplateInterceptorTest {
@Autowired
@ -64,8 +63,7 @@ public class EncodeTransferMedataRestTemplateInterceptorTest {
HttpHeaders httpHeaders = new HttpHeaders();
HttpEntity<String> httpEntity = new HttpEntity<>(httpHeaders);
String metadata = restTemplate
.exchange("http://localhost:" + localServerPort + "/test", HttpMethod.GET,
httpEntity, String.class)
.exchange("http://localhost:" + localServerPort + "/test", HttpMethod.GET, httpEntity, String.class)
.getBody();
Assertions.assertThat(metadata).isEqualTo("2");
}
@ -80,12 +78,8 @@ public class EncodeTransferMedataRestTemplateInterceptorTest {
}
@RequestMapping("/test")
public String test(
@RequestHeader(MetadataConstant.HeaderName.CUSTOM_METADATA) String customMetadataStr)
throws UnsupportedEncodingException {
public String test() throws UnsupportedEncodingException {
return MetadataContextHolder.get().getContext(MetadataContext.FRAGMENT_TRANSITIVE, "b");
}
}
}

@ -48,7 +48,8 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = RANDOM_PORT,
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 {
@Autowired

@ -48,15 +48,14 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = RANDOM_PORT,
classes = EncodeTransferMetadataZuulFilterTest.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 EncodeTransferMetadataZuulFilterTest {
private final MockMultipartHttpServletRequest request = new MockMultipartHttpServletRequest();
@Autowired
private ApplicationContext applicationContext;
private final MockMultipartHttpServletRequest request = new MockMultipartHttpServletRequest();
@Before
public void init() {
RequestContext ctx = RequestContext.getCurrentContext();

@ -66,7 +66,5 @@ public class PolarisCircuitBreakerBootstrapConfiguration {
public int getOrder() {
return ContextConstant.ModifierOrder.CIRCUIT_BREAKER_ORDER;
}
}
}

@ -40,7 +40,8 @@ import static org.springframework.core.Ordered.HIGHEST_PRECEDENCE;
*
* @author Haotian Zhang
*/
@ConditionalOnProperty(value = "spring.cloud.polaris.circuitbreaker.enabled", havingValue = "true", matchIfMissing = true)
@ConditionalOnProperty(value = "spring.cloud.polaris.circuitbreaker.enabled",
havingValue = "true", matchIfMissing = true)
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(name = "org.springframework.cloud.openfeign.FeignAutoConfiguration")
@AutoConfigureAfter(PolarisContextAutoConfiguration.class)
@ -57,5 +58,4 @@ public class PolarisFeignClientAutoConfiguration {
public PolarisFeignBeanPostProcessor polarisFeignBeanPostProcessor(ConsumerAPI consumerAPI) {
return new PolarisFeignBeanPostProcessor(consumerAPI);
}
}

@ -55,5 +55,4 @@ public class PolarisRestTemplateAutoConfiguration {
PolarisRestTemplateResponseErrorHandler restTemplateResponseErrorHandler) {
return new PolarisRestTemplateModifier(restTemplateResponseErrorHandler);
}
}

@ -55,7 +55,8 @@ public class PolarisFeignBeanPostProcessor implements BeanPostProcessor, BeanFac
if (bean instanceof LoadBalancerFeignClient) {
LoadBalancerFeignClient client = ((LoadBalancerFeignClient) bean);
return new PolarisLoadBalancerFeignClient(
createPolarisFeignClient(client.getDelegate()), factory(),
createPolarisFeignClient(client.getDelegate()),
factory(),
clientFactory());
}
if (bean instanceof FeignBlockingLoadBalancerClient) {
@ -91,5 +92,4 @@ public class PolarisFeignBeanPostProcessor implements BeanPostProcessor, BeanFac
SpringClientFactory clientFactory() {
return this.factory.getBean(SpringClientFactory.class);
}
}

@ -32,5 +32,4 @@ public class PolarisFeignBlockingLoadBalancerClient extends FeignBlockingLoadBal
public PolarisFeignBlockingLoadBalancerClient(Client delegate, BlockingLoadBalancerClient loadBalancerClient) {
super(delegate, loadBalancerClient);
}
}

@ -43,7 +43,6 @@ import static feign.Util.checkNotNull;
*/
public class PolarisFeignClient implements Client {
private static final Logger LOG = LoggerFactory.getLogger(PolarisFeignClient.class);
private final Client delegate;
@ -61,7 +60,7 @@ public class PolarisFeignClient implements Client {
try {
Response response = delegate.execute(request, options);
// HTTP code greater than 500 is an exception
if (response.status() >= 500) {
if (response.status() > 500) {
resultRequest.setRetStatus(RetStatus.RetFail);
}
LOG.debug("Will report result of {}. Request=[{}]. Response=[{}].",

@ -30,10 +30,8 @@ import org.springframework.cloud.openfeign.ribbon.LoadBalancerFeignClient;
*/
public class PolarisLoadBalancerFeignClient extends LoadBalancerFeignClient {
public PolarisLoadBalancerFeignClient(Client delegate,
CachingSpringLoadBalancerFactory lbClientFactory,
public PolarisLoadBalancerFeignClient(Client delegate, CachingSpringLoadBalancerFactory lbClientFactory,
SpringClientFactory clientFactory) {
super(delegate, lbClientFactory, clientFactory);
}
}

@ -29,15 +29,15 @@ import org.springframework.web.client.RestTemplate;
/**
* Auto configuration RestTemplate, Find the RestTemplate bean annotated with {@link LoadBalanced},
* then replace {@link org.springframework.web.client.ResponseErrorHandler} with {@link PolarisRestTemplateResponseErrorHandler} .
* then replace {@link org.springframework.web.client.ResponseErrorHandler}
* with {@link PolarisRestTemplateResponseErrorHandler} .
*
* @author wh 2022/6/21
*/
public class PolarisRestTemplateModifier implements ApplicationContextAware, SmartInitializingSingleton {
private ApplicationContext applicationContext;
private final PolarisRestTemplateResponseErrorHandler polarisRestTemplateResponseErrorHandler;
private ApplicationContext applicationContext;
public PolarisRestTemplateModifier(PolarisRestTemplateResponseErrorHandler polarisRestTemplateResponseErrorHandler) {
this.polarisRestTemplateResponseErrorHandler = polarisRestTemplateResponseErrorHandler;

@ -54,7 +54,8 @@ public class PolarisRestTemplateResponseErrorHandler implements ResponseErrorHan
private final PolarisResponseErrorHandler polarisResponseErrorHandler;
public PolarisRestTemplateResponseErrorHandler(ConsumerAPI consumerAPI, PolarisResponseErrorHandler polarisResponseErrorHandler) {
public PolarisRestTemplateResponseErrorHandler(ConsumerAPI consumerAPI,
PolarisResponseErrorHandler polarisResponseErrorHandler) {
this.consumerAPI = consumerAPI;
this.polarisResponseErrorHandler = polarisResponseErrorHandler;
}
@ -74,7 +75,8 @@ public class PolarisRestTemplateResponseErrorHandler implements ResponseErrorHan
}
@Override
public void handleError(@NonNull URI url, @NonNull HttpMethod method, @NonNull ClientHttpResponse response) throws IOException {
public void handleError(@NonNull URI url, @NonNull HttpMethod method, @NonNull ClientHttpResponse response)
throws IOException {
ServiceCallResult resultRequest = createServiceCallResult(url);
try {
HttpURLConnection connection = (HttpURLConnection) ReflectionUtils.getFieldValue(response, FIELD_NAME);
@ -111,5 +113,4 @@ public class PolarisRestTemplateResponseErrorHandler implements ResponseErrorHan
}
return resultRequest;
}
}

@ -32,14 +32,14 @@ import static org.assertj.core.api.Assertions.assertThat;
*/
public class PolarisCircuitBreakerBootstrapConfigurationTest {
private ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(
AutoConfigurations.of(PolarisCircuitBreakerBootstrapConfiguration.class))
.withConfiguration(AutoConfigurations.of(PolarisCircuitBreakerBootstrapConfiguration.class))
.withPropertyValues("spring.cloud.polaris.circuitbreaker.enabled=true");
@Test
public void testDefaultInitialization() {
this.contextRunner.run(context -> {
assertThat(context).hasSingleBean(PolarisCircuitBreakerBootstrapConfiguration.CircuitBreakerConfigModifier.class);
assertThat(context).hasSingleBean(
PolarisCircuitBreakerBootstrapConfiguration.CircuitBreakerConfigModifier.class);
});
}
}

@ -36,8 +36,7 @@ import static org.assertj.core.api.Assertions.assertThat;
public class PolarisFeignClientAutoConfigurationTest {
private ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(
AutoConfigurations.of(
.withConfiguration(AutoConfigurations.of(
PolarisContextAutoConfiguration.class,
PolarisFeignClientAutoConfiguration.class))
.withPropertyValues("spring.cloud.polaris.circuitbreaker.enabled=true");
@ -49,5 +48,4 @@ public class PolarisFeignClientAutoConfigurationTest {
assertThat(context).hasSingleBean(PolarisFeignBeanPostProcessor.class);
});
}
}

@ -42,8 +42,7 @@ import static org.assertj.core.api.Assertions.assertThat;
public class PolarisRestTemplateAutoConfigurationTest {
private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.withConfiguration(
AutoConfigurations.of(
.withConfiguration(AutoConfigurations.of(
PolarisRestTemplateAutoConfigurationTester.class,
PolarisContextAutoConfiguration.class,
PolarisRestTemplateAutoConfiguration.class))
@ -68,5 +67,4 @@ public class PolarisRestTemplateAutoConfigurationTest {
return new RestTemplate();
}
}
}

@ -73,7 +73,8 @@ public class PolarisFeignClientTest {
}
try {
assertThat(new PolarisFeignClient(mock(Client.class), mock(ConsumerAPI.class))).isInstanceOf(PolarisFeignClient.class);
assertThat(new PolarisFeignClient(mock(Client.class), mock(ConsumerAPI.class)))
.isInstanceOf(PolarisFeignClient.class);
}
catch (Throwable e) {
fail("Exception encountered.", e);
@ -90,7 +91,7 @@ public class PolarisFeignClientTest {
return Response.builder().request(request).status(200).build();
}
else if (request.httpMethod().equals(Request.HttpMethod.POST)) {
return Response.builder().request(request).status(500).build();
return Response.builder().request(request).status(502).build();
}
throw new IOException("Mock exception.");
}).when(delegate).execute(any(Request.class), nullable(Request.Options.class));
@ -113,10 +114,10 @@ public class PolarisFeignClientTest {
Maps.newHashMap(), null, requestTemplate), null);
assertThat(response.status()).isEqualTo(200);
// 200
// 502
response = polarisFeignClient.execute(Request.create(Request.HttpMethod.POST, "http://localhost:8080/test",
Maps.newHashMap(), null, requestTemplate), null);
assertThat(response.status()).isEqualTo(500);
assertThat(response.status()).isEqualTo(502);
// Exception
try {

@ -102,5 +102,4 @@ public class SimpleClientHttpResponseTest extends AbstractClientHttpResponse {
// ignore
}
}
}

@ -31,7 +31,6 @@ import org.apache.commons.lang.StringUtils;
import org.springframework.util.CollectionUtils;
/**
* Read configuration from spring cloud's configuration file and override polaris.yaml.
*

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

@ -40,8 +40,7 @@ import org.springframework.core.env.Environment;
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnPolarisEnabled
@ConditionalOnProperty(value = "spring.cloud.polaris.config.enabled",
matchIfMissing = true)
@ConditionalOnProperty(value = "spring.cloud.polaris.config.enabled", matchIfMissing = true)
@Import(PolarisContextAutoConfiguration.class)
public class PolarisConfigBootstrapAutoConfiguration {
@ -80,5 +79,4 @@ public class PolarisConfigBootstrapAutoConfiguration {
PolarisContextProperties polarisContextProperties) {
return new ConfigurationModifier(polarisConfigProperties, polarisContextProperties);
}
}

@ -52,8 +52,7 @@ import org.springframework.util.StringUtils;
@Order(0)
public class PolarisConfigFileLocator implements PropertySourceLocator {
private static final Logger LOGGER = LoggerFactory
.getLogger(PolarisConfigFileLocator.class);
private static final Logger LOGGER = LoggerFactory.getLogger(PolarisConfigFileLocator.class);
private static final String POLARIS_CONFIG_PROPERTY_SOURCE_NAME = "polaris-config";
@ -115,7 +114,7 @@ public class PolarisConfigFileLocator implements PropertySourceLocator {
private List<ConfigFileMetadata> getInternalConfigFiles() {
String namespace = polarisContextProperties.getNamespace();
String serviceName = polarisContextProperties.getService();
if (StringUtils.isEmpty(serviceName)) {
if (!StringUtils.hasText(serviceName)) {
serviceName = environment.getProperty("spring.application.name");
}
@ -125,7 +124,7 @@ public class PolarisConfigFileLocator implements PropertySourceLocator {
String[] activeProfiles = environment.getActiveProfiles();
for (String activeProfile : activeProfiles) {
if (StringUtils.isEmpty(activeProfile)) {
if (!StringUtils.hasText(activeProfile)) {
continue;
}
@ -137,7 +136,7 @@ public class PolarisConfigFileLocator implements PropertySourceLocator {
internalConfigFiles.add(new DefaultConfigFileMetadata(namespace, serviceName, "application.yml"));
for (String activeProfile : activeProfiles) {
if (StringUtils.isEmpty(activeProfile)) {
if (!StringUtils.hasText(activeProfile)) {
continue;
}
@ -160,9 +159,8 @@ public class PolarisConfigFileLocator implements PropertySourceLocator {
for (ConfigFileGroup configFileGroup : configFileGroups) {
String group = configFileGroup.getName();
if (StringUtils.isEmpty(group)) {
throw new IllegalArgumentException(
"polaris config group name cannot be empty.");
if (!StringUtils.hasText(group)) {
throw new IllegalArgumentException("polaris config group name cannot be empty.");
}
List<String> files = configFileGroup.getFiles();
@ -171,16 +169,14 @@ public class PolarisConfigFileLocator implements PropertySourceLocator {
}
for (String fileName : files) {
PolarisPropertySource polarisPropertySource = loadPolarisPropertySource(
namespace, group, fileName);
PolarisPropertySource polarisPropertySource = loadPolarisPropertySource(namespace, group, fileName);
compositePropertySource.addPropertySource(polarisPropertySource);
polarisPropertySourceManager.addPropertySource(polarisPropertySource);
LOGGER.info(
"[SCT Config] Load and inject polaris config file success. namespace = {}, group = {}, fileName = {}",
namespace, group, fileName);
LOGGER.info("[SCT Config] Load and inject polaris config file success."
+ " namespace = {}, group = {}, fileName = {}", namespace, group, fileName);
}
}
}
@ -189,20 +185,17 @@ public class PolarisConfigFileLocator implements PropertySourceLocator {
String group, String fileName) {
ConfigKVFile configKVFile;
// unknown extension is resolved as properties file
if (ConfigFileFormat.isPropertyFile(fileName)
|| ConfigFileFormat.isUnknownFile(fileName)) {
if (ConfigFileFormat.isPropertyFile(fileName) || ConfigFileFormat.isUnknownFile(fileName)) {
configKVFile = configFileService.getConfigPropertiesFile(namespace, group, fileName);
}
else if (ConfigFileFormat.isYamlFile(fileName)) {
configKVFile = configFileService.getConfigYamlFile(namespace, group, fileName);
}
else {
LOGGER.warn(
"[SCT Config] Unsupported config file. namespace = {}, group = {}, fileName = {}",
LOGGER.warn("[SCT Config] Unsupported config file. namespace = {}, group = {}, fileName = {}",
namespace, group, fileName);
throw new IllegalStateException(
"Only configuration files in the format of properties / yaml / yaml"
throw new IllegalStateException("Only configuration files in the format of properties / yaml / yaml"
+ " can be injected into the spring context");
}
@ -213,5 +206,4 @@ public class PolarisConfigFileLocator implements PropertySourceLocator {
return new PolarisPropertySource(namespace, group, fileName, configKVFile, map);
}
}

@ -74,5 +74,4 @@ public class PolarisPropertySource extends MapPropertySource {
return "PolarisPropertySource{" + "namespace='" + namespace + '\'' + ", group='"
+ group + '\'' + ", fileName='" + fileName + '\'' + '}';
}
}

@ -23,7 +23,6 @@ import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import com.tencent.cloud.polaris.config.config.PolarisConfigProperties;
import com.tencent.polaris.configuration.api.core.ConfigKVFileChangeEvent;
import com.tencent.polaris.configuration.api.core.ConfigKVFileChangeListener;
import com.tencent.polaris.configuration.api.core.ConfigPropertyChangeInfo;
import org.slf4j.Logger;
@ -46,18 +45,14 @@ import org.springframework.util.CollectionUtils;
public class PolarisPropertySourceAutoRefresher
implements ApplicationListener<ApplicationReadyEvent>, ApplicationContextAware {
private static final Logger LOGGER = LoggerFactory
.getLogger(PolarisPropertySourceAutoRefresher.class);
private static final Logger LOGGER = LoggerFactory.getLogger(PolarisPropertySourceAutoRefresher.class);
private final PolarisConfigProperties polarisConfigProperties;
private final PolarisPropertySourceManager polarisPropertySourceManager;
private ApplicationContext applicationContext;
private final ContextRefresher contextRefresher;
private final AtomicBoolean registered = new AtomicBoolean(false);
private ApplicationContext applicationContext;
public PolarisPropertySourceAutoRefresher(
PolarisConfigProperties polarisConfigProperties,
@ -69,8 +64,7 @@ public class PolarisPropertySourceAutoRefresher
}
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@ -84,8 +78,7 @@ public class PolarisPropertySourceAutoRefresher
return;
}
List<PolarisPropertySource> polarisPropertySources = polarisPropertySourceManager
.getAllPropertySources();
List<PolarisPropertySource> polarisPropertySources = polarisPropertySourceManager.getAllPropertySources();
if (CollectionUtils.isEmpty(polarisPropertySources)) {
return;
}
@ -97,10 +90,7 @@ public class PolarisPropertySourceAutoRefresher
// register polaris config publish event
for (PolarisPropertySource polarisPropertySource : polarisPropertySources) {
polarisPropertySource.getConfigKVFile()
.addChangeListener(new ConfigKVFileChangeListener() {
@Override
public void onChange(
ConfigKVFileChangeEvent configKVFileChangeEvent) {
.addChangeListener((ConfigKVFileChangeListener) configKVFileChangeEvent -> {
LOGGER.info(
"[SCT Config] received polaris config change event and will refresh spring context."
+ "namespace = {}, group = {}, fileName = {}",
@ -108,22 +98,18 @@ public class PolarisPropertySourceAutoRefresher
polarisPropertySource.getGroup(),
polarisPropertySource.getFileName());
Map<String, Object> source = polarisPropertySource
.getSource();
Map<String, Object> source = polarisPropertySource.getSource();
for (String changedKey : configKVFileChangeEvent
.changedKeys()) {
for (String changedKey : configKVFileChangeEvent.changedKeys()) {
ConfigPropertyChangeInfo configPropertyChangeInfo = configKVFileChangeEvent
.getChangeInfo(changedKey);
LOGGER.info("[SCT Config] changed property = {}",
configPropertyChangeInfo);
LOGGER.info("[SCT Config] changed property = {}", configPropertyChangeInfo);
switch (configPropertyChangeInfo.getChangeType()) {
case MODIFIED:
case ADDED:
source.put(changedKey,
configPropertyChangeInfo.getNewValue());
source.put(changedKey, configPropertyChangeInfo.getNewValue());
break;
case DELETED:
source.remove(changedKey);
@ -133,9 +119,7 @@ public class PolarisPropertySourceAutoRefresher
// rebuild beans with @RefreshScope annotation
contextRefresher.refresh();
}
});
}
}
}

@ -33,12 +33,10 @@ public class PolarisPropertySourceManager {
private final Map<String, PolarisPropertySource> polarisPropertySources = new ConcurrentHashMap<>();
public void addPropertySource(PolarisPropertySource polarisPropertySource) {
polarisPropertySources.putIfAbsent(polarisPropertySource.getPropertySourceName(),
polarisPropertySource);
polarisPropertySources.putIfAbsent(polarisPropertySource.getPropertySourceName(), polarisPropertySource);
}
public List<PolarisPropertySource> getAllPropertySources() {
return new ArrayList<>(polarisPropertySources.values());
}
}

@ -96,10 +96,8 @@ public class PolarisConfigAnnotationProcessor implements BeanPostProcessor, Prio
Set<String> interestedKeys =
annotatedInterestedKeys.length > 0 ? Sets.newHashSet(annotatedInterestedKeys) : null;
Set<String> interestedKeyPrefixes =
annotatedInterestedKeyPrefixes.length > 0 ? Sets.newHashSet(annotatedInterestedKeyPrefixes)
: null;
annotatedInterestedKeyPrefixes.length > 0 ? Sets.newHashSet(annotatedInterestedKeyPrefixes) : null;
addChangeListener(configChangeListener, interestedKeys, interestedKeyPrefixes);
}
}

@ -54,5 +54,4 @@ public @interface PolarisConfigKVFileChangeListener {
* @return interested key-prefixed in the listener
*/
String[] interestedKeyPrefixes() default {};
}

@ -56,5 +56,4 @@ public class ConfigFileGroup {
public String toString() {
return "ConfigFileGroup{" + "name='" + name + '\'' + ", file=" + files + '}';
}
}

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

@ -84,5 +84,4 @@ public final class ConfigChangeEvent {
public Set<String> interestedChangedKeys() {
return interestedChangedKeys;
}
}

@ -31,5 +31,4 @@ public interface ConfigChangeListener {
* @param changeEvent the event for this change
*/
void onChange(ConfigChangeEvent changeEvent);
}

@ -107,5 +107,4 @@ public final class PolarisConfigChangeEventListener implements ApplicationListen
});
return ret;
}
}

@ -52,6 +52,7 @@ import static com.tencent.polaris.configuration.api.core.ChangeType.MODIFIED;
* <p>Refer to the Apollo project implementation
* <code><a href=https://github.com/apolloconfig/apollo/blob/master/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/AbstractConfig.java>
* AbstractConfig</a></code>
*
* @author Palmer Xu 2022-06-06
*/
public final class PolarisConfigListenerContext {
@ -60,32 +61,30 @@ public final class PolarisConfigListenerContext {
* Logger instance.
*/
private static final Logger LOG = LoggerFactory.getLogger(PolarisConfigListenerContext.class);
/**
* Execute service Atomic Reference Cache .
*/
private static final AtomicReference<ExecutorService> EAR = new AtomicReference<>();
/**
* All custom {@link ConfigChangeListener} instance defined in application .
*/
private static final List<ConfigChangeListener> listeners = Lists.newCopyOnWriteArrayList();
/**
* All custom interested keys defined in application .
*/
private static final Map<ConfigChangeListener, Set<String>> interestedKeys = Maps.newHashMap();
/**
* All custom interested key prefixes defined in application .
*/
private static final Map<ConfigChangeListener, Set<String>> interestedKeyPrefixes = Maps.newHashMap();
/**
* Cache all latest configuration information for users in the application environment .
*/
private static final Cache<String, Object> properties = CacheBuilder.newBuilder().build();
private PolarisConfigListenerContext() {
}
/**
* Get or Created new execute server .
* @return execute service instance of {@link ExecutorService}
@ -273,5 +272,4 @@ public final class PolarisConfigListenerContext {
return Collections.unmodifiableSet(interestedChangedKeys);
}
}

@ -31,6 +31,7 @@ import com.tencent.polaris.configuration.api.core.ConfigKVFileChangeListener;
/**
* Mock config kv file for test.
*
* @author lepdou 2022-06-11
*/
public class MockedConfigKVFile implements ConfigKVFile {

@ -41,12 +41,15 @@ import org.springframework.core.env.PropertySource;
import static org.mockito.Mockito.when;
/**
* test for {@link PolarisConfigFileLocator}
* test for {@link PolarisConfigFileLocator}.
*
* @author lepdou 2022-06-11
*/
@RunWith(MockitoJUnitRunner.class)
public class PolarisConfigFileLocatorTest {
private final String testNamespace = "testNamespace";
private final String testServiceName = "testServiceName";
@Mock
private PolarisConfigProperties polarisConfigProperties;
@Mock
@ -58,9 +61,6 @@ public class PolarisConfigFileLocatorTest {
@Mock
private Environment environment;
private final String testNamespace = "testNamespace";
private final String testServiceName = "testServiceName";
@Test
public void testLoadApplicationPropertiesFile() {
PolarisConfigFileLocator locator = new PolarisConfigFileLocator(polarisConfigProperties, polarisContextProperties,

@ -38,12 +38,16 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* test for {@link PolarisPropertySourceAutoRefresher}
* test for {@link PolarisPropertySourceAutoRefresher}.
*
* @author lepdou 2022-06-11
*/
@RunWith(MockitoJUnitRunner.class)
public class PolarisPropertiesSourceAutoRefresherTest {
private final String testNamespace = "testNamespace";
private final String testServiceName = "testServiceName";
private final String testFileName = "application.properties";
@Mock
private PolarisConfigProperties polarisConfigProperties;
@Mock
@ -51,10 +55,6 @@ public class PolarisPropertiesSourceAutoRefresherTest {
@Mock
private ContextRefresher contextRefresher;
private final String testNamespace = "testNamespace";
private final String testServiceName = "testServiceName";
private final String testFileName = "application.properties";
@Test
public void testConfigFileChanged() {
PolarisPropertySourceAutoRefresher refresher = new PolarisPropertySourceAutoRefresher(polarisConfigProperties,
@ -118,5 +118,4 @@ public class PolarisPropertiesSourceAutoRefresherTest {
Assert.assertEquals("v1", polarisPropertySource.getProperty("k1"));
verify(contextRefresher).refresh();
}
}

@ -39,13 +39,13 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
/**
* Integration testing for change listener.
*
* @author lepdou 2022-06-11
*/
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = DEFINED_PORT,
classes = ConfigChangeListenerTest.TestApplication.class,
properties = {"server.port=8081",
"spring.config.location = classpath:application-test.yml"})
properties = {"server.port=8081", "spring.config.location = classpath:application-test.yml"})
public class ConfigChangeListenerTest {
@Autowired
@ -120,5 +120,4 @@ public class ConfigChangeListenerTest {
}
}
}
}

@ -56,15 +56,13 @@ public class DiscoveryPropertiesAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public ProviderAPI polarisProvider(SDKContext polarisContext)
throws PolarisException {
public ProviderAPI polarisProvider(SDKContext polarisContext) throws PolarisException {
return DiscoveryAPIFactory.createProviderAPIByContext(polarisContext);
}
@Bean
@ConditionalOnMissingBean
public ConsumerAPI polarisConsumer(SDKContext polarisContext)
throws PolarisException {
public ConsumerAPI polarisConsumer(SDKContext polarisContext) throws PolarisException {
return DiscoveryAPIFactory.createConsumerAPIByContext(polarisContext);
}
@ -98,5 +96,4 @@ public class DiscoveryPropertiesAutoConfiguration {
public boolean isDiscoveryEnabled() {
return discoveryEnabled;
}
}

@ -28,6 +28,8 @@ import org.springframework.cloud.client.ConditionalOnDiscoveryEnabled;
import org.springframework.context.annotation.Conditional;
/**
* Condition if Polaris discovery is enabled.
*
* @author Haotian Zhang, Andrew Shan, Jie Cheng
*/
@Retention(RetentionPolicy.RUNTIME)

@ -29,21 +29,17 @@ import org.springframework.core.type.AnnotatedTypeMetadata;
public class DiscoveryEnabledCondition implements Condition {
@Override
public boolean matches(ConditionContext conditionContext,
AnnotatedTypeMetadata annotatedTypeMetadata) {
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
boolean isDiscoveryEnabled = Boolean
.parseBoolean(conditionContext.getEnvironment()
.getProperty("spring.cloud.polaris.discovery.enabled", "true"));
boolean isDiscoveryEnabled = Boolean.parseBoolean(
conditionContext.getEnvironment().getProperty("spring.cloud.polaris.discovery.enabled", "true"));
boolean isConsulDiscoveryEnabled = Boolean
.parseBoolean(conditionContext.getEnvironment()
.getProperty("spring.cloud.consul.enabled", "false"))
boolean isConsulDiscoveryEnabled = Boolean.parseBoolean(
conditionContext.getEnvironment().getProperty("spring.cloud.consul.enabled", "false"))
&& Boolean.parseBoolean(conditionContext.getEnvironment()
.getProperty("spring.cloud.consul.discovery.enabled", "true"));
isDiscoveryEnabled |= isConsulDiscoveryEnabled;
return isDiscoveryEnabled;
}
}

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

@ -54,5 +54,4 @@ public class PolarisDiscoveryClient implements DiscoveryClient {
public List<String> getServices() {
return polarisServiceDiscovery.getServices();
}
}

@ -33,15 +33,12 @@ import org.springframework.context.annotation.Configuration;
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnBlockingDiscoveryEnabled
@AutoConfigureBefore({ SimpleDiscoveryClientAutoConfiguration.class,
CommonsClientAutoConfiguration.class })
@AutoConfigureBefore({SimpleDiscoveryClientAutoConfiguration.class, CommonsClientAutoConfiguration.class})
@AutoConfigureAfter(PolarisDiscoveryAutoConfiguration.class)
public class PolarisDiscoveryClientConfiguration {
@Bean
public DiscoveryClient polarisDiscoveryClient(
PolarisServiceDiscovery polarisServiceDiscovery) {
public DiscoveryClient polarisDiscoveryClient(PolarisServiceDiscovery polarisServiceDiscovery) {
return new PolarisDiscoveryClient(polarisServiceDiscovery);
}
}

@ -53,6 +53,7 @@ public class PolarisDiscoveryHandler {
/**
* Get a list of healthy instances.
*
* @param service service name
* @return list of healthy instances
*/
@ -66,6 +67,7 @@ public class PolarisDiscoveryHandler {
/**
* Return all instances for the given service.
*
* @param service serviceName
* @return list of instances
*/
@ -87,6 +89,7 @@ public class PolarisDiscoveryHandler {
/**
* Return all service for given namespace.
*
* @return service list
*/
public ServicesResponse GetServices() {
@ -95,5 +98,4 @@ public class PolarisDiscoveryHandler {
request.setNamespace(namespace);
return polarisConsumer.getServices(request);
}
}

@ -31,6 +31,8 @@ import com.tencent.polaris.api.rpc.InstancesResponse;
import org.springframework.cloud.client.ServiceInstance;
/**
* Polaris service discovery service.
*
* @author Haotian Zhang, Andrew Shan, Jie Cheng
*/
public class PolarisServiceDiscovery {
@ -49,8 +51,7 @@ public class PolarisServiceDiscovery {
*/
public List<ServiceInstance> getInstances(String serviceId) throws PolarisException {
List<ServiceInstance> instances = new ArrayList<>();
InstancesResponse filteredInstances = polarisDiscoveryHandler
.getHealthyInstances(serviceId);
InstancesResponse filteredInstances = polarisDiscoveryHandler.getHealthyInstances(serviceId);
ServiceInstances serviceInstances = filteredInstances.toServiceInstances();
for (Instance instance : serviceInstances.getInstances()) {
instances.add(new PolarisServiceInstance(instance));
@ -67,5 +68,4 @@ public class PolarisServiceDiscovery {
return polarisDiscoveryHandler.GetServices().getServices().stream()
.map(ServiceInfo::getService).collect(Collectors.toList());
}
}

@ -38,13 +38,11 @@ import org.springframework.cloud.client.discovery.ReactiveDiscoveryClient;
*/
public class PolarisReactiveDiscoveryClient implements ReactiveDiscoveryClient {
private static final Logger log = LoggerFactory
.getLogger(PolarisReactiveDiscoveryClient.class);
private static final Logger LOG = LoggerFactory.getLogger(PolarisReactiveDiscoveryClient.class);
private PolarisServiceDiscovery polarisServiceDiscovery;
private final PolarisServiceDiscovery polarisServiceDiscovery;
public PolarisReactiveDiscoveryClient(
PolarisServiceDiscovery polarisServiceDiscovery) {
public PolarisReactiveDiscoveryClient(PolarisServiceDiscovery polarisServiceDiscovery) {
this.polarisServiceDiscovery = polarisServiceDiscovery;
}
@ -55,7 +53,6 @@ public class PolarisReactiveDiscoveryClient implements ReactiveDiscoveryClient {
@Override
public Flux<ServiceInstance> getInstances(String serviceId) {
return Mono.justOrEmpty(serviceId).flatMapMany(loadInstancesFromPolaris())
.subscribeOn(Schedulers.boundedElastic());
}
@ -66,7 +63,7 @@ public class PolarisReactiveDiscoveryClient implements ReactiveDiscoveryClient {
return Flux.fromIterable(polarisServiceDiscovery.getInstances(serviceId));
}
catch (PolarisException e) {
log.error("get service instance[{}] from polaris error!", serviceId, e);
LOG.error("get service instance[{}] from polaris error!", serviceId, e);
return Flux.empty();
}
};
@ -79,10 +76,9 @@ public class PolarisReactiveDiscoveryClient implements ReactiveDiscoveryClient {
return Flux.fromIterable(polarisServiceDiscovery.getServices());
}
catch (Exception e) {
log.error("get services from polaris server fail,", e);
LOG.error("get services from polaris server fail,", e);
return Flux.empty();
}
}).subscribeOn(Schedulers.boundedElastic());
}
}

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

@ -39,7 +39,8 @@ import static com.tencent.cloud.polaris.discovery.refresh.PolarisServiceStatusCh
*
* @author Haotian Zhang
*/
public class PolarisRefreshApplicationReadyEventListener implements ApplicationListener<ApplicationReadyEvent>, ApplicationEventPublisherAware, DisposableBean {
public class PolarisRefreshApplicationReadyEventListener
implements ApplicationListener<ApplicationReadyEvent>, ApplicationEventPublisherAware, DisposableBean {
private static final Logger LOG = LoggerFactory.getLogger(PolarisRefreshApplicationReadyEventListener.class);
private static final int DELAY = 60;
@ -48,7 +49,8 @@ public class PolarisRefreshApplicationReadyEventListener implements ApplicationL
private final ScheduledExecutorService refreshExecutor;
private ApplicationEventPublisher publisher;
public PolarisRefreshApplicationReadyEventListener(PolarisDiscoveryHandler polarisDiscoveryHandler, PolarisServiceStatusChangeListener polarisServiceStatusChangeListener) {
public PolarisRefreshApplicationReadyEventListener(PolarisDiscoveryHandler polarisDiscoveryHandler,
PolarisServiceStatusChangeListener polarisServiceStatusChangeListener) {
this.polarisDiscoveryHandler = polarisDiscoveryHandler;
this.polarisServiceStatusChangeListener = polarisServiceStatusChangeListener;
this.refreshExecutor = Executors.newSingleThreadScheduledExecutor(
@ -86,7 +88,7 @@ public class PolarisRefreshApplicationReadyEventListener implements ApplicationL
}
@Override
public void destroy() throws Exception {
public void destroy() {
refreshExecutor.shutdown();
}
}

@ -35,7 +35,8 @@ import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.util.CollectionUtils;
/**
* Change listener of Polaris service info. When service info is created or deleted, or, instance of service is from 0 to
* Change listener of Polaris service info. When service info is created or deleted, or, instance of service is from
* 0 to many.
*
* @author Haotian Zhang
*/
@ -78,8 +79,10 @@ public class PolarisServiceStatusChangeListener extends AbstractResourceEventLis
LOG.debug("receive service instances={} change event", svcEventKey);
ServiceInstancesByProto oldIns = (ServiceInstancesByProto) oldValue;
ServiceInstancesByProto newIns = (ServiceInstancesByProto) newValue;
if ((CollectionUtils.isEmpty(oldIns.getInstances()) && !CollectionUtils.isEmpty(newIns.getInstances())) ||
(!CollectionUtils.isEmpty(oldIns.getInstances()) && CollectionUtils.isEmpty(newIns.getInstances()))) {
if ((CollectionUtils.isEmpty(oldIns.getInstances())
&& !CollectionUtils.isEmpty(newIns.getInstances())) ||
(!CollectionUtils.isEmpty(oldIns.getInstances())
&& CollectionUtils.isEmpty(newIns.getInstances()))) {
LOG.info("Service status of {} is update.", newIns.getService());
// Trigger reload of gateway route cache.

@ -164,7 +164,5 @@ public class ConsulContextProperties {
public int getOrder() {
return ModifierOrder.LAST;
}
}
}

@ -27,6 +27,8 @@ import com.tencent.cloud.polaris.context.ConditionalOnPolarisEnabled;
import org.springframework.context.annotation.Conditional;
/**
* Condition if Polaris registry is enabled.
*
* @author Haotian Zhang, Andrew Shan, Jie Cheng
*/
@Retention(RetentionPolicy.RUNTIME)

@ -31,11 +31,9 @@ import org.springframework.util.StringUtils;
*
* @author Haotian Zhang, Andrew Shan, Jie Cheng
*/
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 LOG = LoggerFactory.getLogger(PolarisAutoServiceRegistration.class);
private final PolarisRegistration registration;
@ -62,7 +60,7 @@ public class PolarisAutoServiceRegistration
@Override
protected void register() {
if (!this.registration.isRegisterEnabled()) {
log.debug("Registration disabled.");
LOG.debug("Registration disabled.");
return;
}
if (this.registration.getPort() <= 0) {
@ -96,5 +94,4 @@ public class PolarisAutoServiceRegistration
String appName = registration.getPolarisProperties().getService();
return StringUtils.isEmpty(appName) ? super.getAppName() : appName;
}
}

@ -51,10 +51,8 @@ public class PolarisRegistration implements Registration, ServiceInstance {
private final SDKContext polarisContext;
private final StaticMetadataManager staticMetadataManager;
private Map<String, String> metadata;
private final String host;
private Map<String, String> metadata;
public PolarisRegistration(
DiscoveryPropertiesAutoConfiguration discoveryPropertiesAutoConfiguration,
@ -89,8 +87,7 @@ public class PolarisRegistration implements Registration, ServiceInstance {
@Override
public boolean isSecure() {
return StringUtils.equalsIgnoreCase(polarisDiscoveryProperties.getProtocol(),
"https");
return StringUtils.equalsIgnoreCase(polarisDiscoveryProperties.getProtocol(), "https");
}
@Override

@ -51,8 +51,7 @@ import static org.springframework.util.ReflectionUtils.rethrowRuntimeException;
*/
public class PolarisServiceRegistry implements ServiceRegistry<Registration> {
private static final Logger log = LoggerFactory
.getLogger(PolarisServiceRegistry.class);
private static final Logger LOG = LoggerFactory.getLogger(PolarisServiceRegistry.class);
private static final int ttl = 5;
@ -82,9 +81,8 @@ public class PolarisServiceRegistry implements ServiceRegistry<Registration> {
@Override
public void register(Registration registration) {
if (StringUtils.isEmpty(registration.getServiceId())) {
log.warn("No service to register for polaris client...");
LOG.warn("No service to register for polaris client...");
return;
}
// Register instance.
@ -107,7 +105,7 @@ public class PolarisServiceRegistry implements ServiceRegistry<Registration> {
try {
ProviderAPI providerClient = polarisDiscoveryHandler.getProviderAPI();
providerClient.register(instanceRegisterRequest);
log.info("polaris registry, {} {} {}:{} {} register finished",
LOG.info("polaris registry, {} {} {}:{} {} register finished",
polarisDiscoveryProperties.getNamespace(),
registration.getServiceId(), registration.getHost(),
registration.getPort(), staticMetadataManager.getMergedStaticMetadata());
@ -120,19 +118,17 @@ public class PolarisServiceRegistry implements ServiceRegistry<Registration> {
}
}
catch (Exception e) {
log.error("polaris registry, {} register failed...{},",
registration.getServiceId(), registration, e);
LOG.error("polaris registry, {} register failed...{},", registration.getServiceId(), registration, e);
rethrowRuntimeException(e);
}
}
@Override
public void deregister(Registration registration) {
log.info("De-registering from Polaris Server now...");
LOG.info("De-registering from Polaris Server now...");
if (StringUtils.isEmpty(registration.getServiceId())) {
log.warn("No dom to de-register for polaris client...");
LOG.warn("No dom to de-register for polaris client...");
return;
}
@ -148,15 +144,14 @@ public class PolarisServiceRegistry implements ServiceRegistry<Registration> {
providerClient.deRegister(deRegisterRequest);
}
catch (Exception e) {
log.error("ERR_POLARIS_DEREGISTER, de-register failed...{},", registration,
e);
LOG.error("ERR_POLARIS_DEREGISTER, de-register failed...{},", registration, e);
}
finally {
if (null != heartbeatExecutor) {
heartbeatExecutor.shutdown();
}
}
log.info("De-registration finished.");
LOG.info("De-registration finished.");
}
@Override
@ -172,8 +167,7 @@ public class PolarisServiceRegistry implements ServiceRegistry<Registration> {
@Override
public Object getStatus(Registration registration) {
String serviceName = registration.getServiceId();
InstancesResponse instancesResponse = polarisDiscoveryHandler
.getInstances(serviceName);
InstancesResponse instancesResponse = polarisDiscoveryHandler.getInstances(serviceName);
Instance[] instances = instancesResponse.getInstances();
if (null == instances || instances.length == 0) {
return null;
@ -207,13 +201,10 @@ public class PolarisServiceRegistry implements ServiceRegistry<Registration> {
}
String healthCheckUrl = String.format("http://%s:%s%s",
heartbeatRequest.getHost(), heartbeatRequest.getPort(),
healthCheckEndpoint);
heartbeatRequest.getHost(), heartbeatRequest.getPort(), healthCheckEndpoint);
if (!OkHttpUtil.get(healthCheckUrl, null)) {
log.error(
"backend service health check failed. health check endpoint = {}",
healthCheckEndpoint);
LOG.error("backend service health check failed. health check endpoint = {}", healthCheckEndpoint);
return;
}
}
@ -221,12 +212,11 @@ public class PolarisServiceRegistry implements ServiceRegistry<Registration> {
polarisDiscoveryHandler.getProviderAPI().heartbeat(heartbeatRequest);
}
catch (PolarisException e) {
log.error("polaris heartbeat[{}]", e.getCode(), e);
LOG.error("polaris heartbeat[{}]", e.getCode(), e);
}
catch (Exception e) {
log.error("polaris heartbeat runtime error", e);
LOG.error("polaris heartbeat runtime error", e);
}
}, ttl, ttl, TimeUnit.SECONDS);
}
}

@ -43,8 +43,7 @@ import org.springframework.context.annotation.Configuration;
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties
@ConditionalOnPolarisRegisterEnabled
@ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled",
matchIfMissing = true)
@ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true)
@AutoConfigureAfter({AutoServiceRegistrationConfiguration.class,
AutoServiceRegistrationAutoConfiguration.class,
PolarisDiscoveryAutoConfiguration.class})
@ -73,7 +72,6 @@ public class PolarisServiceRegistryAutoConfiguration {
PolarisServiceRegistry registry,
AutoServiceRegistrationProperties autoServiceRegistrationProperties,
PolarisRegistration registration) {
return new PolarisAutoServiceRegistration(registry,
autoServiceRegistrationProperties, registration);
return new PolarisAutoServiceRegistration(registry, autoServiceRegistrationProperties, registration);
}
}

@ -29,19 +29,16 @@ import org.springframework.core.type.AnnotatedTypeMetadata;
public class RegisterEnabledCondition implements Condition {
@Override
public boolean matches(ConditionContext conditionContext,
AnnotatedTypeMetadata annotatedTypeMetadata) {
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
boolean isRegisterEnabled = Boolean.parseBoolean(conditionContext.getEnvironment()
.getProperty("spring.cloud.polaris.discovery.register", "true"));
boolean isConsulRegisterEnabled = Boolean
.parseBoolean(conditionContext.getEnvironment()
.getProperty("spring.cloud.consul.enabled", "false"))
boolean isConsulRegisterEnabled = Boolean.parseBoolean(
conditionContext.getEnvironment().getProperty("spring.cloud.consul.enabled", "false"))
&& Boolean.parseBoolean(conditionContext.getEnvironment()
.getProperty("spring.cloud.consul.discovery.register", "true"));
isRegisterEnabled |= isConsulRegisterEnabled;
return isRegisterEnabled;
}
}

@ -36,12 +36,10 @@ public class PolarisRibbonServerListConfiguration {
@Bean
@ConditionalOnMissingBean
public ServerList<Server> ribbonServerList(
PolarisDiscoveryHandler polarisDiscoveryHandler,
public ServerList<Server> ribbonServerList(PolarisDiscoveryHandler polarisDiscoveryHandler,
IClientConfig iClientConfig) {
PolarisServerList serverList = new PolarisServerList(polarisDiscoveryHandler);
serverList.initWithNiwsConfig(iClientConfig);
return serverList;
}
}

@ -56,8 +56,7 @@ public class PolarisServerList extends AbstractServerList<Server> {
}
private List<Server> getServers() {
InstancesResponse allInstances = polarisDiscoveryHandler
.getHealthyInstances(serviceId);
InstancesResponse allInstances = polarisDiscoveryHandler.getHealthyInstances(serviceId);
ServiceInstances serviceInstances = allInstances.toServiceInstances();
List<Server> polarisServers = new ArrayList<>();
for (Instance instance : serviceInstances.getInstances()) {
@ -74,5 +73,4 @@ public class PolarisServerList extends AbstractServerList<Server> {
public void initWithNiwsConfig(IClientConfig iClientConfig) {
this.serviceId = iClientConfig.getClientName();
}
}

@ -62,8 +62,7 @@ public final class OkHttpUtil {
if (response.isSuccessful() && Objects.nonNull(response.body())) {
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;
}
}
@ -88,5 +87,4 @@ public final class OkHttpUtil {
});
}
}
}

@ -41,7 +41,8 @@ public class DiscoveryPropertiesAutoConfigurationTest {
@Test
public void testDefaultInitialization() {
ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner().withConfiguration(
AutoConfigurations.of(PolarisContextAutoConfiguration.class,
AutoConfigurations.of(
PolarisContextAutoConfiguration.class,
DiscoveryPropertiesAutoConfiguration.class));
applicationContextRunner.run(context -> {
assertThat(context).hasSingleBean(DiscoveryPropertiesAutoConfiguration.class);
@ -57,7 +58,8 @@ public class DiscoveryPropertiesAutoConfigurationTest {
@Test
public void testInit() {
ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner().withConfiguration(
AutoConfigurations.of(PolarisContextAutoConfiguration.class,
AutoConfigurations.of(
PolarisContextAutoConfiguration.class,
TestConfiguration.class,
DiscoveryPropertiesAutoConfiguration.class))
.withPropertyValues("spring.cloud.polaris.discovery.register=false")
@ -65,7 +67,8 @@ public class DiscoveryPropertiesAutoConfigurationTest {
.withPropertyValues("spring.cloud.consul.discovery.enabled=false");
applicationContextRunner.run(context -> {
assertThat(context).hasSingleBean(DiscoveryPropertiesAutoConfiguration.class);
DiscoveryPropertiesAutoConfiguration discoveryPropertiesAutoConfiguration = context.getBean(DiscoveryPropertiesAutoConfiguration.class);
DiscoveryPropertiesAutoConfiguration discoveryPropertiesAutoConfiguration =
context.getBean(DiscoveryPropertiesAutoConfiguration.class);
assertThat(discoveryPropertiesAutoConfiguration.isRegisterEnabled()).isFalse();
assertThat(discoveryPropertiesAutoConfiguration.isDiscoveryEnabled()).isFalse();
});

@ -35,7 +35,8 @@ public class DiscoveryPropertiesBootstrapAutoConfigurationTest {
@Test
public void testDefaultInitialization() {
ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner().withConfiguration(
AutoConfigurations.of(PolarisContextAutoConfiguration.class,
AutoConfigurations.of(
PolarisContextAutoConfiguration.class,
DiscoveryPropertiesBootstrapAutoConfiguration.class))
.withPropertyValues("spring.cloud.polaris.enabled=true");
applicationContextRunner.run(context -> {

@ -30,7 +30,6 @@ import org.junit.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.runner.WebApplicationContextRunner;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Configuration;
import static com.tencent.polaris.test.common.Consts.PORT;
@ -46,9 +45,9 @@ public class PolarisDiscoveryAutoConfigurationTest {
private static NamingServer namingServer;
private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.withConfiguration(
AutoConfigurations.of(PolarisContextAutoConfiguration.class,
private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(
PolarisContextAutoConfiguration.class,
PolarisDiscoveryAutoConfiguration.class,
PolarisDiscoveryClientConfiguration.class,
PolarisContextAutoConfiguration.class))
@ -62,7 +61,7 @@ public class PolarisDiscoveryAutoConfigurationTest {
}
@AfterClass
public static void afterClass() throws Exception {
public static void afterClass() {
if (null != namingServer) {
namingServer.terminate();
}
@ -80,9 +79,7 @@ public class PolarisDiscoveryAutoConfigurationTest {
@Configuration
@EnableAutoConfiguration
@EnableDiscoveryClient
static class PolarisDiscoveryAutoConfiguration {
}
}

@ -26,7 +26,6 @@ import org.junit.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.runner.WebApplicationContextRunner;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Configuration;
import static com.tencent.polaris.test.common.Consts.PORT;
@ -42,9 +41,9 @@ public class PolarisDiscoveryClientConfigurationTest {
private static NamingServer namingServer;
private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.withConfiguration(
AutoConfigurations.of(PolarisContextAutoConfiguration.class,
private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(
PolarisContextAutoConfiguration.class,
PolarisDiscoveryClientConfiguration.class,
PolarisContextAutoConfiguration.class))
.withPropertyValues("spring.application.name=" + SERVICE_PROVIDER)
@ -57,7 +56,7 @@ public class PolarisDiscoveryClientConfigurationTest {
}
@AfterClass
public static void afterClass() throws Exception {
public static void afterClass() {
if (null != namingServer) {
namingServer.terminate();
}
@ -65,23 +64,18 @@ public class PolarisDiscoveryClientConfigurationTest {
@Test
public void testDefaultInitialization() {
this.contextRunner.run(context -> assertThat(context)
.hasSingleBean(PolarisDiscoveryClient.class));
this.contextRunner.run(context -> assertThat(context).hasSingleBean(PolarisDiscoveryClient.class));
}
@Test
public void testDiscoveryBlockingDisabled() {
this.contextRunner
.withPropertyValues("spring.cloud.discovery.blocking.enabled=false")
.run(context -> assertThat(context)
.doesNotHaveBean(PolarisDiscoveryClient.class));
this.contextRunner.withPropertyValues("spring.cloud.discovery.blocking.enabled=false")
.run(context -> assertThat(context).doesNotHaveBean(PolarisDiscoveryClient.class));
}
@Configuration
@EnableAutoConfiguration
@EnableDiscoveryClient
static class PolarisDiscoveryClientConfiguration {
}
}

@ -51,7 +51,6 @@ public class PolarisDiscoveryClientTest {
@Test
public void testGetInstances() {
when(polarisServiceDiscovery.getInstances(anyString()))
.thenReturn(singletonList(mock(PolarisServiceInstance.class)));
@ -62,9 +61,7 @@ public class PolarisDiscoveryClientTest {
@Test
public void testGetServices() {
when(polarisServiceDiscovery.getServices())
.thenReturn(singletonList(SERVICE_PROVIDER));
when(polarisServiceDiscovery.getServices()).thenReturn(singletonList(SERVICE_PROVIDER));
List<String> services = client.getServices();

@ -32,7 +32,6 @@ import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.runner.WebApplicationContextRunner;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Configuration;
import static com.tencent.polaris.test.common.Consts.NAMESPACE_TEST;
@ -49,7 +48,7 @@ public class PolarisServiceDiscoveryTest {
private static NamingServer namingServer;
private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(
PolarisContextAutoConfiguration.class,
PolarisServiceDiscoveryTest.PolarisPropertiesConfiguration.class,
@ -73,12 +72,11 @@ public class PolarisServiceDiscoveryTest {
instanceParameter.setIsolated(false);
instanceParameter.setWeight(100);
ServiceKey serviceKey = new ServiceKey(NAMESPACE_TEST, SERVICE_PROVIDER);
namingServer.getNamingService().batchAddInstances(serviceKey, PORT, 3,
instanceParameter);
namingServer.getNamingService().batchAddInstances(serviceKey, PORT, 3, instanceParameter);
}
@AfterClass
public static void afterClass() throws Exception {
public static void afterClass() {
if (null != namingServer) {
namingServer.terminate();
}
@ -87,10 +85,8 @@ public class PolarisServiceDiscoveryTest {
@Test
public void testGetInstances() {
this.contextRunner.run(context -> {
PolarisServiceDiscovery polarisServiceDiscovery = context
.getBean(PolarisServiceDiscovery.class);
List<ServiceInstance> serviceInstances = polarisServiceDiscovery
.getInstances(SERVICE_PROVIDER);
PolarisServiceDiscovery polarisServiceDiscovery = context.getBean(PolarisServiceDiscovery.class);
List<ServiceInstance> serviceInstances = polarisServiceDiscovery.getInstances(SERVICE_PROVIDER);
assertThat(serviceInstances.isEmpty()).isFalse();
assertThat(serviceInstances).hasSize(3);
assertThat(serviceInstances.get(0).getPort()).isEqualTo(PORT);
@ -102,8 +98,7 @@ public class PolarisServiceDiscoveryTest {
@Test
public void testGetServices() throws PolarisException {
this.contextRunner.run(context -> {
PolarisServiceDiscovery polarisServiceDiscovery = context
.getBean(PolarisServiceDiscovery.class);
PolarisServiceDiscovery polarisServiceDiscovery = context.getBean(PolarisServiceDiscovery.class);
List<String> services = polarisServiceDiscovery.getServices();
assertThat(services.size()).isEqualTo(1);
});
@ -112,9 +107,7 @@ public class PolarisServiceDiscoveryTest {
@Configuration
@EnableAutoConfiguration
@EnableDiscoveryClient
static class PolarisPropertiesConfiguration {
}
}

@ -27,7 +27,6 @@ import org.junit.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.runner.WebApplicationContextRunner;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Configuration;
import static com.tencent.polaris.test.common.Consts.PORT;
@ -43,9 +42,9 @@ public class PolarisReactiveDiscoveryClientConfigurationTest {
private static NamingServer namingServer;
private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.withConfiguration(
AutoConfigurations.of(PolarisContextAutoConfiguration.class,
private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(
PolarisContextAutoConfiguration.class,
PolarisReactiveDiscoveryClientConfiguration.class,
PolarisDiscoveryClientConfiguration.class,
PolarisContextAutoConfiguration.class))
@ -59,7 +58,7 @@ public class PolarisReactiveDiscoveryClientConfigurationTest {
}
@AfterClass
public static void afterClass() throws Exception {
public static void afterClass() {
if (null != namingServer) {
namingServer.terminate();
}
@ -73,9 +72,7 @@ public class PolarisReactiveDiscoveryClientConfigurationTest {
@Configuration
@EnableAutoConfiguration
@EnableDiscoveryClient
static class PolarisReactiveDiscoveryClientConfiguration {
}
}

@ -57,7 +57,6 @@ public class PolarisReactiveDiscoveryClientTest {
@Test
public void testGetInstances() throws PolarisException {
when(serviceDiscovery.getInstances(anyString())).thenAnswer(invocation -> {
String serviceName = invocation.getArgument(0);
if (SERVICE_PROVIDER.equalsIgnoreCase(serviceName)) {
@ -79,7 +78,6 @@ public class PolarisReactiveDiscoveryClientTest {
@Test
public void testGetServices() throws PolarisException {
when(serviceDiscovery.getServices()).thenAnswer(invocation -> {
if (count == 0) {
count++;

@ -64,7 +64,8 @@ public class PolarisServiceStatusChangeListenerTest {
polarisServiceStatusChangeListener.setApplicationEventPublisher(publisher);
// Service update event
ServiceEventKey serviceUpdateEventKey = new ServiceEventKey(new ServiceKey(NAMESPACE_TEST, SERVICE_PROVIDER), ServiceEventKey.EventType.SERVICE);
ServiceEventKey serviceUpdateEventKey = new ServiceEventKey(
new ServiceKey(NAMESPACE_TEST, SERVICE_PROVIDER), ServiceEventKey.EventType.SERVICE);
ServiceInfo serviceInfo = new ServiceInfo();
serviceInfo.setNamespace(NAMESPACE_TEST);
serviceInfo.setService(SERVICE_PROVIDER);
@ -81,7 +82,8 @@ public class PolarisServiceStatusChangeListenerTest {
// Instance update event
ServiceEventKey instanceUpdateEventKey = new ServiceEventKey(new ServiceKey(NAMESPACE_TEST, SERVICE_PROVIDER), ServiceEventKey.EventType.INSTANCE);
ServiceEventKey instanceUpdateEventKey = new ServiceEventKey(
new ServiceKey(NAMESPACE_TEST, SERVICE_PROVIDER), ServiceEventKey.EventType.INSTANCE);
DefaultInstance instance = new DefaultInstance();
instance.setNamespace(NAMESPACE_TEST);
instance.setService(SERVICE_PROVIDER);
@ -96,7 +98,7 @@ public class PolarisServiceStatusChangeListenerTest {
instances.set(oldInstances, Collections.emptyList());
ServiceInstancesByProto newInstances = new ServiceInstancesByProto();
instances.set(newInstances, Collections.singletonList(instance));
polarisServiceStatusChangeListener.onResourceUpdated(serviceUpdateEventKey, oldInstances, newInstances);
polarisServiceStatusChangeListener.onResourceUpdated(instanceUpdateEventKey, oldInstances, newInstances);
verify(publisher, times(2)).publishEvent(any(ApplicationEvent.class));
// No need update
@ -104,7 +106,7 @@ public class PolarisServiceStatusChangeListenerTest {
instances.set(oldInstances, Collections.singletonList(instance));
newInstances = new ServiceInstancesByProto();
instances.set(newInstances, Collections.singletonList(instance));
polarisServiceStatusChangeListener.onResourceUpdated(serviceUpdateEventKey, oldInstances, newInstances);
polarisServiceStatusChangeListener.onResourceUpdated(instanceUpdateEventKey, oldInstances, newInstances);
verify(publisher, times(2)).publishEvent(any(ApplicationEvent.class));
}
catch (NoSuchFieldException | IllegalAccessException e) {

@ -140,5 +140,4 @@ public class PolarisAutoServiceRegistrationTest {
doReturn(SERVICE_PROVIDER).when(polarisDiscoveryProperties).getService();
assertThat(polarisAutoServiceRegistration.getAppName()).isEqualTo(SERVICE_PROVIDER);
}
}

@ -28,7 +28,6 @@ import org.junit.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.runner.WebApplicationContextRunner;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationAutoConfiguration;
import org.springframework.context.annotation.Configuration;
@ -45,9 +44,9 @@ public class PolarisServiceRegistryAutoConfigurationTest {
private static NamingServer namingServer;
private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.withConfiguration(
AutoConfigurations.of(PolarisContextAutoConfiguration.class,
private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(
PolarisContextAutoConfiguration.class,
PolarisServiceRegistryAutoConfiguration.class,
PolarisDiscoveryClientConfiguration.class))
.withPropertyValues("spring.application.name=" + SERVICE_PROVIDER)
@ -60,7 +59,7 @@ public class PolarisServiceRegistryAutoConfigurationTest {
}
@AfterClass
public static void afterClass() throws Exception {
public static void afterClass() {
if (null != namingServer) {
namingServer.terminate();
}
@ -70,16 +69,13 @@ public class PolarisServiceRegistryAutoConfigurationTest {
public void testDefaultInitialization() {
this.contextRunner.run(context -> {
assertThat(context).hasSingleBean(PolarisDiscoveryAutoConfiguration.class);
assertThat(context)
.hasSingleBean(AutoServiceRegistrationAutoConfiguration.class);
assertThat(context).hasSingleBean(AutoServiceRegistrationAutoConfiguration.class);
});
}
@Configuration
@EnableAutoConfiguration
@EnableDiscoveryClient
static class PolarisServiceRegistryAutoConfiguration {
}
}

@ -49,17 +49,16 @@ public class PolarisServiceRegistryTest {
private static NamingServer namingServer;
private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.withConfiguration(
AutoConfigurations.of(PolarisContextAutoConfiguration.class,
private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(
PolarisContextAutoConfiguration.class,
PolarisPropertiesConfiguration.class,
PolarisDiscoveryClientConfiguration.class,
PolarisDiscoveryAutoConfiguration.class))
.withPropertyValues("spring.application.name=" + SERVICE_PROVIDER)
.withPropertyValues("server.port=" + PORT)
.withPropertyValues("spring.cloud.polaris.address=grpc://127.0.0.1:10081")
.withPropertyValues(
"spring.cloud.polaris.discovery.namespace=" + NAMESPACE_TEST)
.withPropertyValues("spring.cloud.polaris.discovery.namespace=" + NAMESPACE_TEST)
.withPropertyValues("spring.cloud.polaris.discovery.token=xxxxxx");
@BeforeClass
@ -67,12 +66,11 @@ public class PolarisServiceRegistryTest {
namingServer = NamingServer.startNamingServer(10081);
// add service
namingServer.getNamingService()
.addService(new ServiceKey(NAMESPACE_TEST, SERVICE_PROVIDER));
namingServer.getNamingService().addService(new ServiceKey(NAMESPACE_TEST, SERVICE_PROVIDER));
}
@AfterClass
public static void afterClass() throws Exception {
public static void afterClass() {
if (null != namingServer) {
namingServer.terminate();
}
@ -81,8 +79,7 @@ public class PolarisServiceRegistryTest {
@Test
public void testRegister() {
this.contextRunner.run(context -> {
PolarisServiceRegistry registry = context
.getBean(PolarisServiceRegistry.class);
PolarisServiceRegistry registry = context.getBean(PolarisServiceRegistry.class);
PolarisRegistration registration = Mockito.mock(PolarisRegistration.class);
when(registration.getHost()).thenReturn("127.0.0.1");
when(registration.getPort()).thenReturn(PORT);
@ -114,8 +111,7 @@ public class PolarisServiceRegistryTest {
@Test
public void testDeRegister() {
this.contextRunner.run(context -> {
PolarisServiceRegistry registry = context
.getBean(PolarisServiceRegistry.class);
PolarisServiceRegistry registry = context.getBean(PolarisServiceRegistry.class);
PolarisRegistration registration = Mockito.mock(PolarisRegistration.class);
doReturn(null).when(registration).getServiceId();
try {
@ -132,5 +128,4 @@ public class PolarisServiceRegistryTest {
static class PolarisPropertiesConfiguration {
}
}

@ -31,7 +31,7 @@ import static org.assertj.core.api.Assertions.assertThat;
*/
public class PolarisDiscoveryRibbonAutoConfigurationTest {
private ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner();
private final ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner();
@Test
public void testDefaultInitialization() {

@ -37,7 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat;
*/
public class PolarisRibbonServerListConfigurationTest {
private ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner();
private final ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner();
@Test
public void testDefaultInitialization() {

@ -54,9 +54,9 @@ public class PolarisServerListTest {
private static NamingServer namingServer;
private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.withConfiguration(
AutoConfigurations.of(PolarisContextAutoConfiguration.class,
private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(
PolarisContextAutoConfiguration.class,
PolarisServerListTest.PolarisPropertiesConfiguration.class,
PolarisDiscoveryClientConfiguration.class,
PolarisDiscoveryAutoConfiguration.class,
@ -64,8 +64,7 @@ public class PolarisServerListTest {
.withPropertyValues("spring.application.name=" + SERVICE_PROVIDER)
.withPropertyValues("server.port=" + PORT)
.withPropertyValues("spring.cloud.polaris.address=grpc://127.0.0.1:10081")
.withPropertyValues(
"spring.cloud.polaris.discovery.namespace=" + NAMESPACE_TEST)
.withPropertyValues("spring.cloud.polaris.discovery.namespace=" + NAMESPACE_TEST)
.withPropertyValues("spring.cloud.polaris.discovery.token=xxxxxx");
private IClientConfig iClientConfig;
@ -75,12 +74,11 @@ public class PolarisServerListTest {
namingServer = NamingServer.startNamingServer(10081);
// add service
namingServer.getNamingService()
.addService(new ServiceKey(NAMESPACE_TEST, SERVICE_PROVIDER));
namingServer.getNamingService().addService(new ServiceKey(NAMESPACE_TEST, SERVICE_PROVIDER));
}
@AfterClass
public static void afterClass() throws Exception {
public static void afterClass() {
if (null != namingServer) {
namingServer.terminate();
}
@ -97,8 +95,7 @@ public class PolarisServerListTest {
@Test
public void testGetInitialListOfServers() {
this.contextRunner.run(context -> {
PolarisDiscoveryHandler polarisDiscoveryHandler = context
.getBean(PolarisDiscoveryHandler.class);
PolarisDiscoveryHandler polarisDiscoveryHandler = context.getBean(PolarisDiscoveryHandler.class);
PolarisServerList serverList = new PolarisServerList(polarisDiscoveryHandler);
serverList.initWithNiwsConfig(iClientConfig);
@ -110,8 +107,7 @@ public class PolarisServerListTest {
@Test
public void testGetUpdatedListOfServers() {
this.contextRunner.run(context -> {
PolarisDiscoveryHandler polarisDiscoveryHandler = context
.getBean(PolarisDiscoveryHandler.class);
PolarisDiscoveryHandler polarisDiscoveryHandler = context.getBean(PolarisDiscoveryHandler.class);
PolarisServerList serverList = new PolarisServerList(polarisDiscoveryHandler);
serverList.initWithNiwsConfig(iClientConfig);
@ -121,8 +117,7 @@ public class PolarisServerListTest {
instanceParameter.setIsolated(false);
instanceParameter.setWeight(100);
ServiceKey serviceKey = new ServiceKey(NAMESPACE_TEST, SERVICE_PROVIDER);
namingServer.getNamingService().batchAddInstances(serviceKey, PORT, 3,
instanceParameter);
namingServer.getNamingService().batchAddInstances(serviceKey, PORT, 3, instanceParameter);
List<Server> servers = serverList.getUpdatedListOfServers();
assertThat(servers).hasSize(3);
@ -135,8 +130,7 @@ public class PolarisServerListTest {
@Test
public void testProperties() {
this.contextRunner.run(context -> {
PolarisDiscoveryHandler polarisDiscoveryHandler = context
.getBean(PolarisDiscoveryHandler.class);
PolarisDiscoveryHandler polarisDiscoveryHandler = context.getBean(PolarisDiscoveryHandler.class);
PolarisServerList serverList = new PolarisServerList(polarisDiscoveryHandler);
serverList.initWithNiwsConfig(iClientConfig);
@ -149,5 +143,4 @@ public class PolarisServerListTest {
static class PolarisPropertiesConfiguration {
}
}

@ -95,7 +95,6 @@ public class PolarisRateLimitAutoConfiguration {
registrationBean.setOrder(RateLimitConstant.FILTER_ORDER);
return registrationBean;
}
}
/**
@ -113,7 +112,5 @@ public class PolarisRateLimitAutoConfiguration {
return new QuotaCheckReactiveFilter(limitAPI, labelResolver,
polarisRateLimitProperties, rateLimitRuleLabelResolver);
}
}
}

@ -37,13 +37,11 @@ public class RateLimitConfigModifier implements PolarisConfigModifier {
@Override
public void modify(ConfigurationImpl configuration) {
// Update MaxQueuingTime.
configuration.getProvider().getRateLimit()
.setMaxQueuingTime(polarisRateLimitProperties.getMaxQueuingTime());
configuration.getProvider().getRateLimit().setMaxQueuingTime(polarisRateLimitProperties.getMaxQueuingTime());
}
@Override
public int getOrder() {
return ContextConstant.ModifierOrder.CIRCUIT_BREAKER_ORDER;
}
}

@ -162,5 +162,4 @@ public class QuotaCheckReactiveFilter implements WebFilter, Ordered {
Set<String> expressionLabels = rateLimitRuleLabelResolver.getExpressionLabelKeys(namespace, service);
return ExpressionLabelUtils.resolve(exchange, expressionLabels);
}
}

@ -144,8 +144,7 @@ public class QuotaCheckServletFilter extends OncePerRequestFilter {
return labelResolver.resolve(request);
}
catch (Throwable e) {
LOG.error("resolve custom label failed. resolver = {}",
labelResolver.getClass().getName(), e);
LOG.error("resolve custom label failed. resolver = {}", labelResolver.getClass().getName(), e);
}
}
return Collections.emptyMap();

@ -35,5 +35,4 @@ public interface PolarisRateLimiterLabelReactiveResolver {
* @return resolved labels
*/
Map<String, String> resolve(ServerWebExchange exchange);
}

@ -35,5 +35,4 @@ public interface PolarisRateLimiterLabelServletResolver {
* @return resolved labels
*/
Map<String, String> resolve(HttpServletRequest request);
}

@ -63,5 +63,4 @@ public final class RateLimitUtils {
return RateLimitConstant.QUOTA_LIMITED_INFO;
}
}

@ -39,11 +39,12 @@ import static org.assertj.core.api.Assertions.assertThat;
*/
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
public void testNoWebApplication() {
@ -58,7 +59,8 @@ public class PolarisRateLimitAutoConfigurationTest {
assertThat(context).doesNotHaveBean(PolarisRateLimitAutoConfiguration.QuotaCheckFilterConfig.class);
assertThat(context).doesNotHaveBean(QuotaCheckServletFilter.class);
assertThat(context).doesNotHaveBean(FilterRegistrationBean.class);
assertThat(context).doesNotHaveBean(PolarisRateLimitAutoConfiguration.MetadataReactiveFilterConfig.class);
assertThat(context).doesNotHaveBean(
PolarisRateLimitAutoConfiguration.MetadataReactiveFilterConfig.class);
assertThat(context).doesNotHaveBean(QuotaCheckReactiveFilter.class);
});
}
@ -66,7 +68,8 @@ public class PolarisRateLimitAutoConfigurationTest {
@Test
public void testServletWebApplication() {
this.webApplicationContextRunner
.withConfiguration(AutoConfigurations.of(PolarisContextAutoConfiguration.class,
.withConfiguration(AutoConfigurations.of(
PolarisContextAutoConfiguration.class,
PolarisRateLimitProperties.class,
PolarisRateLimitAutoConfiguration.class))
.run(context -> {
@ -75,7 +78,8 @@ public class PolarisRateLimitAutoConfigurationTest {
assertThat(context).hasSingleBean(PolarisRateLimitAutoConfiguration.QuotaCheckFilterConfig.class);
assertThat(context).hasSingleBean(QuotaCheckServletFilter.class);
assertThat(context).hasSingleBean(FilterRegistrationBean.class);
assertThat(context).doesNotHaveBean(PolarisRateLimitAutoConfiguration.MetadataReactiveFilterConfig.class);
assertThat(context).doesNotHaveBean(
PolarisRateLimitAutoConfiguration.MetadataReactiveFilterConfig.class);
assertThat(context).doesNotHaveBean(QuotaCheckReactiveFilter.class);
});
}
@ -83,7 +87,8 @@ public class PolarisRateLimitAutoConfigurationTest {
@Test
public void testReactiveWebApplication() {
this.reactiveWebApplicationContextRunner
.withConfiguration(AutoConfigurations.of(PolarisContextAutoConfiguration.class,
.withConfiguration(AutoConfigurations.of(
PolarisContextAutoConfiguration.class,
PolarisRateLimitProperties.class,
PolarisRateLimitAutoConfiguration.class))
.run(context -> {
@ -92,7 +97,8 @@ public class PolarisRateLimitAutoConfigurationTest {
assertThat(context).doesNotHaveBean(PolarisRateLimitAutoConfiguration.QuotaCheckFilterConfig.class);
assertThat(context).doesNotHaveBean(QuotaCheckServletFilter.class);
assertThat(context).doesNotHaveBean(FilterRegistrationBean.class);
assertThat(context).hasSingleBean(PolarisRateLimitAutoConfiguration.MetadataReactiveFilterConfig.class);
assertThat(context).hasSingleBean(
PolarisRateLimitAutoConfiguration.MetadataReactiveFilterConfig.class);
assertThat(context).hasSingleBean(QuotaCheckReactiveFilter.class);
});
}

@ -31,9 +31,8 @@ import static org.assertj.core.api.Assertions.assertThat;
*/
public class PolarisRateLimitPropertiesAutoConfigurationTest {
private ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(
AutoConfigurations.of(PolarisRateLimitPropertiesAutoConfiguration.class));
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(PolarisRateLimitPropertiesAutoConfiguration.class));
@Test
public void testDefaultInitialization() {

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

Loading…
Cancel
Save