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

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

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

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

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

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

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

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

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

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

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

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

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

@ -48,7 +48,8 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
@RunWith(SpringRunner.class) @RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = RANDOM_PORT, @SpringBootTest(webEnvironment = RANDOM_PORT,
classes = EncodeTransferMedataScgFilterTest.TestApplication.class, classes = EncodeTransferMedataScgFilterTest.TestApplication.class,
properties = {"spring.config.location = classpath:application-test.yml", "spring.main.web-application-type = reactive"}) properties = {"spring.config.location = classpath:application-test.yml",
"spring.main.web-application-type = reactive"})
public class EncodeTransferMedataScgFilterTest { public class EncodeTransferMedataScgFilterTest {
@Autowired @Autowired

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

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

@ -40,7 +40,8 @@ import static org.springframework.core.Ordered.HIGHEST_PRECEDENCE;
* *
* @author Haotian Zhang * @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) @Configuration(proxyBeanMethods = false)
@ConditionalOnClass(name = "org.springframework.cloud.openfeign.FeignAutoConfiguration") @ConditionalOnClass(name = "org.springframework.cloud.openfeign.FeignAutoConfiguration")
@AutoConfigureAfter(PolarisContextAutoConfiguration.class) @AutoConfigureAfter(PolarisContextAutoConfiguration.class)
@ -57,5 +58,4 @@ public class PolarisFeignClientAutoConfiguration {
public PolarisFeignBeanPostProcessor polarisFeignBeanPostProcessor(ConsumerAPI consumerAPI) { public PolarisFeignBeanPostProcessor polarisFeignBeanPostProcessor(ConsumerAPI consumerAPI) {
return new PolarisFeignBeanPostProcessor(consumerAPI); return new PolarisFeignBeanPostProcessor(consumerAPI);
} }
} }

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

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

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

@ -43,7 +43,6 @@ import static feign.Util.checkNotNull;
*/ */
public class PolarisFeignClient implements Client { public class PolarisFeignClient implements Client {
private static final Logger LOG = LoggerFactory.getLogger(PolarisFeignClient.class); private static final Logger LOG = LoggerFactory.getLogger(PolarisFeignClient.class);
private final Client delegate; private final Client delegate;
@ -61,7 +60,7 @@ public class PolarisFeignClient implements Client {
try { try {
Response response = delegate.execute(request, options); Response response = delegate.execute(request, options);
// HTTP code greater than 500 is an exception // HTTP code greater than 500 is an exception
if (response.status() >= 500) { if (response.status() > 500) {
resultRequest.setRetStatus(RetStatus.RetFail); resultRequest.setRetStatus(RetStatus.RetFail);
} }
LOG.debug("Will report result of {}. Request=[{}]. Response=[{}].", 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 class PolarisLoadBalancerFeignClient extends LoadBalancerFeignClient {
public PolarisLoadBalancerFeignClient(Client delegate, public PolarisLoadBalancerFeignClient(Client delegate, CachingSpringLoadBalancerFactory lbClientFactory,
CachingSpringLoadBalancerFactory lbClientFactory,
SpringClientFactory clientFactory) { SpringClientFactory clientFactory) {
super(delegate, lbClientFactory, 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}, * 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 * @author wh 2022/6/21
*/ */
public class PolarisRestTemplateModifier implements ApplicationContextAware, SmartInitializingSingleton { public class PolarisRestTemplateModifier implements ApplicationContextAware, SmartInitializingSingleton {
private ApplicationContext applicationContext;
private final PolarisRestTemplateResponseErrorHandler polarisRestTemplateResponseErrorHandler; private final PolarisRestTemplateResponseErrorHandler polarisRestTemplateResponseErrorHandler;
private ApplicationContext applicationContext;
public PolarisRestTemplateModifier(PolarisRestTemplateResponseErrorHandler polarisRestTemplateResponseErrorHandler) { public PolarisRestTemplateModifier(PolarisRestTemplateResponseErrorHandler polarisRestTemplateResponseErrorHandler) {
this.polarisRestTemplateResponseErrorHandler = polarisRestTemplateResponseErrorHandler; this.polarisRestTemplateResponseErrorHandler = polarisRestTemplateResponseErrorHandler;

@ -54,7 +54,8 @@ public class PolarisRestTemplateResponseErrorHandler implements ResponseErrorHan
private final PolarisResponseErrorHandler polarisResponseErrorHandler; private final PolarisResponseErrorHandler polarisResponseErrorHandler;
public PolarisRestTemplateResponseErrorHandler(ConsumerAPI consumerAPI, PolarisResponseErrorHandler polarisResponseErrorHandler) { public PolarisRestTemplateResponseErrorHandler(ConsumerAPI consumerAPI,
PolarisResponseErrorHandler polarisResponseErrorHandler) {
this.consumerAPI = consumerAPI; this.consumerAPI = consumerAPI;
this.polarisResponseErrorHandler = polarisResponseErrorHandler; this.polarisResponseErrorHandler = polarisResponseErrorHandler;
} }
@ -74,7 +75,8 @@ public class PolarisRestTemplateResponseErrorHandler implements ResponseErrorHan
} }
@Override @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); ServiceCallResult resultRequest = createServiceCallResult(url);
try { try {
HttpURLConnection connection = (HttpURLConnection) ReflectionUtils.getFieldValue(response, FIELD_NAME); HttpURLConnection connection = (HttpURLConnection) ReflectionUtils.getFieldValue(response, FIELD_NAME);
@ -111,5 +113,4 @@ public class PolarisRestTemplateResponseErrorHandler implements ResponseErrorHan
} }
return resultRequest; return resultRequest;
} }
} }

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

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

@ -42,11 +42,10 @@ import static org.assertj.core.api.Assertions.assertThat;
public class PolarisRestTemplateAutoConfigurationTest { public class PolarisRestTemplateAutoConfigurationTest {
private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.withConfiguration( .withConfiguration(AutoConfigurations.of(
AutoConfigurations.of( PolarisRestTemplateAutoConfigurationTester.class,
PolarisRestTemplateAutoConfigurationTester.class, PolarisContextAutoConfiguration.class,
PolarisContextAutoConfiguration.class, PolarisRestTemplateAutoConfiguration.class))
PolarisRestTemplateAutoConfiguration.class))
.withPropertyValues("spring.cloud.polaris.circuitbreaker.enabled=true"); .withPropertyValues("spring.cloud.polaris.circuitbreaker.enabled=true");
@Test @Test
@ -68,5 +67,4 @@ public class PolarisRestTemplateAutoConfigurationTest {
return new RestTemplate(); return new RestTemplate();
} }
} }
} }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

@ -27,9 +27,9 @@ import com.tencent.polaris.plugins.router.healthy.RecoverRouterConfig;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
/** /**
* Spring Cloud Tencent config Override polaris config. * Spring Cloud Tencent config Override polaris config.
* *
*@author lepdou 2022-04-24 * @author lepdou 2022-04-24
*/ */
public class DiscoveryConfigModifier implements PolarisConfigModifier { public class DiscoveryConfigModifier implements PolarisConfigModifier {

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

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

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

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

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

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

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

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

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

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

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

@ -35,7 +35,8 @@ import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.util.CollectionUtils; 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 * @author Haotian Zhang
*/ */
@ -78,8 +79,10 @@ public class PolarisServiceStatusChangeListener extends AbstractResourceEventLis
LOG.debug("receive service instances={} change event", svcEventKey); LOG.debug("receive service instances={} change event", svcEventKey);
ServiceInstancesByProto oldIns = (ServiceInstancesByProto) oldValue; ServiceInstancesByProto oldIns = (ServiceInstancesByProto) oldValue;
ServiceInstancesByProto newIns = (ServiceInstancesByProto) newValue; ServiceInstancesByProto newIns = (ServiceInstancesByProto) newValue;
if ((CollectionUtils.isEmpty(oldIns.getInstances()) && !CollectionUtils.isEmpty(newIns.getInstances())) || if ((CollectionUtils.isEmpty(oldIns.getInstances())
(!CollectionUtils.isEmpty(oldIns.getInstances()) && CollectionUtils.isEmpty(newIns.getInstances()))) { && !CollectionUtils.isEmpty(newIns.getInstances())) ||
(!CollectionUtils.isEmpty(oldIns.getInstances())
&& CollectionUtils.isEmpty(newIns.getInstances()))) {
LOG.info("Service status of {} is update.", newIns.getService()); LOG.info("Service status of {} is update.", newIns.getService());
// Trigger reload of gateway route cache. // Trigger reload of gateway route cache.

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

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

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

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

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

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

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

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

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

@ -62,8 +62,7 @@ public final class OkHttpUtil {
if (response.isSuccessful() && Objects.nonNull(response.body())) { if (response.isSuccessful() && Objects.nonNull(response.body())) {
String result = response.body().string(); String result = response.body().string();
logger.debug("exec get request, url: {} successresponse data: {}", url, logger.debug("exec get request, url: {} successresponse data: {}", url, result);
result);
return true; return true;
} }
} }
@ -88,5 +87,4 @@ public final class OkHttpUtil {
}); });
} }
} }
} }

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

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

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

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

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

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

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

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

@ -140,5 +140,4 @@ public class PolarisAutoServiceRegistrationTest {
doReturn(SERVICE_PROVIDER).when(polarisDiscoveryProperties).getService(); doReturn(SERVICE_PROVIDER).when(polarisDiscoveryProperties).getService();
assertThat(polarisAutoServiceRegistration.getAppName()).isEqualTo(SERVICE_PROVIDER); 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.AutoConfigurations;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.runner.WebApplicationContextRunner; 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.cloud.client.serviceregistry.AutoServiceRegistrationAutoConfiguration;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
@ -45,11 +44,11 @@ public class PolarisServiceRegistryAutoConfigurationTest {
private static NamingServer namingServer; private static NamingServer namingServer;
private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.withConfiguration( .withConfiguration(AutoConfigurations.of(
AutoConfigurations.of(PolarisContextAutoConfiguration.class, PolarisContextAutoConfiguration.class,
PolarisServiceRegistryAutoConfiguration.class, PolarisServiceRegistryAutoConfiguration.class,
PolarisDiscoveryClientConfiguration.class)) PolarisDiscoveryClientConfiguration.class))
.withPropertyValues("spring.application.name=" + SERVICE_PROVIDER) .withPropertyValues("spring.application.name=" + SERVICE_PROVIDER)
.withPropertyValues("server.port=" + PORT) .withPropertyValues("server.port=" + PORT)
.withPropertyValues("spring.cloud.polaris.address=grpc://127.0.0.1:10081"); .withPropertyValues("spring.cloud.polaris.address=grpc://127.0.0.1:10081");
@ -60,7 +59,7 @@ public class PolarisServiceRegistryAutoConfigurationTest {
} }
@AfterClass @AfterClass
public static void afterClass() throws Exception { public static void afterClass() {
if (null != namingServer) { if (null != namingServer) {
namingServer.terminate(); namingServer.terminate();
} }
@ -70,16 +69,13 @@ public class PolarisServiceRegistryAutoConfigurationTest {
public void testDefaultInitialization() { public void testDefaultInitialization() {
this.contextRunner.run(context -> { this.contextRunner.run(context -> {
assertThat(context).hasSingleBean(PolarisDiscoveryAutoConfiguration.class); assertThat(context).hasSingleBean(PolarisDiscoveryAutoConfiguration.class);
assertThat(context) assertThat(context).hasSingleBean(AutoServiceRegistrationAutoConfiguration.class);
.hasSingleBean(AutoServiceRegistrationAutoConfiguration.class);
}); });
} }
@Configuration @Configuration
@EnableAutoConfiguration @EnableAutoConfiguration
@EnableDiscoveryClient
static class PolarisServiceRegistryAutoConfiguration { static class PolarisServiceRegistryAutoConfiguration {
} }
} }

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

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

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

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

@ -34,7 +34,7 @@ import org.springframework.util.CollectionUtils;
/** /**
* resolve labels from rate limit rule. * resolve labels from rate limit rule.
* *
*@author lepdou 2022-05-13 * @author lepdou 2022-05-13
*/ */
public class RateLimitRuleLabelResolver { public class RateLimitRuleLabelResolver {

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

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

@ -44,5 +44,4 @@ public final class RateLimitConstant {
private RateLimitConstant() { private RateLimitConstant() {
} }
} }

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

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

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

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

@ -57,5 +57,4 @@ public final class QuotaCheckUtils {
"get quota failed")); "get quota failed"));
} }
} }
} }

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

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

Loading…
Cancel
Save