diff --git a/.github/workflows/codecov.yml b/.github/workflows/codecov.yml index c0ef90771..cc452e861 100644 --- a/.github/workflows/codecov.yml +++ b/.github/workflows/codecov.yml @@ -5,12 +5,17 @@ name: Codecov on: push: - branches: [ main ] + branches: + - main + - 2021.0 + - 2020.0 + - greenwich pull_request: - branches: [ main ] - -permissions: - contents: write + branches: + - main + - 2021.0 + - 2020.0 + - greenwich jobs: build: diff --git a/.github/workflows/junit_test.yml b/.github/workflows/junit_test.yml index 57cfae035..165255247 100644 --- a/.github/workflows/junit_test.yml +++ b/.github/workflows/junit_test.yml @@ -22,7 +22,7 @@ jobs: strategy: matrix: java: [ 8, 11, 17 ] - os: [ 'windows-latest', 'macos-latest', 'ubuntu-latest' ] + os: [ 'windows-latest', 'ubuntu-latest' ] runs-on: ${{ matrix.os }} diff --git a/CHANGELOG.md b/CHANGELOG.md index 51fd829ce..088bc7523 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,8 +21,20 @@ - [Fix the current limiting effect is that other requests cannot be processed when queuing at a constant speed](https://github.com/Tencent/spring-cloud-tencent/pull/316) - [Fix config file format misspell](https://github.com/Tencent/spring-cloud-tencent/pull/319) - [UT: improve test coverage for load balancer unit test](https://github.com/Tencent/spring-cloud-tencent/pull/325) -- [Feature: Optimize polaris load balancer test code format](https://github.com/Tencent/spring-cloud-tencent/pull/333) +- [optimize polaris load balancer test code format](https://github.com/Tencent/spring-cloud-tencent/pull/333) - [feat:Add GitHub action of codecov.yml.](https://github.com/Tencent/spring-cloud-tencent/pull/328) - [Feature: add spring cloud tencent logo](https://github.com/Tencent/spring-cloud-tencent/pull/329) - [Feature: Optimize static metadata manager](https://github.com/Tencent/spring-cloud-tencent/pull/327) +- [Feature: support actuator for sct core components](https://github.com/Tencent/spring-cloud-tencent/pull/343) +- [test:update junit of metadata.](https://github.com/Tencent/spring-cloud-tencent/pull/340) +- [Optimize code style & unit test case](https://github.com/Tencent/spring-cloud-tencent/pull/336) +- [rm code: Condition 'null != interceptors' is always 'true' ](https://github.com/Tencent/spring-cloud-tencent/pull/342) +- [fix: shutdown thread pool before the container closes](https://github.com/Tencent/spring-cloud-tencent/pull/353) +- [docs:update logo in README.](https://github.com/Tencent/spring-cloud-tencent/pull/358) +- [Refator JacksonUtils and JacksonUtilsTest](https://github.com/Tencent/spring-cloud-tencent/pull/365) +- [refactor:optimize project and code.](https://github.com/Tencent/spring-cloud-tencent/pull/368) +- [docs: Fix javadoc
error](https://github.com/Tencent/spring-cloud-tencent/pull/371) +- [UT: add Polaris LoadBalancer unit test](https://github.com/Tencent/spring-cloud-tencent/pull/373) +- [docs:update docs](https://github.com/Tencent/spring-cloud-tencent/pull/378) +- [docs:optimize example](https://github.com/Tencent/spring-cloud-tencent/pull/385) - [Feature: optimization refreshScope](https://github.com/Tencent/spring-cloud-tencent/pull/326) diff --git a/README-zh.md b/README-zh.md index 5724154c0..f29879285 100644 --- a/README-zh.md +++ b/README-zh.md @@ -1,4 +1,4 @@ -Spring-Cloud-Tencent-Logo +Spring-Cloud-Tencent-Logo [![Wiki](https://badgen.net/badge/icon/wiki?icon=wiki&label)](https://github.com/Tencent/spring-cloud-tencent/wiki) [![Build Status](https://github.com/Tencent/spring-cloud-tencent/actions/workflows/junit_test.yml/badge.svg)](https://github.com/Tencent/spring-cloud-tencent/actions/workflows/junit_test.yml) diff --git a/README.md b/README.md index adfa43cf9..2c2965a53 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -Spring-Cloud-Tencent-Logo +Spring-Cloud-Tencent-Logo [![Wiki](https://badgen.net/badge/icon/wiki?icon=wiki&label)](https://github.com/Tencent/spring-cloud-tencent/wiki) diff --git a/changes/changes-1.5.3.md b/changes/changes-1.5.3.md new file mode 100644 index 000000000..59766dc54 --- /dev/null +++ b/changes/changes-1.5.3.md @@ -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) diff --git a/doc/logo/1280x640-transparent.png b/doc/logo/1280x640-transparent.png new file mode 100644 index 000000000..9e722651c Binary files /dev/null and b/doc/logo/1280x640-transparent.png differ diff --git a/doc/logo/1280x640-transparent.svg b/doc/logo/1280x640-transparent.svg new file mode 100644 index 000000000..ed57761db --- /dev/null +++ b/doc/logo/1280x640-transparent.svg @@ -0,0 +1,17 @@ + + + 1280x640-svg透明 + + + + + + + + + + + + + + \ No newline at end of file diff --git a/doc/logo/1280x640-white.png b/doc/logo/1280x640-white.png new file mode 100644 index 000000000..21181cfda Binary files /dev/null and b/doc/logo/1280x640-white.png differ diff --git a/doc/logo/1280x640-white.svg b/doc/logo/1280x640-white.svg new file mode 100644 index 000000000..e09dba3f9 --- /dev/null +++ b/doc/logo/1280x640-white.svg @@ -0,0 +1,17 @@ + + + 1280x640-svg白底 + + + + + + + + + + + + + + \ No newline at end of file diff --git a/doc/logo/640x640-transparent.png b/doc/logo/640x640-transparent.png new file mode 100644 index 000000000..67e0c3f4f Binary files /dev/null and b/doc/logo/640x640-transparent.png differ diff --git a/doc/logo/640x640-transparent.svg b/doc/logo/640x640-transparent.svg new file mode 100644 index 000000000..bb45e2cd1 --- /dev/null +++ b/doc/logo/640x640-transparent.svg @@ -0,0 +1,17 @@ + + + 640x640-svg透明 + + + + + + + + + + + + + + \ No newline at end of file diff --git a/doc/logo/640x640-white.png b/doc/logo/640x640-white.png new file mode 100644 index 000000000..b4cfaab59 Binary files /dev/null and b/doc/logo/640x640-white.png differ diff --git a/doc/logo/640x640-white.svg b/doc/logo/640x640-white.svg new file mode 100644 index 000000000..f5870166a --- /dev/null +++ b/doc/logo/640x640-white.svg @@ -0,0 +1,17 @@ + + + 640x640-svg白底 + + + + + + + + + + + + + + \ No newline at end of file diff --git a/doc/logo/logo.png b/doc/logo/logo.png deleted file mode 100644 index 56598b4fc..000000000 Binary files a/doc/logo/logo.png and /dev/null differ diff --git a/doc/logo/rectangle-transparent.png b/doc/logo/rectangle-transparent.png new file mode 100644 index 000000000..772332df2 Binary files /dev/null and b/doc/logo/rectangle-transparent.png differ diff --git a/doc/logo/rectangle-transparent.svg b/doc/logo/rectangle-transparent.svg new file mode 100644 index 000000000..c4c34ccc3 --- /dev/null +++ b/doc/logo/rectangle-transparent.svg @@ -0,0 +1,15 @@ + + + 长款的 svg格式透明 + + + + Spring Cloud Tencent + + + + + + + + \ No newline at end of file diff --git a/doc/logo/rectangle-white.png b/doc/logo/rectangle-white.png new file mode 100644 index 000000000..46a1c77d9 Binary files /dev/null and b/doc/logo/rectangle-white.png differ diff --git a/doc/logo/rectangle-white.svg b/doc/logo/rectangle-white.svg new file mode 100644 index 000000000..5bc74ffb7 --- /dev/null +++ b/doc/logo/rectangle-white.svg @@ -0,0 +1,16 @@ + + + 长款的 svg 格式的白底 + + + + + Spring Cloud Tencent + + + + + + + + \ No newline at end of file diff --git a/spring-cloud-starter-tencent-metadata-transfer/src/main/java/com/tencent/cloud/metadata/config/MetadataTransferAutoConfiguration.java b/spring-cloud-starter-tencent-metadata-transfer/src/main/java/com/tencent/cloud/metadata/config/MetadataTransferAutoConfiguration.java index 589875875..ecc342288 100644 --- a/spring-cloud-starter-tencent-metadata-transfer/src/main/java/com/tencent/cloud/metadata/config/MetadataTransferAutoConfiguration.java +++ b/spring-cloud-starter-tencent-metadata-transfer/src/main/java/com/tencent/cloud/metadata/config/MetadataTransferAutoConfiguration.java @@ -68,12 +68,10 @@ public class MetadataTransferAutoConfiguration { @Bean public FilterRegistrationBean metadataServletFilterRegistrationBean( DecodeTransferMetadataServletFilter decodeTransferMetadataServletFilter) { - FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean<>( - decodeTransferMetadataServletFilter); - filterRegistrationBean.setDispatcherTypes(ASYNC, ERROR, FORWARD, INCLUDE, - REQUEST); - filterRegistrationBean - .setOrder(MetadataConstant.OrderConstant.WEB_FILTER_ORDER); + FilterRegistrationBean filterRegistrationBean = + new FilterRegistrationBean<>(decodeTransferMetadataServletFilter); + filterRegistrationBean.setDispatcherTypes(ASYNC, ERROR, FORWARD, INCLUDE, REQUEST); + filterRegistrationBean.setOrder(MetadataConstant.OrderConstant.WEB_FILTER_ORDER); return filterRegistrationBean; } @@ -158,30 +156,25 @@ public class MetadataTransferAutoConfiguration { BeanPostProcessor encodeTransferMetadataRestTemplatePostProcessor( EncodeTransferMedataRestTemplateInterceptor encodeTransferMedataRestTemplateInterceptor) { // Coping with multiple bean injection scenarios - Map beans = this.context - .getBeansOfType(RestTemplate.class); + Map beans = this.context.getBeansOfType(RestTemplate.class); // If the restTemplate has been created when the // MetadataRestTemplatePostProcessor Bean // is initialized, then manually set the interceptor. if (!CollectionUtils.isEmpty(beans)) { for (RestTemplate restTemplate : beans.values()) { - List interceptors = restTemplate - .getInterceptors(); + List interceptors = restTemplate.getInterceptors(); // Avoid setting interceptor repeatedly. - if (null != interceptors && !interceptors - .contains(encodeTransferMedataRestTemplateInterceptor)) { + if (!interceptors.contains(encodeTransferMedataRestTemplateInterceptor)) { interceptors.add(encodeTransferMedataRestTemplateInterceptor); restTemplate.setInterceptors(interceptors); } } } - return new EncodeTransferMetadataRestTemplatePostProcessor( - encodeTransferMedataRestTemplateInterceptor); + return new EncodeTransferMetadataRestTemplatePostProcessor(encodeTransferMedataRestTemplateInterceptor); } @Override - public void setApplicationContext(ApplicationContext applicationContext) - throws BeansException { + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.context = applicationContext; } @@ -204,21 +197,15 @@ public class MetadataTransferAutoConfiguration { public Object postProcessAfterInitialization(Object bean, String beanName) { if (bean instanceof RestTemplate) { RestTemplate restTemplate = (RestTemplate) bean; - List interceptors = restTemplate - .getInterceptors(); + List interceptors = restTemplate.getInterceptors(); // Avoid setting interceptor repeatedly. - if (null != interceptors && !interceptors - .contains(encodeTransferMedataRestTemplateInterceptor)) { - interceptors - .add(this.encodeTransferMedataRestTemplateInterceptor); + if (!interceptors.contains(encodeTransferMedataRestTemplateInterceptor)) { + interceptors.add(this.encodeTransferMedataRestTemplateInterceptor); restTemplate.setInterceptors(interceptors); } } return bean; } - } - } - } diff --git a/spring-cloud-starter-tencent-metadata-transfer/src/main/java/com/tencent/cloud/metadata/core/CustomTransitiveMetadataResolver.java b/spring-cloud-starter-tencent-metadata-transfer/src/main/java/com/tencent/cloud/metadata/core/CustomTransitiveMetadataResolver.java index b8645efb2..932c753b7 100644 --- a/spring-cloud-starter-tencent-metadata-transfer/src/main/java/com/tencent/cloud/metadata/core/CustomTransitiveMetadataResolver.java +++ b/spring-cloud-starter-tencent-metadata-transfer/src/main/java/com/tencent/cloud/metadata/core/CustomTransitiveMetadataResolver.java @@ -32,13 +32,16 @@ import org.springframework.util.CollectionUtils; import org.springframework.web.server.ServerWebExchange; /** - * resolve custom transitive metadata from request. - *@author lepdou 2022-05-20 + * Resolve custom transitive metadata from request. + * + * @author lepdou 2022-05-20 */ -public class CustomTransitiveMetadataResolver { +public final class CustomTransitiveMetadataResolver { private static final String TRANSITIVE_HEADER_PREFIX = "X-SCT-Metadata-Transitive-"; private static final int TRANSITIVE_HEADER_PREFIX_LENGTH = TRANSITIVE_HEADER_PREFIX.length(); + private CustomTransitiveMetadataResolver() { + } public static Map resolve(ServerWebExchange exchange) { Map result = new HashMap<>(); @@ -46,11 +49,9 @@ public class CustomTransitiveMetadataResolver { HttpHeaders headers = exchange.getRequest().getHeaders(); for (Map.Entry> entry : headers.entrySet()) { String key = entry.getKey(); - - if (StringUtils.isNotBlank(key) && - StringUtils.startsWithIgnoreCase(key, TRANSITIVE_HEADER_PREFIX) + if (StringUtils.isNotBlank(key) + && StringUtils.startsWithIgnoreCase(key, TRANSITIVE_HEADER_PREFIX) && !CollectionUtils.isEmpty(entry.getValue())) { - String sourceKey = StringUtils.substring(key, TRANSITIVE_HEADER_PREFIX_LENGTH); result.put(sourceKey, entry.getValue().get(0)); } @@ -66,10 +67,9 @@ public class CustomTransitiveMetadataResolver { while (headers.hasMoreElements()) { String key = headers.nextElement(); - if (StringUtils.isNotBlank(key) && - StringUtils.startsWithIgnoreCase(key, TRANSITIVE_HEADER_PREFIX) + if (StringUtils.isNotBlank(key) + && StringUtils.startsWithIgnoreCase(key, TRANSITIVE_HEADER_PREFIX) && StringUtils.isNotBlank(request.getHeader(key))) { - String sourceKey = StringUtils.substring(key, TRANSITIVE_HEADER_PREFIX_LENGTH); result.put(sourceKey, request.getHeader(key)); } diff --git a/spring-cloud-starter-tencent-metadata-transfer/src/main/java/com/tencent/cloud/metadata/core/DecodeTransferMetadataReactiveFilter.java b/spring-cloud-starter-tencent-metadata-transfer/src/main/java/com/tencent/cloud/metadata/core/DecodeTransferMetadataReactiveFilter.java index 3a258560e..5894d2ed7 100644 --- a/spring-cloud-starter-tencent-metadata-transfer/src/main/java/com/tencent/cloud/metadata/core/DecodeTransferMetadataReactiveFilter.java +++ b/spring-cloud-starter-tencent-metadata-transfer/src/main/java/com/tencent/cloud/metadata/core/DecodeTransferMetadataReactiveFilter.java @@ -47,8 +47,7 @@ import org.springframework.web.server.WebFilterChain; */ public class DecodeTransferMetadataReactiveFilter implements WebFilter, Ordered { - private static final Logger LOG = LoggerFactory - .getLogger(DecodeTransferMetadataReactiveFilter.class); + private static final Logger LOG = LoggerFactory.getLogger(DecodeTransferMetadataReactiveFilter.class); @Override public int getOrder() { diff --git a/spring-cloud-starter-tencent-metadata-transfer/src/main/java/com/tencent/cloud/metadata/core/DecodeTransferMetadataServletFilter.java b/spring-cloud-starter-tencent-metadata-transfer/src/main/java/com/tencent/cloud/metadata/core/DecodeTransferMetadataServletFilter.java index 10aa7b60f..2236463be 100644 --- a/spring-cloud-starter-tencent-metadata-transfer/src/main/java/com/tencent/cloud/metadata/core/DecodeTransferMetadataServletFilter.java +++ b/spring-cloud-starter-tencent-metadata-transfer/src/main/java/com/tencent/cloud/metadata/core/DecodeTransferMetadataServletFilter.java @@ -49,8 +49,7 @@ import org.springframework.web.filter.OncePerRequestFilter; @Order(MetadataConstant.OrderConstant.WEB_FILTER_ORDER) public class DecodeTransferMetadataServletFilter extends OncePerRequestFilter { - private static final Logger LOG = LoggerFactory - .getLogger(DecodeTransferMetadataServletFilter.class); + private static final Logger LOG = LoggerFactory.getLogger(DecodeTransferMetadataServletFilter.class); @Override protected void doFilterInternal(HttpServletRequest httpServletRequest, @@ -75,8 +74,7 @@ public class DecodeTransferMetadataServletFilter extends OncePerRequestFilter { private Map getInternalTransitiveMetadata(HttpServletRequest httpServletRequest) { // Get custom metadata string from http header. - String customMetadataStr = httpServletRequest - .getHeader(MetadataConstant.HeaderName.CUSTOM_METADATA); + String customMetadataStr = httpServletRequest.getHeader(MetadataConstant.HeaderName.CUSTOM_METADATA); try { if (StringUtils.hasText(customMetadataStr)) { customMetadataStr = URLDecoder.decode(customMetadataStr, StandardCharsets.UTF_8.name()); @@ -90,5 +88,4 @@ public class DecodeTransferMetadataServletFilter extends OncePerRequestFilter { // create custom metadata. return JacksonUtils.deserialize2Map(customMetadataStr); } - } diff --git a/spring-cloud-starter-tencent-metadata-transfer/src/main/java/com/tencent/cloud/metadata/core/EncodeTransferMedataFeignInterceptor.java b/spring-cloud-starter-tencent-metadata-transfer/src/main/java/com/tencent/cloud/metadata/core/EncodeTransferMedataFeignInterceptor.java index cf889d754..b361ee81b 100644 --- a/spring-cloud-starter-tencent-metadata-transfer/src/main/java/com/tencent/cloud/metadata/core/EncodeTransferMedataFeignInterceptor.java +++ b/spring-cloud-starter-tencent-metadata-transfer/src/main/java/com/tencent/cloud/metadata/core/EncodeTransferMedataFeignInterceptor.java @@ -45,8 +45,7 @@ import static com.tencent.cloud.common.constant.MetadataConstant.HeaderName.CUST */ public class EncodeTransferMedataFeignInterceptor implements RequestInterceptor, Ordered { - private static final Logger LOG = LoggerFactory - .getLogger(EncodeTransferMedataFeignInterceptor.class); + private static final Logger LOG = LoggerFactory.getLogger(EncodeTransferMedataFeignInterceptor.class); @Override public int getOrder() { diff --git a/spring-cloud-starter-tencent-metadata-transfer/src/main/java/com/tencent/cloud/metadata/core/EncodeTransferMedataRestTemplateInterceptor.java b/spring-cloud-starter-tencent-metadata-transfer/src/main/java/com/tencent/cloud/metadata/core/EncodeTransferMedataRestTemplateInterceptor.java index 9f3a7940f..92a9c8ec8 100644 --- a/spring-cloud-starter-tencent-metadata-transfer/src/main/java/com/tencent/cloud/metadata/core/EncodeTransferMedataRestTemplateInterceptor.java +++ b/spring-cloud-starter-tencent-metadata-transfer/src/main/java/com/tencent/cloud/metadata/core/EncodeTransferMedataRestTemplateInterceptor.java @@ -42,8 +42,7 @@ import org.springframework.util.CollectionUtils; * * @author Haotian Zhang */ -public class EncodeTransferMedataRestTemplateInterceptor - implements ClientHttpRequestInterceptor, Ordered { +public class EncodeTransferMedataRestTemplateInterceptor implements ClientHttpRequestInterceptor, Ordered { @Override public int getOrder() { @@ -71,5 +70,4 @@ public class EncodeTransferMedataRestTemplateInterceptor return clientHttpRequestExecution.execute(httpRequest, bytes); } - } diff --git a/spring-cloud-starter-tencent-metadata-transfer/src/main/java/com/tencent/cloud/metadata/core/EncodeTransferMedataScgFilter.java b/spring-cloud-starter-tencent-metadata-transfer/src/main/java/com/tencent/cloud/metadata/core/EncodeTransferMedataScgFilter.java index cc3aa2aa1..81745459b 100644 --- a/spring-cloud-starter-tencent-metadata-transfer/src/main/java/com/tencent/cloud/metadata/core/EncodeTransferMedataScgFilter.java +++ b/spring-cloud-starter-tencent-metadata-transfer/src/main/java/com/tencent/cloud/metadata/core/EncodeTransferMedataScgFilter.java @@ -45,8 +45,7 @@ import static org.springframework.cloud.gateway.filter.LoadBalancerClientFilter. */ public class EncodeTransferMedataScgFilter implements GlobalFilter, Ordered { - private static final int METADATA_SCG_FILTER_ORDER = LOAD_BALANCER_CLIENT_FILTER_ORDER - + 1; + private static final int METADATA_SCG_FILTER_ORDER = LOAD_BALANCER_CLIENT_FILTER_ORDER + 1; @Override public int getOrder() { @@ -59,8 +58,7 @@ public class EncodeTransferMedataScgFilter implements GlobalFilter, Ordered { ServerHttpRequest.Builder builder = exchange.getRequest().mutate(); // get metadata of current thread - MetadataContext metadataContext = exchange - .getAttribute(MetadataConstant.HeaderName.METADATA_CONTEXT); + MetadataContext metadataContext = exchange.getAttribute(MetadataConstant.HeaderName.METADATA_CONTEXT); // add new metadata and cover old if (metadataContext == null) { @@ -80,5 +78,4 @@ public class EncodeTransferMedataScgFilter implements GlobalFilter, Ordered { return chain.filter(exchange.mutate().request(builder.build()).build()); } - } diff --git a/spring-cloud-starter-tencent-metadata-transfer/src/main/java/com/tencent/cloud/metadata/core/EncodeTransferMetadataZuulFilter.java b/spring-cloud-starter-tencent-metadata-transfer/src/main/java/com/tencent/cloud/metadata/core/EncodeTransferMetadataZuulFilter.java index bb34a96f6..9d18f3e6d 100644 --- a/spring-cloud-starter-tencent-metadata-transfer/src/main/java/com/tencent/cloud/metadata/core/EncodeTransferMetadataZuulFilter.java +++ b/spring-cloud-starter-tencent-metadata-transfer/src/main/java/com/tencent/cloud/metadata/core/EncodeTransferMetadataZuulFilter.java @@ -70,13 +70,11 @@ public class EncodeTransferMetadataZuulFilter extends ZuulFilter { if (!CollectionUtils.isEmpty(customMetadata)) { String metadataStr = JacksonUtils.serialize2Json(customMetadata); try { - requestContext.addZuulRequestHeader( - MetadataConstant.HeaderName.CUSTOM_METADATA, + requestContext.addZuulRequestHeader(MetadataConstant.HeaderName.CUSTOM_METADATA, URLEncoder.encode(metadataStr, StandardCharsets.UTF_8.name())); } catch (UnsupportedEncodingException e) { - requestContext.addZuulRequestHeader( - MetadataConstant.HeaderName.CUSTOM_METADATA, metadataStr); + requestContext.addZuulRequestHeader(MetadataConstant.HeaderName.CUSTOM_METADATA, metadataStr); } } return null; diff --git a/spring-cloud-starter-tencent-metadata-transfer/src/test/java/com/tencent/cloud/metadata/config/MetadataTransferAutoConfigurationTest.java b/spring-cloud-starter-tencent-metadata-transfer/src/test/java/com/tencent/cloud/metadata/config/MetadataTransferAutoConfigurationTest.java index 87968b8b3..1e5579f90 100644 --- a/spring-cloud-starter-tencent-metadata-transfer/src/test/java/com/tencent/cloud/metadata/config/MetadataTransferAutoConfigurationTest.java +++ b/spring-cloud-starter-tencent-metadata-transfer/src/test/java/com/tencent/cloud/metadata/config/MetadataTransferAutoConfigurationTest.java @@ -55,7 +55,9 @@ public class MetadataTransferAutoConfigurationTest { Assertions.assertThat(context).hasSingleBean( EncodeTransferMedataRestTemplateInterceptor.class); Assertions.assertThat(context).hasSingleBean( - MetadataTransferAutoConfiguration.MetadataTransferRestTemplateConfig.EncodeTransferMetadataRestTemplatePostProcessor.class); + MetadataTransferAutoConfiguration + .MetadataTransferRestTemplateConfig + .EncodeTransferMetadataRestTemplatePostProcessor.class); Assertions.assertThat(context).hasSingleBean( MetadataTransferAutoConfiguration.MetadataTransferZuulFilterConfig.class); Assertions.assertThat(context) @@ -65,5 +67,4 @@ public class MetadataTransferAutoConfigurationTest { Assertions.assertThat(context).hasSingleBean(GlobalFilter.class); }); } - } diff --git a/spring-cloud-starter-tencent-metadata-transfer/src/test/java/com/tencent/cloud/metadata/CustomTransitiveMetadataResolverTest.java b/spring-cloud-starter-tencent-metadata-transfer/src/test/java/com/tencent/cloud/metadata/core/CustomTransitiveMetadataResolverTest.java similarity index 94% rename from spring-cloud-starter-tencent-metadata-transfer/src/test/java/com/tencent/cloud/metadata/CustomTransitiveMetadataResolverTest.java rename to spring-cloud-starter-tencent-metadata-transfer/src/test/java/com/tencent/cloud/metadata/core/CustomTransitiveMetadataResolverTest.java index f3fbfc4e0..9dc83bd51 100644 --- a/spring-cloud-starter-tencent-metadata-transfer/src/test/java/com/tencent/cloud/metadata/CustomTransitiveMetadataResolverTest.java +++ b/spring-cloud-starter-tencent-metadata-transfer/src/test/java/com/tencent/cloud/metadata/core/CustomTransitiveMetadataResolverTest.java @@ -13,14 +13,12 @@ * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. - * */ -package com.tencent.cloud.metadata; +package com.tencent.cloud.metadata.core; import java.util.Map; -import com.tencent.cloud.metadata.core.CustomTransitiveMetadataResolver; import org.assertj.core.api.Assertions; import org.junit.Test; @@ -29,6 +27,8 @@ import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.server.MockServerWebExchange; /** + * Test for {@link CustomTransitiveMetadataResolver}. + * * @author quan */ public class CustomTransitiveMetadataResolverTest { diff --git a/spring-cloud-starter-tencent-metadata-transfer/src/test/java/com/tencent/cloud/metadata/DecodeTransferMetadataReactiveFilterTest.java b/spring-cloud-starter-tencent-metadata-transfer/src/test/java/com/tencent/cloud/metadata/core/DecodeTransferMetadataReactiveFilterTest.java similarity index 96% rename from spring-cloud-starter-tencent-metadata-transfer/src/test/java/com/tencent/cloud/metadata/DecodeTransferMetadataReactiveFilterTest.java rename to spring-cloud-starter-tencent-metadata-transfer/src/test/java/com/tencent/cloud/metadata/core/DecodeTransferMetadataReactiveFilterTest.java index 48412d443..bbe001415 100644 --- a/spring-cloud-starter-tencent-metadata-transfer/src/test/java/com/tencent/cloud/metadata/DecodeTransferMetadataReactiveFilterTest.java +++ b/spring-cloud-starter-tencent-metadata-transfer/src/test/java/com/tencent/cloud/metadata/core/DecodeTransferMetadataReactiveFilterTest.java @@ -13,14 +13,12 @@ * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. - * */ -package com.tencent.cloud.metadata; +package com.tencent.cloud.metadata.core; import com.tencent.cloud.common.constant.MetadataConstant; import com.tencent.cloud.common.metadata.config.MetadataLocalProperties; -import com.tencent.cloud.metadata.core.DecodeTransferMetadataReactiveFilter; import org.assertj.core.api.Assertions; import org.junit.Before; import org.junit.Test; @@ -38,6 +36,8 @@ import org.springframework.web.server.WebFilterChain; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.MOCK; /** + * Test for {@link DecodeTransferMetadataReactiveFilter}. + * * @author Haotian Zhang */ @RunWith(SpringRunner.class) @@ -80,5 +80,4 @@ public class DecodeTransferMetadataReactiveFilterTest { .isEqualTo("2"); Assertions.assertThat(metadataLocalProperties.getContent().get("c")).isNull(); } - } diff --git a/spring-cloud-starter-tencent-metadata-transfer/src/test/java/com/tencent/cloud/metadata/DecodeTransferMetadataServletFilterTest.java b/spring-cloud-starter-tencent-metadata-transfer/src/test/java/com/tencent/cloud/metadata/core/DecodeTransferMetadataServletFilterTest.java similarity index 94% rename from spring-cloud-starter-tencent-metadata-transfer/src/test/java/com/tencent/cloud/metadata/DecodeTransferMetadataServletFilterTest.java rename to spring-cloud-starter-tencent-metadata-transfer/src/test/java/com/tencent/cloud/metadata/core/DecodeTransferMetadataServletFilterTest.java index 4f452ffb9..9e5389ef5 100644 --- a/spring-cloud-starter-tencent-metadata-transfer/src/test/java/com/tencent/cloud/metadata/DecodeTransferMetadataServletFilterTest.java +++ b/spring-cloud-starter-tencent-metadata-transfer/src/test/java/com/tencent/cloud/metadata/core/DecodeTransferMetadataServletFilterTest.java @@ -13,10 +13,9 @@ * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. - * */ -package com.tencent.cloud.metadata; +package com.tencent.cloud.metadata.core; import java.io.IOException; @@ -25,7 +24,6 @@ import javax.servlet.ServletException; import com.tencent.cloud.common.constant.MetadataConstant; import com.tencent.cloud.common.metadata.config.MetadataLocalProperties; -import com.tencent.cloud.metadata.core.DecodeTransferMetadataServletFilter; import org.assertj.core.api.Assertions; import org.junit.Test; import org.junit.runner.RunWith; @@ -40,6 +38,8 @@ import org.springframework.test.context.junit4.SpringRunner; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; /** + * Test for {@link DecodeTransferMetadataServletFilter}. + * * @author Haotian Zhang */ @RunWith(SpringRunner.class) @@ -68,10 +68,8 @@ public class DecodeTransferMetadataServletFilterTest { request.addHeader(MetadataConstant.HeaderName.CUSTOM_METADATA, "{\"c\": \"3\"}"); MockHttpServletResponse response = new MockHttpServletResponse(); metadataServletFilter.doFilter(request, response, filterChain); - Assertions.assertThat(metadataLocalProperties.getContent().get("a")) - .isEqualTo("1"); - Assertions.assertThat(metadataLocalProperties.getContent().get("b")) - .isEqualTo("2"); + Assertions.assertThat(metadataLocalProperties.getContent().get("a")).isEqualTo("1"); + Assertions.assertThat(metadataLocalProperties.getContent().get("b")).isEqualTo("2"); Assertions.assertThat(metadataLocalProperties.getContent().get("c")).isNull(); } @@ -79,5 +77,4 @@ public class DecodeTransferMetadataServletFilterTest { protected static class TestApplication { } - } diff --git a/spring-cloud-starter-tencent-metadata-transfer/src/test/java/com/tencent/cloud/metadata/core/intercepter/EncodeTransferMedataFeignInterceptorTest.java b/spring-cloud-starter-tencent-metadata-transfer/src/test/java/com/tencent/cloud/metadata/core/EncodeTransferMedataFeignInterceptorTest.java similarity index 89% rename from spring-cloud-starter-tencent-metadata-transfer/src/test/java/com/tencent/cloud/metadata/core/intercepter/EncodeTransferMedataFeignInterceptorTest.java rename to spring-cloud-starter-tencent-metadata-transfer/src/test/java/com/tencent/cloud/metadata/core/EncodeTransferMedataFeignInterceptorTest.java index 9d8c7ea3f..eef57ee00 100644 --- a/spring-cloud-starter-tencent-metadata-transfer/src/test/java/com/tencent/cloud/metadata/core/intercepter/EncodeTransferMedataFeignInterceptorTest.java +++ b/spring-cloud-starter-tencent-metadata-transfer/src/test/java/com/tencent/cloud/metadata/core/EncodeTransferMedataFeignInterceptorTest.java @@ -13,10 +13,9 @@ * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. - * */ -package com.tencent.cloud.metadata.core.intercepter; +package com.tencent.cloud.metadata.core; import java.io.UnsupportedEncodingException; @@ -24,7 +23,6 @@ import com.tencent.cloud.common.constant.MetadataConstant; import com.tencent.cloud.common.metadata.MetadataContext; import com.tencent.cloud.common.metadata.MetadataContextHolder; import com.tencent.cloud.common.metadata.config.MetadataLocalProperties; -import com.tencent.cloud.metadata.core.EncodeTransferMedataFeignInterceptor; import feign.RequestInterceptor; import feign.RequestTemplate; import org.assertj.core.api.Assertions; @@ -38,7 +36,6 @@ import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @@ -68,10 +65,8 @@ public class EncodeTransferMedataFeignInterceptorTest { public void testTransitiveMetadataFromApplicationConfig() { String metadata = testFeign.test(); Assertions.assertThat(metadata).isEqualTo("2"); - Assertions.assertThat(metadataLocalProperties.getContent().get("a")) - .isEqualTo("1"); - Assertions.assertThat(metadataLocalProperties.getContent().get("b")) - .isEqualTo("2"); + Assertions.assertThat(metadataLocalProperties.getContent().get("a")).isEqualTo("1"); + Assertions.assertThat(metadataLocalProperties.getContent().get("b")).isEqualTo("2"); } @SpringBootApplication @@ -80,9 +75,7 @@ public class EncodeTransferMedataFeignInterceptorTest { protected static class TestApplication { @RequestMapping("/test") - public String test( - @RequestHeader(MetadataConstant.HeaderName.CUSTOM_METADATA) String customMetadataStr) - throws UnsupportedEncodingException { + public String test() throws UnsupportedEncodingException { return MetadataContextHolder.get().getContext(MetadataContext.FRAGMENT_TRANSITIVE, "b"); } @@ -91,7 +84,6 @@ public class EncodeTransferMedataFeignInterceptorTest { @RequestMapping("/test") String test(); - } @Configuration @@ -102,9 +94,6 @@ public class EncodeTransferMedataFeignInterceptorTest { template.header(MetadataConstant.HeaderName.CUSTOM_METADATA, "{\"a\":\"11\",\"b\":\"22\",\"c\":\"33\"}"); } - } - } - } diff --git a/spring-cloud-starter-tencent-metadata-transfer/src/test/java/com/tencent/cloud/metadata/core/intercepter/EncodeTransferMedataRestTemplateInterceptorTest.java b/spring-cloud-starter-tencent-metadata-transfer/src/test/java/com/tencent/cloud/metadata/core/EncodeTransferMedataRestTemplateInterceptorTest.java similarity index 82% rename from spring-cloud-starter-tencent-metadata-transfer/src/test/java/com/tencent/cloud/metadata/core/intercepter/EncodeTransferMedataRestTemplateInterceptorTest.java rename to spring-cloud-starter-tencent-metadata-transfer/src/test/java/com/tencent/cloud/metadata/core/EncodeTransferMedataRestTemplateInterceptorTest.java index 10626e5a6..e5fe24c9c 100644 --- a/spring-cloud-starter-tencent-metadata-transfer/src/test/java/com/tencent/cloud/metadata/core/intercepter/EncodeTransferMedataRestTemplateInterceptorTest.java +++ b/spring-cloud-starter-tencent-metadata-transfer/src/test/java/com/tencent/cloud/metadata/core/EncodeTransferMedataRestTemplateInterceptorTest.java @@ -13,17 +13,14 @@ * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. - * */ -package com.tencent.cloud.metadata.core.intercepter; +package com.tencent.cloud.metadata.core; import java.io.UnsupportedEncodingException; -import com.tencent.cloud.common.constant.MetadataConstant; import com.tencent.cloud.common.metadata.MetadataContext; import com.tencent.cloud.common.metadata.MetadataContextHolder; -import com.tencent.cloud.metadata.core.EncodeTransferMedataRestTemplateInterceptor; import org.assertj.core.api.Assertions; import org.junit.Test; import org.junit.runner.RunWith; @@ -37,7 +34,6 @@ import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; @@ -52,7 +48,8 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = RANDOM_PORT, classes = EncodeTransferMedataRestTemplateInterceptorTest.TestApplication.class, - properties = { "spring.config.location = classpath:application-test.yml", "spring.main.web-application-type = reactive" }) + properties = {"spring.config.location = classpath:application-test.yml", + "spring.main.web-application-type = reactive"}) public class EncodeTransferMedataRestTemplateInterceptorTest { @Autowired @@ -66,8 +63,7 @@ public class EncodeTransferMedataRestTemplateInterceptorTest { HttpHeaders httpHeaders = new HttpHeaders(); HttpEntity httpEntity = new HttpEntity<>(httpHeaders); String metadata = restTemplate - .exchange("http://localhost:" + localServerPort + "/test", HttpMethod.GET, - httpEntity, String.class) + .exchange("http://localhost:" + localServerPort + "/test", HttpMethod.GET, httpEntity, String.class) .getBody(); Assertions.assertThat(metadata).isEqualTo("2"); } @@ -82,12 +78,8 @@ public class EncodeTransferMedataRestTemplateInterceptorTest { } @RequestMapping("/test") - public String test( - @RequestHeader(MetadataConstant.HeaderName.CUSTOM_METADATA) String customMetadataStr) - throws UnsupportedEncodingException { + public String test() throws UnsupportedEncodingException { return MetadataContextHolder.get().getContext(MetadataContext.FRAGMENT_TRANSITIVE, "b"); } - } - } diff --git a/spring-cloud-starter-tencent-metadata-transfer/src/test/java/com/tencent/cloud/metadata/core/filter/EncodeTransferMedataScgFilterTest.java b/spring-cloud-starter-tencent-metadata-transfer/src/test/java/com/tencent/cloud/metadata/core/EncodeTransferMedataScgFilterTest.java similarity index 82% rename from spring-cloud-starter-tencent-metadata-transfer/src/test/java/com/tencent/cloud/metadata/core/filter/EncodeTransferMedataScgFilterTest.java rename to spring-cloud-starter-tencent-metadata-transfer/src/test/java/com/tencent/cloud/metadata/core/EncodeTransferMedataScgFilterTest.java index bc8a6277e..51a6bd6be 100644 --- a/spring-cloud-starter-tencent-metadata-transfer/src/test/java/com/tencent/cloud/metadata/core/filter/EncodeTransferMedataScgFilterTest.java +++ b/spring-cloud-starter-tencent-metadata-transfer/src/test/java/com/tencent/cloud/metadata/core/EncodeTransferMedataScgFilterTest.java @@ -13,10 +13,9 @@ * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. - * */ -package com.tencent.cloud.metadata.core.filter; +package com.tencent.cloud.metadata.core; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; @@ -25,9 +24,7 @@ import java.util.Map; import com.tencent.cloud.common.constant.MetadataConstant; import com.tencent.cloud.common.util.JacksonUtils; -import com.tencent.cloud.metadata.core.EncodeTransferMedataScgFilter; import org.assertj.core.api.Assertions; -import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; @@ -44,12 +41,15 @@ import org.springframework.test.context.junit4.SpringRunner; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; /** + * Test for {@link EncodeTransferMedataScgFilter}. + * * @author quan */ @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = RANDOM_PORT, classes = EncodeTransferMedataScgFilterTest.TestApplication.class, - properties = { "spring.config.location = classpath:application-test.yml", "spring.main.web-application-type = reactive" }) + properties = {"spring.config.location = classpath:application-test.yml", + "spring.main.web-application-type = reactive"}) public class EncodeTransferMedataScgFilterTest { @Autowired @@ -61,14 +61,20 @@ public class EncodeTransferMedataScgFilterTest { @Test public void testTransitiveMetadataFromApplicationConfig() throws UnsupportedEncodingException { EncodeTransferMedataScgFilter filter = applicationContext.getBean(EncodeTransferMedataScgFilter.class); + + // Mock Server Http Request MockServerHttpRequest.BaseBuilder builder = MockServerHttpRequest.get(""); MockServerWebExchange exchange = MockServerWebExchange.from(builder); filter.filter(exchange, chain); - String metadataStr = exchange.getRequest().getHeaders().getFirst(MetadataConstant.HeaderName.CUSTOM_METADATA); - String decode = URLDecoder.decode(metadataStr, StandardCharsets.UTF_8.name()); + + // Check metadata str + String metadata = exchange.getRequest().getHeaders().getFirst(MetadataConstant.HeaderName.CUSTOM_METADATA); + Assertions.assertThat(metadata).isNotNull(); + + String decode = URLDecoder.decode(metadata, StandardCharsets.UTF_8.name()); Map transitiveMap = JacksonUtils.deserialize2Map(decode); Assertions.assertThat(transitiveMap.size()).isEqualTo(1); - Assert.assertEquals(transitiveMap.get("b"), "2"); + Assertions.assertThat(transitiveMap.get("b")).isEqualTo("2"); } @SpringBootApplication diff --git a/spring-cloud-starter-tencent-metadata-transfer/src/test/java/com/tencent/cloud/metadata/core/filter/EncodeTransferMetadataZuulFilterTest.java b/spring-cloud-starter-tencent-metadata-transfer/src/test/java/com/tencent/cloud/metadata/core/EncodeTransferMetadataZuulFilterTest.java similarity index 82% rename from spring-cloud-starter-tencent-metadata-transfer/src/test/java/com/tencent/cloud/metadata/core/filter/EncodeTransferMetadataZuulFilterTest.java rename to spring-cloud-starter-tencent-metadata-transfer/src/test/java/com/tencent/cloud/metadata/core/EncodeTransferMetadataZuulFilterTest.java index 7cb159e84..5b36c2693 100644 --- a/spring-cloud-starter-tencent-metadata-transfer/src/test/java/com/tencent/cloud/metadata/core/filter/EncodeTransferMetadataZuulFilterTest.java +++ b/spring-cloud-starter-tencent-metadata-transfer/src/test/java/com/tencent/cloud/metadata/core/EncodeTransferMetadataZuulFilterTest.java @@ -16,7 +16,7 @@ * */ -package com.tencent.cloud.metadata.core.filter; +package com.tencent.cloud.metadata.core; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; @@ -26,9 +26,7 @@ import java.util.Map; import com.netflix.zuul.context.RequestContext; import com.tencent.cloud.common.constant.MetadataConstant; import com.tencent.cloud.common.util.JacksonUtils; -import com.tencent.cloud.metadata.core.EncodeTransferMetadataZuulFilter; import org.assertj.core.api.Assertions; -import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -43,20 +41,21 @@ import org.springframework.test.context.junit4.SpringRunner; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; /** + * Test for {@link EncodeTransferMetadataZuulFilter}. + * * @author quan */ @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = RANDOM_PORT, classes = EncodeTransferMetadataZuulFilterTest.TestApplication.class, - properties = { "spring.config.location = classpath:application-test.yml", "spring.main.web-application-type = reactive" }) - + properties = {"spring.config.location = classpath:application-test.yml", + "spring.main.web-application-type = reactive"}) public class EncodeTransferMetadataZuulFilterTest { + private final MockMultipartHttpServletRequest request = new MockMultipartHttpServletRequest(); @Autowired private ApplicationContext applicationContext; - private MockMultipartHttpServletRequest request = new MockMultipartHttpServletRequest(); - @Before public void init() { RequestContext ctx = RequestContext.getCurrentContext(); @@ -70,11 +69,13 @@ public class EncodeTransferMetadataZuulFilterTest { filter.run(); final RequestContext ctx = RequestContext.getCurrentContext(); Map zuulRequestHeaders = ctx.getZuulRequestHeaders(); - String metaData = zuulRequestHeaders.get(MetadataConstant.HeaderName.CUSTOM_METADATA.toLowerCase()); - String decode = URLDecoder.decode(metaData, StandardCharsets.UTF_8.name()); + String metadata = zuulRequestHeaders.get(MetadataConstant.HeaderName.CUSTOM_METADATA.toLowerCase()); + Assertions.assertThat(metadata).isNotNull(); + + String decode = URLDecoder.decode(metadata, StandardCharsets.UTF_8.name()); Map transitiveMap = JacksonUtils.deserialize2Map(decode); Assertions.assertThat(transitiveMap.size()).isEqualTo(1); - Assert.assertEquals(transitiveMap.get("b"), "2"); + Assertions.assertThat(transitiveMap.get("b")).isEqualTo("2"); } @SpringBootApplication diff --git a/spring-cloud-starter-tencent-polaris-circuitbreaker/pom.xml b/spring-cloud-starter-tencent-polaris-circuitbreaker/pom.xml index 5c8c0d957..80bb8a22a 100644 --- a/spring-cloud-starter-tencent-polaris-circuitbreaker/pom.xml +++ b/spring-cloud-starter-tencent-polaris-circuitbreaker/pom.xml @@ -102,6 +102,12 @@ test + + org.springframework.boot + spring-boot-starter-web + test + + org.springframework.boot spring-boot-starter-test diff --git a/spring-cloud-starter-tencent-polaris-circuitbreaker/src/main/java/com/tencent/cloud/polaris/circuitbreaker/config/PolarisCircuitBreakerBootstrapConfiguration.java b/spring-cloud-starter-tencent-polaris-circuitbreaker/src/main/java/com/tencent/cloud/polaris/circuitbreaker/config/PolarisCircuitBreakerBootstrapConfiguration.java index 393c0ea7d..6fdc71e61 100644 --- a/spring-cloud-starter-tencent-polaris-circuitbreaker/src/main/java/com/tencent/cloud/polaris/circuitbreaker/config/PolarisCircuitBreakerBootstrapConfiguration.java +++ b/spring-cloud-starter-tencent-polaris-circuitbreaker/src/main/java/com/tencent/cloud/polaris/circuitbreaker/config/PolarisCircuitBreakerBootstrapConfiguration.java @@ -66,7 +66,5 @@ public class PolarisCircuitBreakerBootstrapConfiguration { public int getOrder() { return ContextConstant.ModifierOrder.CIRCUIT_BREAKER_ORDER; } - } - } diff --git a/spring-cloud-starter-tencent-polaris-circuitbreaker/src/main/java/com/tencent/cloud/polaris/circuitbreaker/config/PolarisFeignClientAutoConfiguration.java b/spring-cloud-starter-tencent-polaris-circuitbreaker/src/main/java/com/tencent/cloud/polaris/circuitbreaker/config/PolarisFeignClientAutoConfiguration.java index a1f50a3df..baad28432 100644 --- a/spring-cloud-starter-tencent-polaris-circuitbreaker/src/main/java/com/tencent/cloud/polaris/circuitbreaker/config/PolarisFeignClientAutoConfiguration.java +++ b/spring-cloud-starter-tencent-polaris-circuitbreaker/src/main/java/com/tencent/cloud/polaris/circuitbreaker/config/PolarisFeignClientAutoConfiguration.java @@ -40,7 +40,8 @@ import static org.springframework.core.Ordered.HIGHEST_PRECEDENCE; * * @author Haotian Zhang */ -@ConditionalOnProperty(value = "spring.cloud.polaris.circuitbreaker.enabled", havingValue = "true", matchIfMissing = true) +@ConditionalOnProperty(value = "spring.cloud.polaris.circuitbreaker.enabled", + havingValue = "true", matchIfMissing = true) @Configuration(proxyBeanMethods = false) @ConditionalOnClass(name = "org.springframework.cloud.openfeign.FeignAutoConfiguration") @AutoConfigureAfter(PolarisContextAutoConfiguration.class) @@ -57,5 +58,4 @@ public class PolarisFeignClientAutoConfiguration { public PolarisFeignBeanPostProcessor polarisFeignBeanPostProcessor(ConsumerAPI consumerAPI) { return new PolarisFeignBeanPostProcessor(consumerAPI); } - } diff --git a/spring-cloud-starter-tencent-polaris-circuitbreaker/src/main/java/com/tencent/cloud/polaris/circuitbreaker/config/PolarisRestTemplateAutoConfiguration.java b/spring-cloud-starter-tencent-polaris-circuitbreaker/src/main/java/com/tencent/cloud/polaris/circuitbreaker/config/PolarisRestTemplateAutoConfiguration.java index d537de32e..207f1651d 100644 --- a/spring-cloud-starter-tencent-polaris-circuitbreaker/src/main/java/com/tencent/cloud/polaris/circuitbreaker/config/PolarisRestTemplateAutoConfiguration.java +++ b/spring-cloud-starter-tencent-polaris-circuitbreaker/src/main/java/com/tencent/cloud/polaris/circuitbreaker/config/PolarisRestTemplateAutoConfiguration.java @@ -32,9 +32,9 @@ import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate; /** - * @author : wh - * @date : 2022/6/21 21:34 - * @description: Auto configuration PolarisRestTemplateAutoConfiguration + * Auto configuration PolarisRestTemplateAutoConfiguration . + * + * @author wh 2022/6/21 */ @ConditionalOnProperty(value = "spring.cloud.polaris.circuitbreaker.enabled", havingValue = "true", matchIfMissing = true) @@ -44,13 +44,15 @@ public class PolarisRestTemplateAutoConfiguration { @Bean @ConditionalOnBean(RestTemplate.class) - public PolarisRestTemplateResponseErrorHandler polarisRestTemplateResponseErrorHandler(ConsumerAPI consumerAPI, @Autowired(required = false) PolarisResponseErrorHandler polarisResponseErrorHandler) { + public PolarisRestTemplateResponseErrorHandler polarisRestTemplateResponseErrorHandler( + ConsumerAPI consumerAPI, @Autowired(required = false) PolarisResponseErrorHandler polarisResponseErrorHandler) { return new PolarisRestTemplateResponseErrorHandler(consumerAPI, polarisResponseErrorHandler); } @Bean @ConditionalOnBean(RestTemplate.class) - public PolarisRestTemplateModifier polarisRestTemplateBeanPostProcessor(PolarisRestTemplateResponseErrorHandler restTemplateResponseErrorHandler) { + public PolarisRestTemplateModifier polarisRestTemplateBeanPostProcessor( + PolarisRestTemplateResponseErrorHandler restTemplateResponseErrorHandler) { return new PolarisRestTemplateModifier(restTemplateResponseErrorHandler); } } diff --git a/spring-cloud-starter-tencent-polaris-circuitbreaker/src/main/java/com/tencent/cloud/polaris/circuitbreaker/feign/PolarisFeignBeanPostProcessor.java b/spring-cloud-starter-tencent-polaris-circuitbreaker/src/main/java/com/tencent/cloud/polaris/circuitbreaker/feign/PolarisFeignBeanPostProcessor.java index 619815795..ea8242587 100644 --- a/spring-cloud-starter-tencent-polaris-circuitbreaker/src/main/java/com/tencent/cloud/polaris/circuitbreaker/feign/PolarisFeignBeanPostProcessor.java +++ b/spring-cloud-starter-tencent-polaris-circuitbreaker/src/main/java/com/tencent/cloud/polaris/circuitbreaker/feign/PolarisFeignBeanPostProcessor.java @@ -55,7 +55,8 @@ public class PolarisFeignBeanPostProcessor implements BeanPostProcessor, BeanFac if (bean instanceof LoadBalancerFeignClient) { LoadBalancerFeignClient client = ((LoadBalancerFeignClient) bean); return new PolarisLoadBalancerFeignClient( - createPolarisFeignClient(client.getDelegate()), factory(), + createPolarisFeignClient(client.getDelegate()), + factory(), clientFactory()); } if (bean instanceof FeignBlockingLoadBalancerClient) { @@ -91,5 +92,4 @@ public class PolarisFeignBeanPostProcessor implements BeanPostProcessor, BeanFac SpringClientFactory clientFactory() { return this.factory.getBean(SpringClientFactory.class); } - } diff --git a/spring-cloud-starter-tencent-polaris-circuitbreaker/src/main/java/com/tencent/cloud/polaris/circuitbreaker/feign/PolarisFeignBlockingLoadBalancerClient.java b/spring-cloud-starter-tencent-polaris-circuitbreaker/src/main/java/com/tencent/cloud/polaris/circuitbreaker/feign/PolarisFeignBlockingLoadBalancerClient.java index 4cf8780c1..feea51242 100644 --- a/spring-cloud-starter-tencent-polaris-circuitbreaker/src/main/java/com/tencent/cloud/polaris/circuitbreaker/feign/PolarisFeignBlockingLoadBalancerClient.java +++ b/spring-cloud-starter-tencent-polaris-circuitbreaker/src/main/java/com/tencent/cloud/polaris/circuitbreaker/feign/PolarisFeignBlockingLoadBalancerClient.java @@ -32,5 +32,4 @@ public class PolarisFeignBlockingLoadBalancerClient extends FeignBlockingLoadBal public PolarisFeignBlockingLoadBalancerClient(Client delegate, BlockingLoadBalancerClient loadBalancerClient) { super(delegate, loadBalancerClient); } - } diff --git a/spring-cloud-starter-tencent-polaris-circuitbreaker/src/main/java/com/tencent/cloud/polaris/circuitbreaker/feign/PolarisFeignClient.java b/spring-cloud-starter-tencent-polaris-circuitbreaker/src/main/java/com/tencent/cloud/polaris/circuitbreaker/feign/PolarisFeignClient.java index dc49566f2..0c8551404 100644 --- a/spring-cloud-starter-tencent-polaris-circuitbreaker/src/main/java/com/tencent/cloud/polaris/circuitbreaker/feign/PolarisFeignClient.java +++ b/spring-cloud-starter-tencent-polaris-circuitbreaker/src/main/java/com/tencent/cloud/polaris/circuitbreaker/feign/PolarisFeignClient.java @@ -43,7 +43,6 @@ import static feign.Util.checkNotNull; */ public class PolarisFeignClient implements Client { - private static final Logger LOG = LoggerFactory.getLogger(PolarisFeignClient.class); private final Client delegate; @@ -61,7 +60,7 @@ public class PolarisFeignClient implements Client { try { Response response = delegate.execute(request, options); // HTTP code greater than 500 is an exception - if (response.status() >= 500) { + if (response.status() > 500) { resultRequest.setRetStatus(RetStatus.RetFail); } LOG.debug("Will report result of {}. Request=[{}]. Response=[{}].", diff --git a/spring-cloud-starter-tencent-polaris-circuitbreaker/src/main/java/com/tencent/cloud/polaris/circuitbreaker/feign/PolarisLoadBalancerFeignClient.java b/spring-cloud-starter-tencent-polaris-circuitbreaker/src/main/java/com/tencent/cloud/polaris/circuitbreaker/feign/PolarisLoadBalancerFeignClient.java index 41e4a608f..f8518470d 100644 --- a/spring-cloud-starter-tencent-polaris-circuitbreaker/src/main/java/com/tencent/cloud/polaris/circuitbreaker/feign/PolarisLoadBalancerFeignClient.java +++ b/spring-cloud-starter-tencent-polaris-circuitbreaker/src/main/java/com/tencent/cloud/polaris/circuitbreaker/feign/PolarisLoadBalancerFeignClient.java @@ -30,10 +30,8 @@ import org.springframework.cloud.openfeign.ribbon.LoadBalancerFeignClient; */ public class PolarisLoadBalancerFeignClient extends LoadBalancerFeignClient { - public PolarisLoadBalancerFeignClient(Client delegate, - CachingSpringLoadBalancerFactory lbClientFactory, + public PolarisLoadBalancerFeignClient(Client delegate, CachingSpringLoadBalancerFactory lbClientFactory, SpringClientFactory clientFactory) { super(delegate, lbClientFactory, clientFactory); } - } diff --git a/spring-cloud-starter-tencent-polaris-circuitbreaker/src/main/java/com/tencent/cloud/polaris/circuitbreaker/resttemplate/PolarisResponseErrorHandler.java b/spring-cloud-starter-tencent-polaris-circuitbreaker/src/main/java/com/tencent/cloud/polaris/circuitbreaker/resttemplate/PolarisResponseErrorHandler.java index 5ddd1e6aa..3c690b1cc 100644 --- a/spring-cloud-starter-tencent-polaris-circuitbreaker/src/main/java/com/tencent/cloud/polaris/circuitbreaker/resttemplate/PolarisResponseErrorHandler.java +++ b/spring-cloud-starter-tencent-polaris-circuitbreaker/src/main/java/com/tencent/cloud/polaris/circuitbreaker/resttemplate/PolarisResponseErrorHandler.java @@ -20,9 +20,9 @@ package com.tencent.cloud.polaris.circuitbreaker.resttemplate; import org.springframework.web.client.ResponseErrorHandler; /** - * @author : wh - * @date : 2022/6/21 19:12 - * @description: errorHandler {@link ResponseErrorHandler} + * Polaris Response Error Handler Definition Of {@link ResponseErrorHandler}. + * + * @author wh 2022/6/21 */ public interface PolarisResponseErrorHandler extends ResponseErrorHandler { diff --git a/spring-cloud-starter-tencent-polaris-circuitbreaker/src/main/java/com/tencent/cloud/polaris/circuitbreaker/resttemplate/PolarisRestTemplateModifier.java b/spring-cloud-starter-tencent-polaris-circuitbreaker/src/main/java/com/tencent/cloud/polaris/circuitbreaker/resttemplate/PolarisRestTemplateModifier.java index bd43913f4..6fd56e582 100644 --- a/spring-cloud-starter-tencent-polaris-circuitbreaker/src/main/java/com/tencent/cloud/polaris/circuitbreaker/resttemplate/PolarisRestTemplateModifier.java +++ b/spring-cloud-starter-tencent-polaris-circuitbreaker/src/main/java/com/tencent/cloud/polaris/circuitbreaker/resttemplate/PolarisRestTemplateModifier.java @@ -28,16 +28,16 @@ import org.springframework.util.ObjectUtils; import org.springframework.web.client.RestTemplate; /** - * @author : wh - * @date : 2022/6/21 21:20 - * @description: auto configuration RestTemplate Find the RestTemplate bean annotated with {@link LoadBalanced} and replace {@link org.springframework.web.client.ResponseErrorHandler} - * with {@link PolarisRestTemplateResponseErrorHandler} + * Auto configuration RestTemplate, Find the RestTemplate bean annotated with {@link LoadBalanced}, + * then replace {@link org.springframework.web.client.ResponseErrorHandler} + * with {@link PolarisRestTemplateResponseErrorHandler} . + * + * @author wh 2022/6/21 */ public class PolarisRestTemplateModifier implements ApplicationContextAware, SmartInitializingSingleton { - private ApplicationContext applicationContext; - private final PolarisRestTemplateResponseErrorHandler polarisRestTemplateResponseErrorHandler; + private ApplicationContext applicationContext; public PolarisRestTemplateModifier(PolarisRestTemplateResponseErrorHandler polarisRestTemplateResponseErrorHandler) { this.polarisRestTemplateResponseErrorHandler = polarisRestTemplateResponseErrorHandler; diff --git a/spring-cloud-starter-tencent-polaris-circuitbreaker/src/main/java/com/tencent/cloud/polaris/circuitbreaker/resttemplate/PolarisRestTemplateResponseErrorHandler.java b/spring-cloud-starter-tencent-polaris-circuitbreaker/src/main/java/com/tencent/cloud/polaris/circuitbreaker/resttemplate/PolarisRestTemplateResponseErrorHandler.java index e6e003d90..4adf0bac2 100644 --- a/spring-cloud-starter-tencent-polaris-circuitbreaker/src/main/java/com/tencent/cloud/polaris/circuitbreaker/resttemplate/PolarisRestTemplateResponseErrorHandler.java +++ b/spring-cloud-starter-tencent-polaris-circuitbreaker/src/main/java/com/tencent/cloud/polaris/circuitbreaker/resttemplate/PolarisRestTemplateResponseErrorHandler.java @@ -29,42 +29,44 @@ import com.tencent.polaris.api.core.ConsumerAPI; import com.tencent.polaris.api.pojo.RetStatus; import com.tencent.polaris.api.pojo.ServiceKey; import com.tencent.polaris.api.rpc.ServiceCallResult; -import com.tencent.polaris.api.utils.StringUtils; +import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpMethod; import org.springframework.http.client.ClientHttpResponse; +import org.springframework.lang.NonNull; import org.springframework.web.client.ResponseErrorHandler; /** - * @author : wh - * @date : 2022/6/21 17:25 - * @description: Extend ResponseErrorHandler to get request information + * Extend ResponseErrorHandler to get request information. + * + * @author wh 2022/6/21 */ public class PolarisRestTemplateResponseErrorHandler implements ResponseErrorHandler { private static final Logger LOG = LoggerFactory.getLogger(PolarisRestTemplateResponseErrorHandler.class); - private static final String FileName = "connection"; + private static final String FIELD_NAME = "connection"; private final ConsumerAPI consumerAPI; private final PolarisResponseErrorHandler polarisResponseErrorHandler; - public PolarisRestTemplateResponseErrorHandler(ConsumerAPI consumerAPI, PolarisResponseErrorHandler polarisResponseErrorHandler) { + public PolarisRestTemplateResponseErrorHandler(ConsumerAPI consumerAPI, + PolarisResponseErrorHandler polarisResponseErrorHandler) { this.consumerAPI = consumerAPI; this.polarisResponseErrorHandler = polarisResponseErrorHandler; } @Override - public boolean hasError(ClientHttpResponse response) { + public boolean hasError(@NonNull ClientHttpResponse response) { return true; } @Override - public void handleError(ClientHttpResponse response) throws IOException { + public void handleError(@NonNull ClientHttpResponse response) throws IOException { if (Objects.nonNull(polarisResponseErrorHandler)) { if (polarisResponseErrorHandler.hasError(response)) { polarisResponseErrorHandler.handleError(response); @@ -72,12 +74,23 @@ public class PolarisRestTemplateResponseErrorHandler implements ResponseErrorHan } } - public void handleError(URI url, HttpMethod method, ClientHttpResponse response) throws IOException { - ServiceCallResult resultRequest = null; + @Override + public void handleError(@NonNull URI url, @NonNull HttpMethod method, @NonNull ClientHttpResponse response) + throws IOException { + ServiceCallResult resultRequest = createServiceCallResult(url); try { - resultRequest = builderServiceCallResult(url, response); + HttpURLConnection connection = (HttpURLConnection) ReflectionUtils.getFieldValue(response, FIELD_NAME); + if (connection != null) { + URL realURL = connection.getURL(); + resultRequest.setHost(realURL.getHost()); + resultRequest.setPort(realURL.getPort()); + } + + if (response.getStatusCode().value() > 500) { + resultRequest.setRetStatus(RetStatus.RetFail); + } } - catch (IOException e) { + catch (Exception e) { LOG.error("Will report response of {} url {}", response, url, e); throw e; } @@ -86,7 +99,7 @@ public class PolarisRestTemplateResponseErrorHandler implements ResponseErrorHan } } - private ServiceCallResult builderServiceCallResult(URI uri, ClientHttpResponse response) throws IOException { + private ServiceCallResult createServiceCallResult(URI uri) { ServiceCallResult resultRequest = new ServiceCallResult(); String serviceName = uri.getHost(); resultRequest.setService(serviceName); @@ -98,14 +111,6 @@ public class PolarisRestTemplateResponseErrorHandler implements ResponseErrorHan if (StringUtils.isNotBlank(sourceNamespace) && StringUtils.isNotBlank(sourceService)) { resultRequest.setCallerService(new ServiceKey(sourceNamespace, sourceService)); } - HttpURLConnection connection = (HttpURLConnection) ReflectionUtils.getFieldValue(response, FileName); - URL url = connection.getURL(); - resultRequest.setHost(url.getHost()); - resultRequest.setPort(url.getPort()); - if (response.getStatusCode().value() > 500) { - resultRequest.setRetStatus(RetStatus.RetFail); - } return resultRequest; } - } diff --git a/spring-cloud-starter-tencent-polaris-circuitbreaker/src/test/java/com/tencent/cloud/polaris/circuitbreaker/PolarisCircuitBreakerBootstrapConfigurationTest.java b/spring-cloud-starter-tencent-polaris-circuitbreaker/src/test/java/com/tencent/cloud/polaris/circuitbreaker/PolarisCircuitBreakerBootstrapConfigurationTest.java index a5bd4f2e6..e29c4a76f 100644 --- a/spring-cloud-starter-tencent-polaris-circuitbreaker/src/test/java/com/tencent/cloud/polaris/circuitbreaker/PolarisCircuitBreakerBootstrapConfigurationTest.java +++ b/spring-cloud-starter-tencent-polaris-circuitbreaker/src/test/java/com/tencent/cloud/polaris/circuitbreaker/PolarisCircuitBreakerBootstrapConfigurationTest.java @@ -32,14 +32,14 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class PolarisCircuitBreakerBootstrapConfigurationTest { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(PolarisCircuitBreakerBootstrapConfiguration.class)) + .withConfiguration(AutoConfigurations.of(PolarisCircuitBreakerBootstrapConfiguration.class)) .withPropertyValues("spring.cloud.polaris.circuitbreaker.enabled=true"); @Test public void testDefaultInitialization() { this.contextRunner.run(context -> { - assertThat(context).hasSingleBean(PolarisCircuitBreakerBootstrapConfiguration.CircuitBreakerConfigModifier.class); + assertThat(context).hasSingleBean( + PolarisCircuitBreakerBootstrapConfiguration.CircuitBreakerConfigModifier.class); }); } } diff --git a/spring-cloud-starter-tencent-polaris-circuitbreaker/src/test/java/com/tencent/cloud/polaris/circuitbreaker/PolarisFeignClientAutoConfigurationTest.java b/spring-cloud-starter-tencent-polaris-circuitbreaker/src/test/java/com/tencent/cloud/polaris/circuitbreaker/PolarisFeignClientAutoConfigurationTest.java index 682b99522..94a84ed43 100644 --- a/spring-cloud-starter-tencent-polaris-circuitbreaker/src/test/java/com/tencent/cloud/polaris/circuitbreaker/PolarisFeignClientAutoConfigurationTest.java +++ b/spring-cloud-starter-tencent-polaris-circuitbreaker/src/test/java/com/tencent/cloud/polaris/circuitbreaker/PolarisFeignClientAutoConfigurationTest.java @@ -36,10 +36,9 @@ import static org.assertj.core.api.Assertions.assertThat; public class PolarisFeignClientAutoConfigurationTest { private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of( - PolarisContextAutoConfiguration.class, - PolarisFeignClientAutoConfiguration.class)) + .withConfiguration(AutoConfigurations.of( + PolarisContextAutoConfiguration.class, + PolarisFeignClientAutoConfiguration.class)) .withPropertyValues("spring.cloud.polaris.circuitbreaker.enabled=true"); @Test @@ -49,5 +48,4 @@ public class PolarisFeignClientAutoConfigurationTest { assertThat(context).hasSingleBean(PolarisFeignBeanPostProcessor.class); }); } - } diff --git a/spring-cloud-starter-tencent-polaris-circuitbreaker/src/test/java/com/tencent/cloud/polaris/circuitbreaker/PolarisRestTemplateAutoConfigurationTest.java b/spring-cloud-starter-tencent-polaris-circuitbreaker/src/test/java/com/tencent/cloud/polaris/circuitbreaker/PolarisRestTemplateAutoConfigurationTest.java new file mode 100644 index 000000000..2707bc87f --- /dev/null +++ b/spring-cloud-starter-tencent-polaris-circuitbreaker/src/test/java/com/tencent/cloud/polaris/circuitbreaker/PolarisRestTemplateAutoConfigurationTest.java @@ -0,0 +1,70 @@ +/* + * Tencent is pleased to support the open source community by making Spring Cloud Tencent available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + */ + +package com.tencent.cloud.polaris.circuitbreaker; + +import com.tencent.cloud.polaris.circuitbreaker.config.PolarisRestTemplateAutoConfiguration; +import com.tencent.cloud.polaris.circuitbreaker.resttemplate.PolarisRestTemplateModifier; +import com.tencent.cloud.polaris.circuitbreaker.resttemplate.PolarisRestTemplateResponseErrorHandler; +import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration; +import org.junit.Test; + +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.autoconfigure.AutoConfigureBefore; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.test.context.runner.WebApplicationContextRunner; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.client.RestTemplate; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Test For {@link PolarisRestTemplateAutoConfiguration} . + * + * @author Palmer Xu 2022-06-28 + */ +public class PolarisRestTemplateAutoConfigurationTest { + + private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() + .withConfiguration(AutoConfigurations.of( + PolarisRestTemplateAutoConfigurationTester.class, + PolarisContextAutoConfiguration.class, + PolarisRestTemplateAutoConfiguration.class)) + .withPropertyValues("spring.cloud.polaris.circuitbreaker.enabled=true"); + + @Test + public void testInitialization() { + this.contextRunner + .run(context -> { + assertThat(context).hasSingleBean(PolarisRestTemplateModifier.class); + assertThat(context).hasSingleBean(PolarisRestTemplateResponseErrorHandler.class); + }); + } + + @Configuration + @EnableAutoConfiguration + @AutoConfigureBefore(PolarisRestTemplateAutoConfiguration.class) + static class PolarisRestTemplateAutoConfigurationTester { + + @Bean + RestTemplate restTemplate() { + return new RestTemplate(); + } + } +} diff --git a/spring-cloud-starter-tencent-polaris-circuitbreaker/src/test/java/com/tencent/cloud/polaris/circuitbreaker/feign/PolarisFeignClientTest.java b/spring-cloud-starter-tencent-polaris-circuitbreaker/src/test/java/com/tencent/cloud/polaris/circuitbreaker/feign/PolarisFeignClientTest.java index 993eedc58..8d21f6a1e 100644 --- a/spring-cloud-starter-tencent-polaris-circuitbreaker/src/test/java/com/tencent/cloud/polaris/circuitbreaker/feign/PolarisFeignClientTest.java +++ b/spring-cloud-starter-tencent-polaris-circuitbreaker/src/test/java/com/tencent/cloud/polaris/circuitbreaker/feign/PolarisFeignClientTest.java @@ -73,7 +73,8 @@ public class PolarisFeignClientTest { } try { - assertThat(new PolarisFeignClient(mock(Client.class), mock(ConsumerAPI.class))).isInstanceOf(PolarisFeignClient.class); + assertThat(new PolarisFeignClient(mock(Client.class), mock(ConsumerAPI.class))) + .isInstanceOf(PolarisFeignClient.class); } catch (Throwable e) { fail("Exception encountered.", e); @@ -90,7 +91,7 @@ public class PolarisFeignClientTest { return Response.builder().request(request).status(200).build(); } else if (request.httpMethod().equals(Request.HttpMethod.POST)) { - return Response.builder().request(request).status(500).build(); + return Response.builder().request(request).status(502).build(); } throw new IOException("Mock exception."); }).when(delegate).execute(any(Request.class), nullable(Request.Options.class)); @@ -113,10 +114,10 @@ public class PolarisFeignClientTest { Maps.newHashMap(), null, requestTemplate), null); assertThat(response.status()).isEqualTo(200); - // 200 + // 502 response = polarisFeignClient.execute(Request.create(Request.HttpMethod.POST, "http://localhost:8080/test", Maps.newHashMap(), null, requestTemplate), null); - assertThat(response.status()).isEqualTo(500); + assertThat(response.status()).isEqualTo(502); // Exception try { diff --git a/spring-cloud-starter-tencent-polaris-circuitbreaker/src/test/java/com/tencent/cloud/polaris/circuitbreaker/PolarisRestTemplateResponseErrorHandlerTest.java b/spring-cloud-starter-tencent-polaris-circuitbreaker/src/test/java/com/tencent/cloud/polaris/circuitbreaker/resttemplate/PolarisRestTemplateResponseErrorHandlerTest.java similarity index 90% rename from spring-cloud-starter-tencent-polaris-circuitbreaker/src/test/java/com/tencent/cloud/polaris/circuitbreaker/PolarisRestTemplateResponseErrorHandlerTest.java rename to spring-cloud-starter-tencent-polaris-circuitbreaker/src/test/java/com/tencent/cloud/polaris/circuitbreaker/resttemplate/PolarisRestTemplateResponseErrorHandlerTest.java index 5daf30bc6..6cb630e37 100644 --- a/spring-cloud-starter-tencent-polaris-circuitbreaker/src/test/java/com/tencent/cloud/polaris/circuitbreaker/PolarisRestTemplateResponseErrorHandlerTest.java +++ b/spring-cloud-starter-tencent-polaris-circuitbreaker/src/test/java/com/tencent/cloud/polaris/circuitbreaker/resttemplate/PolarisRestTemplateResponseErrorHandlerTest.java @@ -15,14 +15,13 @@ * specific language governing permissions and limitations under the License. */ -package com.tencent.cloud.polaris.circuitbreaker; +package com.tencent.cloud.polaris.circuitbreaker.resttemplate; import java.net.HttpURLConnection; import java.net.URI; import java.net.URL; -import com.tencent.cloud.polaris.circuitbreaker.resttemplate.PolarisRestTemplateResponseErrorHandler; import com.tencent.polaris.api.core.ConsumerAPI; import org.junit.Test; import org.junit.runner.RunWith; @@ -36,9 +35,9 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** - * @author : wh - * @date : 2022/6/22 09:00 - * @description: Test for {@link PolarisRestTemplateResponseErrorHandler}. + * Test For {@link PolarisRestTemplateResponseErrorHandler}. + * + * @author wh 2022/6/22 */ @RunWith(SpringRunner.class) @SpringBootTest(classes = PolarisRestTemplateResponseErrorHandlerTest.TestApplication.class, diff --git a/spring-cloud-starter-tencent-polaris-circuitbreaker/src/test/java/com/tencent/cloud/polaris/circuitbreaker/SimpleClientHttpResponseTest.java b/spring-cloud-starter-tencent-polaris-circuitbreaker/src/test/java/com/tencent/cloud/polaris/circuitbreaker/resttemplate/SimpleClientHttpResponseTest.java similarity index 93% rename from spring-cloud-starter-tencent-polaris-circuitbreaker/src/test/java/com/tencent/cloud/polaris/circuitbreaker/SimpleClientHttpResponseTest.java rename to spring-cloud-starter-tencent-polaris-circuitbreaker/src/test/java/com/tencent/cloud/polaris/circuitbreaker/resttemplate/SimpleClientHttpResponseTest.java index ed76da17b..d8ac018cf 100644 --- a/spring-cloud-starter-tencent-polaris-circuitbreaker/src/test/java/com/tencent/cloud/polaris/circuitbreaker/SimpleClientHttpResponseTest.java +++ b/spring-cloud-starter-tencent-polaris-circuitbreaker/src/test/java/com/tencent/cloud/polaris/circuitbreaker/resttemplate/SimpleClientHttpResponseTest.java @@ -15,7 +15,7 @@ * specific language governing permissions and limitations under the License. */ -package com.tencent.cloud.polaris.circuitbreaker; +package com.tencent.cloud.polaris.circuitbreaker.resttemplate; import java.io.IOException; import java.io.InputStream; @@ -29,9 +29,9 @@ import org.springframework.util.StringUtils; /** - * @author : wh - * @date : 2022/6/22 09:00 - * @description: mock {@link org.springframework.http.client.SimpleClientHttpResponse} + * Mock Test for {@link AbstractClientHttpResponse}. + * + * @author wh 2022/6/22 */ public class SimpleClientHttpResponseTest extends AbstractClientHttpResponse { @@ -102,5 +102,4 @@ public class SimpleClientHttpResponseTest extends AbstractClientHttpResponse { // ignore } } - } diff --git a/spring-cloud-starter-tencent-polaris-config/pom.xml b/spring-cloud-starter-tencent-polaris-config/pom.xml index a7f0e5894..e7262c29f 100644 --- a/spring-cloud-starter-tencent-polaris-config/pom.xml +++ b/spring-cloud-starter-tencent-polaris-config/pom.xml @@ -71,6 +71,18 @@ test + + org.springframework.boot + spring-boot-actuator + true + + + + org.springframework.boot + spring-boot-actuator-autoconfigure + true + + org.mockito mockito-inline diff --git a/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/ConfigurationModifier.java b/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/ConfigurationModifier.java index 9953b3c67..e6994edb2 100644 --- a/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/ConfigurationModifier.java +++ b/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/ConfigurationModifier.java @@ -31,7 +31,6 @@ import org.apache.commons.lang.StringUtils; import org.springframework.util.CollectionUtils; - /** * Read configuration from spring cloud's configuration file and override polaris.yaml. * diff --git a/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/PolarisConfigBootstrapAutoConfiguration.java b/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/PolarisConfigBootstrapAutoConfiguration.java index e16f1480c..a67c8a89d 100644 --- a/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/PolarisConfigBootstrapAutoConfiguration.java +++ b/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/PolarisConfigBootstrapAutoConfiguration.java @@ -40,8 +40,7 @@ import org.springframework.core.env.Environment; */ @Configuration(proxyBeanMethods = false) @ConditionalOnPolarisEnabled -@ConditionalOnProperty(value = "spring.cloud.polaris.config.enabled", - matchIfMissing = true) +@ConditionalOnProperty(value = "spring.cloud.polaris.config.enabled", matchIfMissing = true) @Import(PolarisContextAutoConfiguration.class) public class PolarisConfigBootstrapAutoConfiguration { @@ -80,5 +79,4 @@ public class PolarisConfigBootstrapAutoConfiguration { PolarisContextProperties polarisContextProperties) { return new ConfigurationModifier(polarisConfigProperties, polarisContextProperties); } - } diff --git a/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/adapter/PolarisConfigFileLocator.java b/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/adapter/PolarisConfigFileLocator.java index b3b92ce30..091f09beb 100644 --- a/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/adapter/PolarisConfigFileLocator.java +++ b/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/adapter/PolarisConfigFileLocator.java @@ -52,8 +52,7 @@ import org.springframework.util.StringUtils; @Order(0) public class PolarisConfigFileLocator implements PropertySourceLocator { - private static final Logger LOGGER = LoggerFactory - .getLogger(PolarisConfigFileLocator.class); + private static final Logger LOGGER = LoggerFactory.getLogger(PolarisConfigFileLocator.class); private static final String POLARIS_CONFIG_PROPERTY_SOURCE_NAME = "polaris-config"; @@ -115,7 +114,7 @@ public class PolarisConfigFileLocator implements PropertySourceLocator { private List getInternalConfigFiles() { String namespace = polarisContextProperties.getNamespace(); String serviceName = polarisContextProperties.getService(); - if (StringUtils.isEmpty(serviceName)) { + if (!StringUtils.hasText(serviceName)) { serviceName = environment.getProperty("spring.application.name"); } @@ -125,7 +124,7 @@ public class PolarisConfigFileLocator implements PropertySourceLocator { String[] activeProfiles = environment.getActiveProfiles(); for (String activeProfile : activeProfiles) { - if (StringUtils.isEmpty(activeProfile)) { + if (!StringUtils.hasText(activeProfile)) { continue; } @@ -137,7 +136,7 @@ public class PolarisConfigFileLocator implements PropertySourceLocator { internalConfigFiles.add(new DefaultConfigFileMetadata(namespace, serviceName, "application.yml")); for (String activeProfile : activeProfiles) { - if (StringUtils.isEmpty(activeProfile)) { + if (!StringUtils.hasText(activeProfile)) { continue; } @@ -160,9 +159,8 @@ public class PolarisConfigFileLocator implements PropertySourceLocator { for (ConfigFileGroup configFileGroup : configFileGroups) { String group = configFileGroup.getName(); - if (StringUtils.isEmpty(group)) { - throw new IllegalArgumentException( - "polaris config group name cannot be empty."); + if (!StringUtils.hasText(group)) { + throw new IllegalArgumentException("polaris config group name cannot be empty."); } List files = configFileGroup.getFiles(); @@ -171,16 +169,14 @@ public class PolarisConfigFileLocator implements PropertySourceLocator { } for (String fileName : files) { - PolarisPropertySource polarisPropertySource = loadPolarisPropertySource( - namespace, group, fileName); + PolarisPropertySource polarisPropertySource = loadPolarisPropertySource(namespace, group, fileName); compositePropertySource.addPropertySource(polarisPropertySource); polarisPropertySourceManager.addPropertySource(polarisPropertySource); - LOGGER.info( - "[SCT Config] Load and inject polaris config file success. namespace = {}, group = {}, fileName = {}", - namespace, group, fileName); + LOGGER.info("[SCT Config] Load and inject polaris config file success." + + " namespace = {}, group = {}, fileName = {}", namespace, group, fileName); } } } @@ -189,21 +185,18 @@ public class PolarisConfigFileLocator implements PropertySourceLocator { String group, String fileName) { ConfigKVFile configKVFile; // unknown extension is resolved as properties file - if (ConfigFileFormat.isPropertyFile(fileName) - || ConfigFileFormat.isUnknownFile(fileName)) { + if (ConfigFileFormat.isPropertyFile(fileName) || ConfigFileFormat.isUnknownFile(fileName)) { configKVFile = configFileService.getConfigPropertiesFile(namespace, group, fileName); } else if (ConfigFileFormat.isYamlFile(fileName)) { configKVFile = configFileService.getConfigYamlFile(namespace, group, fileName); } else { - LOGGER.warn( - "[SCT Config] Unsupported config file. namespace = {}, group = {}, fileName = {}", + LOGGER.warn("[SCT Config] Unsupported config file. namespace = {}, group = {}, fileName = {}", namespace, group, fileName); - throw new IllegalStateException( - "Only configuration files in the format of properties / yaml / yaml" - + " can be injected into the spring context"); + throw new IllegalStateException("Only configuration files in the format of properties / yaml / yaml" + + " can be injected into the spring context"); } Map map = new ConcurrentHashMap<>(); @@ -213,5 +206,4 @@ public class PolarisConfigFileLocator implements PropertySourceLocator { return new PolarisPropertySource(namespace, group, fileName, configKVFile, map); } - } diff --git a/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/adapter/PolarisPropertySource.java b/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/adapter/PolarisPropertySource.java index 76b234e72..7a47fd187 100644 --- a/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/adapter/PolarisPropertySource.java +++ b/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/adapter/PolarisPropertySource.java @@ -74,5 +74,4 @@ public class PolarisPropertySource extends MapPropertySource { return "PolarisPropertySource{" + "namespace='" + namespace + '\'' + ", group='" + group + '\'' + ", fileName='" + fileName + '\'' + '}'; } - } diff --git a/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/adapter/PolarisPropertySourceAutoRefresher.java b/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/adapter/PolarisPropertySourceAutoRefresher.java index 76006f184..1cc324b5b 100644 --- a/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/adapter/PolarisPropertySourceAutoRefresher.java +++ b/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/adapter/PolarisPropertySourceAutoRefresher.java @@ -53,8 +53,7 @@ import org.springframework.util.CollectionUtils; public class PolarisPropertySourceAutoRefresher implements ApplicationListener, ApplicationContextAware { - private static final Logger LOGGER = LoggerFactory - .getLogger(PolarisPropertySourceAutoRefresher.class); + private static final Logger LOGGER = LoggerFactory.getLogger(PolarisPropertySourceAutoRefresher.class); private final PolarisConfigProperties polarisConfigProperties; @@ -92,8 +91,7 @@ public class PolarisPropertySourceAutoRefresher } @Override - public void setApplicationContext(ApplicationContext applicationContext) - throws BeansException { + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; this.beanFactory = ((ConfigurableApplicationContext) applicationContext).getBeanFactory(); this.typeConverter = this.beanFactory.getTypeConverter(); @@ -109,8 +107,7 @@ public class PolarisPropertySourceAutoRefresher return; } - List polarisPropertySources = polarisPropertySourceManager - .getAllPropertySources(); + List polarisPropertySources = polarisPropertySourceManager.getAllPropertySources(); if (CollectionUtils.isEmpty(polarisPropertySources)) { return; } diff --git a/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/adapter/PolarisPropertySourceManager.java b/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/adapter/PolarisPropertySourceManager.java index 6fff49069..f8736e20e 100644 --- a/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/adapter/PolarisPropertySourceManager.java +++ b/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/adapter/PolarisPropertySourceManager.java @@ -33,12 +33,10 @@ public class PolarisPropertySourceManager { private final Map polarisPropertySources = new ConcurrentHashMap<>(); public void addPropertySource(PolarisPropertySource polarisPropertySource) { - polarisPropertySources.putIfAbsent(polarisPropertySource.getPropertySourceName(), - polarisPropertySource); + polarisPropertySources.putIfAbsent(polarisPropertySource.getPropertySourceName(), polarisPropertySource); } public List getAllPropertySources() { return new ArrayList<>(polarisPropertySources.values()); } - } diff --git a/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/annotation/PolarisConfigAnnotationProcessor.java b/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/annotation/PolarisConfigAnnotationProcessor.java index 349799f69..59bbb994c 100644 --- a/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/annotation/PolarisConfigAnnotationProcessor.java +++ b/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/annotation/PolarisConfigAnnotationProcessor.java @@ -96,10 +96,8 @@ public class PolarisConfigAnnotationProcessor implements BeanPostProcessor, Prio Set interestedKeys = annotatedInterestedKeys.length > 0 ? Sets.newHashSet(annotatedInterestedKeys) : null; Set interestedKeyPrefixes = - annotatedInterestedKeyPrefixes.length > 0 ? Sets.newHashSet(annotatedInterestedKeyPrefixes) - : null; + annotatedInterestedKeyPrefixes.length > 0 ? Sets.newHashSet(annotatedInterestedKeyPrefixes) : null; addChangeListener(configChangeListener, interestedKeys, interestedKeyPrefixes); } - } diff --git a/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/annotation/PolarisConfigKVFileChangeListener.java b/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/annotation/PolarisConfigKVFileChangeListener.java index 6acbf2336..a324c4d78 100644 --- a/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/annotation/PolarisConfigKVFileChangeListener.java +++ b/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/annotation/PolarisConfigKVFileChangeListener.java @@ -38,7 +38,7 @@ public @interface PolarisConfigKVFileChangeListener { /** * The keys interested in the listener, will only be notified if any of the interested keys is changed. - *
+ *

* If neither of {@code interestedKeys} and {@code interestedKeyPrefixes} is specified then the {@code listener} will be notified when any key is changed. * @return interested keys in the listener */ @@ -49,10 +49,9 @@ public @interface PolarisConfigKVFileChangeListener { * The prefixes will simply be used to determine whether the {@code listener} should be notified or not using {@code changedKey.startsWith(prefix)}. * e.g. "spring." means that {@code listener} is interested in keys that starts with "spring.", such as "spring.banner", "spring.jpa", etc. * and "application" means that {@code listener} is interested in keys that starts with "application", such as "applicationName", "application.port", etc. - *
+ *

* If neither of {@code interestedKeys} and {@code interestedKeyPrefixes} is specified then the {@code listener} will be notified when whatever key is changed. * @return interested key-prefixed in the listener */ String[] interestedKeyPrefixes() default {}; - } diff --git a/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/config/ConfigFileGroup.java b/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/config/ConfigFileGroup.java index 05f1d7c5d..b52ffd13e 100644 --- a/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/config/ConfigFileGroup.java +++ b/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/config/ConfigFileGroup.java @@ -56,5 +56,4 @@ public class ConfigFileGroup { public String toString() { return "ConfigFileGroup{" + "name='" + name + '\'' + ", file=" + files + '}'; } - } diff --git a/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/config/PolarisConfigProperties.java b/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/config/PolarisConfigProperties.java index a2c9032fe..f39c5337f 100644 --- a/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/config/PolarisConfigProperties.java +++ b/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/config/PolarisConfigProperties.java @@ -94,5 +94,4 @@ public class PolarisConfigProperties { public void setGroups(List groups) { this.groups = groups; } - } diff --git a/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/endpoint/PolarisConfigEndpoint.java b/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/endpoint/PolarisConfigEndpoint.java new file mode 100644 index 000000000..eb9e94f5b --- /dev/null +++ b/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/endpoint/PolarisConfigEndpoint.java @@ -0,0 +1,58 @@ +/* + * Tencent is pleased to support the open source community by making Spring Cloud Tencent available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + */ + +package com.tencent.cloud.polaris.config.endpoint; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.tencent.cloud.polaris.config.adapter.PolarisPropertySource; +import com.tencent.cloud.polaris.config.adapter.PolarisPropertySourceManager; +import com.tencent.cloud.polaris.config.config.PolarisConfigProperties; + +import org.springframework.boot.actuate.endpoint.annotation.Endpoint; +import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; + +/** + * Endpoint of polaris config. + * + * @author shuiqingliu + **/ +@Endpoint(id = "polaris-config") +public class PolarisConfigEndpoint { + + private final PolarisConfigProperties polarisConfigProperties; + private final PolarisPropertySourceManager polarisPropertySourceManager; + + public PolarisConfigEndpoint(PolarisConfigProperties polarisConfigProperties, PolarisPropertySourceManager polarisPropertySourceManager) { + this.polarisConfigProperties = polarisConfigProperties; + this.polarisPropertySourceManager = polarisPropertySourceManager; + } + + @ReadOperation + public Map polarisConfig() { + Map configInfo = new HashMap<>(); + configInfo.put("PolarisConfigProperties", polarisConfigProperties); + + List propertySourceList = polarisPropertySourceManager.getAllPropertySources(); + configInfo.put("PolarisPropertySource", propertySourceList); + + return configInfo; + } +} diff --git a/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/endpoint/PolarisConfigEndpointAutoConfiguration.java b/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/endpoint/PolarisConfigEndpointAutoConfiguration.java new file mode 100644 index 000000000..cb26462ee --- /dev/null +++ b/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/endpoint/PolarisConfigEndpointAutoConfiguration.java @@ -0,0 +1,49 @@ +/* + * Tencent is pleased to support the open source community by making Spring Cloud Tencent available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + */ + +package com.tencent.cloud.polaris.config.endpoint; + +import com.tencent.cloud.polaris.config.adapter.PolarisPropertySourceManager; +import com.tencent.cloud.polaris.config.config.PolarisConfigProperties; + +import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnAvailableEndpoint; +import org.springframework.boot.actuate.endpoint.annotation.Endpoint; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * The AutoConfiguration for Polaris Config's endpoint. + * + * @author shuiqingliu + **/ +@Configuration(proxyBeanMethods = false) +@ConditionalOnClass(Endpoint.class) +@ConditionalOnProperty(value = "spring.cloud.polaris.config.enabled", + matchIfMissing = true) +public class PolarisConfigEndpointAutoConfiguration { + + @Bean + @ConditionalOnAvailableEndpoint + @ConditionalOnMissingBean + public PolarisConfigEndpoint polarisConfigEndpoint(PolarisConfigProperties polarisConfigProperties, PolarisPropertySourceManager polarisPropertySourceManager) { + return new PolarisConfigEndpoint(polarisConfigProperties, polarisPropertySourceManager); + } +} diff --git a/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/enums/ConfigFileFormat.java b/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/enums/ConfigFileFormat.java index 024ad67d0..d7c7b590c 100644 --- a/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/enums/ConfigFileFormat.java +++ b/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/enums/ConfigFileFormat.java @@ -80,5 +80,4 @@ public enum ConfigFileFormat { } return true; } - } diff --git a/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/listener/ConfigChangeEvent.java b/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/listener/ConfigChangeEvent.java index 119a5ce4c..367740d8c 100644 --- a/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/listener/ConfigChangeEvent.java +++ b/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/listener/ConfigChangeEvent.java @@ -84,5 +84,4 @@ public final class ConfigChangeEvent { public Set interestedChangedKeys() { return interestedChangedKeys; } - } diff --git a/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/listener/ConfigChangeListener.java b/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/listener/ConfigChangeListener.java index 14ab64a32..1ff9d139c 100644 --- a/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/listener/ConfigChangeListener.java +++ b/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/listener/ConfigChangeListener.java @@ -31,5 +31,4 @@ public interface ConfigChangeListener { * @param changeEvent the event for this change */ void onChange(ConfigChangeEvent changeEvent); - } diff --git a/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/listener/PolarisConfigChangeEventListener.java b/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/listener/PolarisConfigChangeEventListener.java index 0a55255d5..378f69628 100644 --- a/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/listener/PolarisConfigChangeEventListener.java +++ b/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/listener/PolarisConfigChangeEventListener.java @@ -107,5 +107,4 @@ public final class PolarisConfigChangeEventListener implements ApplicationListen }); return ret; } - } diff --git a/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/listener/PolarisConfigListenerContext.java b/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/listener/PolarisConfigListenerContext.java index 05ac41756..15a9a9336 100644 --- a/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/listener/PolarisConfigListenerContext.java +++ b/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/listener/PolarisConfigListenerContext.java @@ -52,6 +52,7 @@ import static com.tencent.polaris.configuration.api.core.ChangeType.MODIFIED; *

Refer to the Apollo project implementation: * * AbstractConfig + * * @author Palmer Xu 2022-06-06 */ public final class PolarisConfigListenerContext { @@ -60,32 +61,30 @@ public final class PolarisConfigListenerContext { * Logger instance. */ private static final Logger LOG = LoggerFactory.getLogger(PolarisConfigListenerContext.class); - /** * Execute service Atomic Reference Cache . */ private static final AtomicReference EAR = new AtomicReference<>(); - /** * All custom {@link ConfigChangeListener} instance defined in application . */ private static final List listeners = Lists.newCopyOnWriteArrayList(); - /** * All custom interested keys defined in application . */ private static final Map> interestedKeys = Maps.newHashMap(); - /** * All custom interested key prefixes defined in application . */ private static final Map> interestedKeyPrefixes = Maps.newHashMap(); - /** * Cache all latest configuration information for users in the application environment . */ private static final Cache properties = CacheBuilder.newBuilder().build(); + private PolarisConfigListenerContext() { + } + /** * Get or Created new execute server . * @return execute service instance of {@link ExecutorService} @@ -273,5 +272,4 @@ public final class PolarisConfigListenerContext { return Collections.unmodifiableSet(interestedChangedKeys); } - } diff --git a/spring-cloud-starter-tencent-polaris-config/src/main/resources/META-INF/spring.factories b/spring-cloud-starter-tencent-polaris-config/src/main/resources/META-INF/spring.factories index a0c33067e..98221a39a 100644 --- a/spring-cloud-starter-tencent-polaris-config/src/main/resources/META-INF/spring.factories +++ b/spring-cloud-starter-tencent-polaris-config/src/main/resources/META-INF/spring.factories @@ -1,4 +1,5 @@ org.springframework.cloud.bootstrap.BootstrapConfiguration=\ com.tencent.cloud.polaris.config.PolarisConfigBootstrapAutoConfiguration org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ - com.tencent.cloud.polaris.config.PolarisConfigAutoConfiguration + com.tencent.cloud.polaris.config.PolarisConfigAutoConfiguration,\ + com.tencent.cloud.polaris.config.endpoint.PolarisConfigEndpointAutoConfiguration diff --git a/spring-cloud-starter-tencent-polaris-config/src/test/java/com/tencent/cloud/polaris/config/adapter/MockedConfigKVFile.java b/spring-cloud-starter-tencent-polaris-config/src/test/java/com/tencent/cloud/polaris/config/adapter/MockedConfigKVFile.java index 026fe4d52..59e89ebcc 100644 --- a/spring-cloud-starter-tencent-polaris-config/src/test/java/com/tencent/cloud/polaris/config/adapter/MockedConfigKVFile.java +++ b/spring-cloud-starter-tencent-polaris-config/src/test/java/com/tencent/cloud/polaris/config/adapter/MockedConfigKVFile.java @@ -31,7 +31,8 @@ import com.tencent.polaris.configuration.api.core.ConfigKVFileChangeListener; /** * Mock config kv file for test. - *@author lepdou 2022-06-11 + * + * @author lepdou 2022-06-11 */ public class MockedConfigKVFile implements ConfigKVFile { diff --git a/spring-cloud-starter-tencent-polaris-config/src/test/java/com/tencent/cloud/polaris/config/adapter/PolarisConfigFileLocatorTest.java b/spring-cloud-starter-tencent-polaris-config/src/test/java/com/tencent/cloud/polaris/config/adapter/PolarisConfigFileLocatorTest.java index 8c072ef9d..bfe1fc5d2 100644 --- a/spring-cloud-starter-tencent-polaris-config/src/test/java/com/tencent/cloud/polaris/config/adapter/PolarisConfigFileLocatorTest.java +++ b/spring-cloud-starter-tencent-polaris-config/src/test/java/com/tencent/cloud/polaris/config/adapter/PolarisConfigFileLocatorTest.java @@ -41,12 +41,15 @@ import org.springframework.core.env.PropertySource; import static org.mockito.Mockito.when; /** - * test for {@link PolarisConfigFileLocator} - *@author lepdou 2022-06-11 + * test for {@link PolarisConfigFileLocator}. + * + * @author lepdou 2022-06-11 */ @RunWith(MockitoJUnitRunner.class) public class PolarisConfigFileLocatorTest { + private final String testNamespace = "testNamespace"; + private final String testServiceName = "testServiceName"; @Mock private PolarisConfigProperties polarisConfigProperties; @Mock @@ -58,9 +61,6 @@ public class PolarisConfigFileLocatorTest { @Mock private Environment environment; - private final String testNamespace = "testNamespace"; - private final String testServiceName = "testServiceName"; - @Test public void testLoadApplicationPropertiesFile() { PolarisConfigFileLocator locator = new PolarisConfigFileLocator(polarisConfigProperties, polarisContextProperties, diff --git a/spring-cloud-starter-tencent-polaris-config/src/test/java/com/tencent/cloud/polaris/config/adapter/PolarisPropertiesSourceAutoRefresherTest.java b/spring-cloud-starter-tencent-polaris-config/src/test/java/com/tencent/cloud/polaris/config/adapter/PolarisPropertiesSourceAutoRefresherTest.java index 04d455b46..ff9e405d1 100644 --- a/spring-cloud-starter-tencent-polaris-config/src/test/java/com/tencent/cloud/polaris/config/adapter/PolarisPropertiesSourceAutoRefresherTest.java +++ b/spring-cloud-starter-tencent-polaris-config/src/test/java/com/tencent/cloud/polaris/config/adapter/PolarisPropertiesSourceAutoRefresherTest.java @@ -48,12 +48,16 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** - * test for {@link PolarisPropertySourceAutoRefresher} - *@author lepdou 2022-06-11 + * test for {@link PolarisPropertySourceAutoRefresher}. + * + * @author lepdou 2022-06-11 */ @RunWith(MockitoJUnitRunner.class) public class PolarisPropertiesSourceAutoRefresherTest { + private final String testNamespace = "testNamespace"; + private final String testServiceName = "testServiceName"; + private final String testFileName = "application.properties"; @Mock private PolarisConfigProperties polarisConfigProperties; @Mock @@ -67,10 +71,6 @@ public class PolarisPropertiesSourceAutoRefresherTest { @Mock private PlaceholderHelper placeholderHelper; - private final String testNamespace = "testNamespace"; - private final String testServiceName = "testServiceName"; - private final String testFileName = "application.properties"; - @Test public void testConfigFileChanged() throws Exception { PolarisPropertySourceAutoRefresher refresher = new PolarisPropertySourceAutoRefresher(polarisConfigProperties, @@ -83,8 +83,7 @@ public class PolarisPropertiesSourceAutoRefresherTest { when(applicationContext.getBeanFactory()).thenReturn(beanFactory); refresher.setApplicationContext(applicationContext); when(typeConverter.convertIfNecessary(any(), any(), (Field) any())).thenReturn("v11"); - - + Collection springValues = new ArrayList<>(); MockedConfigChange mockedConfigChange = new MockedConfigChange(); mockedConfigChange.setK1("v1"); @@ -95,8 +94,7 @@ public class PolarisPropertiesSourceAutoRefresherTest { when(springValueRegistry.get(any(), any())).thenReturn(springValues); when(polarisConfigProperties.isAutoRefresh()).thenReturn(true); - - + Map content = new HashMap<>(); content.put("k1", "v1"); content.put("k2", "v2"); @@ -123,5 +121,4 @@ public class PolarisPropertiesSourceAutoRefresherTest { Assert.assertEquals("v11", mockedConfigChange.getK1()); } - } diff --git a/spring-cloud-starter-tencent-polaris-config/src/test/java/com/tencent/cloud/polaris/config/endpoint/PolarisConfigEndpointTest.java b/spring-cloud-starter-tencent-polaris-config/src/test/java/com/tencent/cloud/polaris/config/endpoint/PolarisConfigEndpointTest.java new file mode 100644 index 000000000..93190ee1a --- /dev/null +++ b/spring-cloud-starter-tencent-polaris-config/src/test/java/com/tencent/cloud/polaris/config/endpoint/PolarisConfigEndpointTest.java @@ -0,0 +1,70 @@ +/* + * Tencent is pleased to support the open source community by making Spring Cloud Tencent available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + */ + +package com.tencent.cloud.polaris.config.endpoint; + +import java.util.HashMap; +import java.util.Map; + +import com.google.common.collect.Lists; +import com.tencent.cloud.polaris.config.adapter.MockedConfigKVFile; +import com.tencent.cloud.polaris.config.adapter.PolarisPropertySource; +import com.tencent.cloud.polaris.config.adapter.PolarisPropertySourceManager; +import com.tencent.cloud.polaris.config.config.PolarisConfigProperties; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +/** + * Test for polaris config endpoint. + * + * @author shuiqingliu + */ +@RunWith(MockitoJUnitRunner.class) +public class PolarisConfigEndpointTest { + + private final String testNamespace = "testNamespace"; + private final String testServiceName = "testServiceName"; + private final String testFileName = "application.properties"; + + @Mock + private PolarisConfigProperties polarisConfigProperties; + @Mock + private PolarisPropertySourceManager polarisPropertySourceManager; + + @Test + public void testPolarisConfigEndpoint() { + Map content = new HashMap<>(); + content.put("k1", "v1"); + content.put("k2", "v2"); + content.put("k3", "v3"); + MockedConfigKVFile file = new MockedConfigKVFile(content); + PolarisPropertySource polarisPropertySource = new PolarisPropertySource(testNamespace, testServiceName, testFileName, + file, content); + when(polarisPropertySourceManager.getAllPropertySources()).thenReturn(Lists.newArrayList(polarisPropertySource)); + + PolarisConfigEndpoint endpoint = new PolarisConfigEndpoint(polarisConfigProperties, polarisPropertySourceManager); + Map info = endpoint.polarisConfig(); + assertThat(polarisConfigProperties).isEqualTo(info.get("PolarisConfigProperties")); + assertThat(Lists.newArrayList(polarisPropertySource)).isEqualTo(info.get("PolarisPropertySource")); + } +} diff --git a/spring-cloud-starter-tencent-polaris-config/src/test/java/com/tencent/cloud/polaris/config/listener/ConfigChangeListenerTest.java b/spring-cloud-starter-tencent-polaris-config/src/test/java/com/tencent/cloud/polaris/config/listener/ConfigChangeListenerTest.java index c408f4f54..58e39c89f 100644 --- a/spring-cloud-starter-tencent-polaris-config/src/test/java/com/tencent/cloud/polaris/config/listener/ConfigChangeListenerTest.java +++ b/spring-cloud-starter-tencent-polaris-config/src/test/java/com/tencent/cloud/polaris/config/listener/ConfigChangeListenerTest.java @@ -39,13 +39,13 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen /** * Integration testing for change listener. - *@author lepdou 2022-06-11 + * + * @author lepdou 2022-06-11 */ @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = DEFINED_PORT, classes = ConfigChangeListenerTest.TestApplication.class, - properties = {"server.port=8081", - "spring.config.location = classpath:application-test.yml"}) + properties = {"server.port=8081", "spring.config.location = classpath:application-test.yml"}) public class ConfigChangeListenerTest { @Autowired @@ -120,5 +120,4 @@ public class ConfigChangeListenerTest { } } } - } diff --git a/spring-cloud-starter-tencent-polaris-discovery/pom.xml b/spring-cloud-starter-tencent-polaris-discovery/pom.xml index 39d8d5f83..ac077bb7b 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/pom.xml +++ b/spring-cloud-starter-tencent-polaris-discovery/pom.xml @@ -93,6 +93,18 @@ test + + org.springframework.boot + spring-boot-actuator + true + + + + org.springframework.boot + spring-boot-actuator-autoconfigure + true + + io.projectreactor reactor-test diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/DiscoveryConfigModifier.java b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/DiscoveryConfigModifier.java index 67690ef24..0512de81e 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/DiscoveryConfigModifier.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/DiscoveryConfigModifier.java @@ -27,9 +27,9 @@ import com.tencent.polaris.plugins.router.healthy.RecoverRouterConfig; 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 { diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/DiscoveryPropertiesAutoConfiguration.java b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/DiscoveryPropertiesAutoConfiguration.java index d0129afc0..341b08192 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/DiscoveryPropertiesAutoConfiguration.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/DiscoveryPropertiesAutoConfiguration.java @@ -56,15 +56,13 @@ public class DiscoveryPropertiesAutoConfiguration { @Bean @ConditionalOnMissingBean - public ProviderAPI polarisProvider(SDKContext polarisContext) - throws PolarisException { + public ProviderAPI polarisProvider(SDKContext polarisContext) throws PolarisException { return DiscoveryAPIFactory.createProviderAPIByContext(polarisContext); } @Bean @ConditionalOnMissingBean - public ConsumerAPI polarisConsumer(SDKContext polarisContext) - throws PolarisException { + public ConsumerAPI polarisConsumer(SDKContext polarisContext) throws PolarisException { return DiscoveryAPIFactory.createConsumerAPIByContext(polarisContext); } @@ -98,5 +96,4 @@ public class DiscoveryPropertiesAutoConfiguration { public boolean isDiscoveryEnabled() { return discoveryEnabled; } - } diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/PolarisDiscoveryProperties.java b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/PolarisDiscoveryProperties.java index 2de7d0140..495cdc861 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/PolarisDiscoveryProperties.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/PolarisDiscoveryProperties.java @@ -258,5 +258,4 @@ public class PolarisDiscoveryProperties { } } - } diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/ConditionalOnPolarisDiscoveryEnabled.java b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/ConditionalOnPolarisDiscoveryEnabled.java index 97f478683..78f95ae9a 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/ConditionalOnPolarisDiscoveryEnabled.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/ConditionalOnPolarisDiscoveryEnabled.java @@ -28,6 +28,8 @@ import org.springframework.cloud.client.ConditionalOnDiscoveryEnabled; import org.springframework.context.annotation.Conditional; /** + * Condition if Polaris discovery is enabled. + * * @author Haotian Zhang, Andrew Shan, Jie Cheng */ @Retention(RetentionPolicy.RUNTIME) diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/DiscoveryEnabledCondition.java b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/DiscoveryEnabledCondition.java index 84041557f..1963537c2 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/DiscoveryEnabledCondition.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/DiscoveryEnabledCondition.java @@ -29,21 +29,17 @@ import org.springframework.core.type.AnnotatedTypeMetadata; public class DiscoveryEnabledCondition implements Condition { @Override - public boolean matches(ConditionContext conditionContext, - AnnotatedTypeMetadata annotatedTypeMetadata) { + public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) { - boolean isDiscoveryEnabled = Boolean - .parseBoolean(conditionContext.getEnvironment() - .getProperty("spring.cloud.polaris.discovery.enabled", "true")); + boolean isDiscoveryEnabled = Boolean.parseBoolean( + conditionContext.getEnvironment().getProperty("spring.cloud.polaris.discovery.enabled", "true")); - boolean isConsulDiscoveryEnabled = Boolean - .parseBoolean(conditionContext.getEnvironment() - .getProperty("spring.cloud.consul.enabled", "false")) + boolean isConsulDiscoveryEnabled = Boolean.parseBoolean( + conditionContext.getEnvironment().getProperty("spring.cloud.consul.enabled", "false")) && Boolean.parseBoolean(conditionContext.getEnvironment() - .getProperty("spring.cloud.consul.discovery.enabled", "true")); + .getProperty("spring.cloud.consul.discovery.enabled", "true")); isDiscoveryEnabled |= isConsulDiscoveryEnabled; return isDiscoveryEnabled; } - } diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/PolarisDiscoveryAutoConfiguration.java b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/PolarisDiscoveryAutoConfiguration.java index cc8000f44..b92ca6259 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/PolarisDiscoveryAutoConfiguration.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/PolarisDiscoveryAutoConfiguration.java @@ -43,5 +43,4 @@ public class PolarisDiscoveryAutoConfiguration { PolarisDiscoveryHandler polarisDiscoveryHandler) { return new PolarisServiceDiscovery(polarisDiscoveryHandler); } - } diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/PolarisDiscoveryClient.java b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/PolarisDiscoveryClient.java index f07469807..80cf3afdf 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/PolarisDiscoveryClient.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/PolarisDiscoveryClient.java @@ -54,5 +54,4 @@ public class PolarisDiscoveryClient implements DiscoveryClient { public List getServices() { return polarisServiceDiscovery.getServices(); } - } diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/PolarisDiscoveryClientConfiguration.java b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/PolarisDiscoveryClientConfiguration.java index 249685946..6b1ef7118 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/PolarisDiscoveryClientConfiguration.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/PolarisDiscoveryClientConfiguration.java @@ -33,15 +33,12 @@ import org.springframework.context.annotation.Configuration; */ @Configuration(proxyBeanMethods = false) @ConditionalOnBlockingDiscoveryEnabled -@AutoConfigureBefore({ SimpleDiscoveryClientAutoConfiguration.class, - CommonsClientAutoConfiguration.class }) +@AutoConfigureBefore({SimpleDiscoveryClientAutoConfiguration.class, CommonsClientAutoConfiguration.class}) @AutoConfigureAfter(PolarisDiscoveryAutoConfiguration.class) public class PolarisDiscoveryClientConfiguration { @Bean - public DiscoveryClient polarisDiscoveryClient( - PolarisServiceDiscovery polarisServiceDiscovery) { + public DiscoveryClient polarisDiscoveryClient(PolarisServiceDiscovery polarisServiceDiscovery) { return new PolarisDiscoveryClient(polarisServiceDiscovery); } - } diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/PolarisDiscoveryHandler.java b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/PolarisDiscoveryHandler.java index a55443561..f96c7d3d9 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/PolarisDiscoveryHandler.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/PolarisDiscoveryHandler.java @@ -53,6 +53,7 @@ public class PolarisDiscoveryHandler { /** * Get a list of healthy instances. + * * @param service service name * @return list of healthy instances */ @@ -66,6 +67,7 @@ public class PolarisDiscoveryHandler { /** * Return all instances for the given service. + * * @param service serviceName * @return list of instances */ @@ -87,6 +89,7 @@ public class PolarisDiscoveryHandler { /** * Return all service for given namespace. + * * @return service list */ public ServicesResponse GetServices() { @@ -95,5 +98,4 @@ public class PolarisDiscoveryHandler { request.setNamespace(namespace); return polarisConsumer.getServices(request); } - } diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/PolarisServiceDiscovery.java b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/PolarisServiceDiscovery.java index 95387ae5c..d05117b72 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/PolarisServiceDiscovery.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/PolarisServiceDiscovery.java @@ -31,6 +31,8 @@ import com.tencent.polaris.api.rpc.InstancesResponse; import org.springframework.cloud.client.ServiceInstance; /** + * Polaris service discovery service. + * * @author Haotian Zhang, Andrew Shan, Jie Cheng */ public class PolarisServiceDiscovery { @@ -49,8 +51,7 @@ public class PolarisServiceDiscovery { */ public List getInstances(String serviceId) throws PolarisException { List instances = new ArrayList<>(); - InstancesResponse filteredInstances = polarisDiscoveryHandler - .getHealthyInstances(serviceId); + InstancesResponse filteredInstances = polarisDiscoveryHandler.getHealthyInstances(serviceId); ServiceInstances serviceInstances = filteredInstances.toServiceInstances(); for (Instance instance : serviceInstances.getInstances()) { instances.add(new PolarisServiceInstance(instance)); @@ -67,5 +68,4 @@ public class PolarisServiceDiscovery { return polarisDiscoveryHandler.GetServices().getServices().stream() .map(ServiceInfo::getService).collect(Collectors.toList()); } - } diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/reactive/PolarisReactiveDiscoveryClient.java b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/reactive/PolarisReactiveDiscoveryClient.java index 6d3588c6f..09f50f2a7 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/reactive/PolarisReactiveDiscoveryClient.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/reactive/PolarisReactiveDiscoveryClient.java @@ -38,13 +38,11 @@ import org.springframework.cloud.client.discovery.ReactiveDiscoveryClient; */ public class PolarisReactiveDiscoveryClient implements ReactiveDiscoveryClient { - private static final Logger log = LoggerFactory - .getLogger(PolarisReactiveDiscoveryClient.class); + private static final Logger LOG = LoggerFactory.getLogger(PolarisReactiveDiscoveryClient.class); - private PolarisServiceDiscovery polarisServiceDiscovery; + private final PolarisServiceDiscovery polarisServiceDiscovery; - public PolarisReactiveDiscoveryClient( - PolarisServiceDiscovery polarisServiceDiscovery) { + public PolarisReactiveDiscoveryClient(PolarisServiceDiscovery polarisServiceDiscovery) { this.polarisServiceDiscovery = polarisServiceDiscovery; } @@ -55,7 +53,6 @@ public class PolarisReactiveDiscoveryClient implements ReactiveDiscoveryClient { @Override public Flux getInstances(String serviceId) { - return Mono.justOrEmpty(serviceId).flatMapMany(loadInstancesFromPolaris()) .subscribeOn(Schedulers.boundedElastic()); } @@ -66,7 +63,7 @@ public class PolarisReactiveDiscoveryClient implements ReactiveDiscoveryClient { return Flux.fromIterable(polarisServiceDiscovery.getInstances(serviceId)); } catch (PolarisException e) { - log.error("get service instance[{}] from polaris error!", serviceId, e); + LOG.error("get service instance[{}] from polaris error!", serviceId, e); return Flux.empty(); } }; @@ -79,10 +76,9 @@ public class PolarisReactiveDiscoveryClient implements ReactiveDiscoveryClient { return Flux.fromIterable(polarisServiceDiscovery.getServices()); } catch (Exception e) { - log.error("get services from polaris server fail,", e); + LOG.error("get services from polaris server fail,", e); return Flux.empty(); } }).subscribeOn(Schedulers.boundedElastic()); } - } diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/reactive/PolarisReactiveDiscoveryClientConfiguration.java b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/reactive/PolarisReactiveDiscoveryClientConfiguration.java index 09928e208..2f3d8e201 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/reactive/PolarisReactiveDiscoveryClientConfiguration.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/reactive/PolarisReactiveDiscoveryClientConfiguration.java @@ -47,5 +47,4 @@ public class PolarisReactiveDiscoveryClientConfiguration { PolarisServiceDiscovery polarisServiceDiscovery) { return new PolarisReactiveDiscoveryClient(polarisServiceDiscovery); } - } diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/refresh/PolarisRefreshApplicationReadyEventListener.java b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/refresh/PolarisRefreshApplicationReadyEventListener.java index 9591cb389..d8773ce7f 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/refresh/PolarisRefreshApplicationReadyEventListener.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/refresh/PolarisRefreshApplicationReadyEventListener.java @@ -25,6 +25,7 @@ import com.tencent.polaris.client.util.NamedThreadFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.DisposableBean; import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.cloud.client.discovery.event.HeartbeatEvent; import org.springframework.context.ApplicationEventPublisher; @@ -38,7 +39,8 @@ import static com.tencent.cloud.polaris.discovery.refresh.PolarisServiceStatusCh * * @author Haotian Zhang */ -public class PolarisRefreshApplicationReadyEventListener implements ApplicationListener, ApplicationEventPublisherAware { +public class PolarisRefreshApplicationReadyEventListener + implements ApplicationListener, ApplicationEventPublisherAware, DisposableBean { private static final Logger LOG = LoggerFactory.getLogger(PolarisRefreshApplicationReadyEventListener.class); private static final int DELAY = 60; @@ -47,7 +49,8 @@ public class PolarisRefreshApplicationReadyEventListener implements ApplicationL private final ScheduledExecutorService refreshExecutor; private ApplicationEventPublisher publisher; - public PolarisRefreshApplicationReadyEventListener(PolarisDiscoveryHandler polarisDiscoveryHandler, PolarisServiceStatusChangeListener polarisServiceStatusChangeListener) { + public PolarisRefreshApplicationReadyEventListener(PolarisDiscoveryHandler polarisDiscoveryHandler, + PolarisServiceStatusChangeListener polarisServiceStatusChangeListener) { this.polarisDiscoveryHandler = polarisDiscoveryHandler; this.polarisServiceStatusChangeListener = polarisServiceStatusChangeListener; this.refreshExecutor = Executors.newSingleThreadScheduledExecutor( @@ -83,4 +86,9 @@ public class PolarisRefreshApplicationReadyEventListener implements ApplicationL public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { this.publisher = applicationEventPublisher; } + + @Override + public void destroy() { + refreshExecutor.shutdown(); + } } diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/refresh/PolarisServiceStatusChangeListener.java b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/refresh/PolarisServiceStatusChangeListener.java index c923295d5..a5ce70782 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/refresh/PolarisServiceStatusChangeListener.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/refresh/PolarisServiceStatusChangeListener.java @@ -35,7 +35,8 @@ import org.springframework.context.ApplicationEventPublisherAware; import org.springframework.util.CollectionUtils; /** - * Change listener of Polaris service info. When service info is created or deleted, or, instance of service is from 0 to + * Change listener of Polaris service info. When service info is created or deleted, or, instance of service is from + * 0 to many. * * @author Haotian Zhang */ @@ -78,8 +79,10 @@ public class PolarisServiceStatusChangeListener extends AbstractResourceEventLis LOG.debug("receive service instances={} change event", svcEventKey); ServiceInstancesByProto oldIns = (ServiceInstancesByProto) oldValue; ServiceInstancesByProto newIns = (ServiceInstancesByProto) newValue; - if ((CollectionUtils.isEmpty(oldIns.getInstances()) && !CollectionUtils.isEmpty(newIns.getInstances())) || - (!CollectionUtils.isEmpty(oldIns.getInstances()) && CollectionUtils.isEmpty(newIns.getInstances()))) { + if ((CollectionUtils.isEmpty(oldIns.getInstances()) + && !CollectionUtils.isEmpty(newIns.getInstances())) || + (!CollectionUtils.isEmpty(oldIns.getInstances()) + && CollectionUtils.isEmpty(newIns.getInstances()))) { LOG.info("Service status of {} is update.", newIns.getService()); // Trigger reload of gateway route cache. diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/endpoint/PolarisDiscoveryEndPoint.java b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/endpoint/PolarisDiscoveryEndPoint.java new file mode 100644 index 000000000..5e006ac00 --- /dev/null +++ b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/endpoint/PolarisDiscoveryEndPoint.java @@ -0,0 +1,82 @@ +/* + * Tencent is pleased to support the open source community by making Spring Cloud Tencent available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.cloud.polaris.endpoint; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.tencent.cloud.polaris.PolarisDiscoveryProperties; +import com.tencent.cloud.polaris.discovery.PolarisDiscoveryHandler; +import com.tencent.polaris.api.pojo.ServiceInstances; +import com.tencent.polaris.api.rpc.InstancesResponse; +import org.apache.commons.lang.StringUtils; + +import org.springframework.boot.actuate.endpoint.annotation.Endpoint; +import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; +import org.springframework.boot.actuate.endpoint.annotation.Selector; +import org.springframework.cloud.client.discovery.DiscoveryClient; + +/** + * Endpoint of polaris discovery, include discovery properties and service instance. + * + * @author shuiqingliu + */ +@Endpoint(id = "polaris-discovery") +public class PolarisDiscoveryEndPoint { + + private final PolarisDiscoveryProperties polarisDiscoveryProperties; + private final DiscoveryClient polarisDiscoveryClient; + private final PolarisDiscoveryHandler polarisDiscoveryHandler; + + public PolarisDiscoveryEndPoint(PolarisDiscoveryProperties polarisDiscoveryProperties, DiscoveryClient polarisDiscoveryClient, PolarisDiscoveryHandler polarisDiscoveryHandler) { + this.polarisDiscoveryProperties = polarisDiscoveryProperties; + this.polarisDiscoveryClient = polarisDiscoveryClient; + this.polarisDiscoveryHandler = polarisDiscoveryHandler; + } + + @ReadOperation + public Map polarisDiscovery(@Selector String serviceId) { + Map polarisDisConveryInfo = new HashMap<>(); + polarisDisConveryInfo.put("PolarisDiscoveryProperties", polarisDiscoveryProperties); + + List serviceInstancesInfoList = new ArrayList<>(); + + if (StringUtils.isNotEmpty(serviceId)) { + ServiceInstances serviceInstances = getServiceInstances(serviceId); + serviceInstancesInfoList.add(serviceInstances); + polarisDisConveryInfo.put("ServiceInstances", serviceInstancesInfoList); + return polarisDisConveryInfo; + } + + for (String service : polarisDiscoveryClient.getServices()) { + ServiceInstances serviceInstances = getServiceInstances(service); + serviceInstancesInfoList.add(serviceInstances); + } + + polarisDisConveryInfo.put("ServiceInstances", serviceInstancesInfoList); + return polarisDisConveryInfo; + } + + private ServiceInstances getServiceInstances(String serviceId) { + InstancesResponse instancesResponse = polarisDiscoveryHandler.getHealthyInstances(serviceId); + ServiceInstances serviceInstances = instancesResponse.toServiceInstances(); + return serviceInstances; + } +} diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/endpoint/PolarisDiscoveryEndpointAutoConfiguration.java b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/endpoint/PolarisDiscoveryEndpointAutoConfiguration.java new file mode 100644 index 000000000..d6b597634 --- /dev/null +++ b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/endpoint/PolarisDiscoveryEndpointAutoConfiguration.java @@ -0,0 +1,49 @@ +/* + * Tencent is pleased to support the open source community by making Spring Cloud Tencent available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.cloud.polaris.endpoint; + +import com.tencent.cloud.polaris.PolarisDiscoveryProperties; +import com.tencent.cloud.polaris.discovery.ConditionalOnPolarisDiscoveryEnabled; +import com.tencent.cloud.polaris.discovery.PolarisDiscoveryHandler; + +import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnAvailableEndpoint; +import org.springframework.boot.actuate.endpoint.annotation.Endpoint; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.cloud.client.discovery.DiscoveryClient; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * The AutoConfiguration for Polaris Discovery's Endpoint. + * + * @author shuiqingliu + **/ +@Configuration(proxyBeanMethods = false) +@ConditionalOnClass(Endpoint.class) +@ConditionalOnPolarisDiscoveryEnabled +public class PolarisDiscoveryEndpointAutoConfiguration { + + @Bean + @ConditionalOnMissingBean + @ConditionalOnAvailableEndpoint + public PolarisDiscoveryEndPoint polarisDiscoveryEndPoint(PolarisDiscoveryProperties polarisDiscoveryProperties, + DiscoveryClient discoveryClient, PolarisDiscoveryHandler polarisDiscoveryHandler) { + return new PolarisDiscoveryEndPoint(polarisDiscoveryProperties, discoveryClient, polarisDiscoveryHandler); + } +} diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/extend/consul/ConsulContextProperties.java b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/extend/consul/ConsulContextProperties.java index 2efbd93d6..bc2ebefc9 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/extend/consul/ConsulContextProperties.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/extend/consul/ConsulContextProperties.java @@ -164,7 +164,5 @@ public class ConsulContextProperties { public int getOrder() { return ModifierOrder.LAST; } - } - } diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/registry/ConditionalOnPolarisRegisterEnabled.java b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/registry/ConditionalOnPolarisRegisterEnabled.java index 440312cab..3b186d27a 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/registry/ConditionalOnPolarisRegisterEnabled.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/registry/ConditionalOnPolarisRegisterEnabled.java @@ -27,6 +27,8 @@ import com.tencent.cloud.polaris.context.ConditionalOnPolarisEnabled; import org.springframework.context.annotation.Conditional; /** + * Condition if Polaris registry is enabled. + * * @author Haotian Zhang, Andrew Shan, Jie Cheng */ @Retention(RetentionPolicy.RUNTIME) diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/registry/PolarisAutoServiceRegistration.java b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/registry/PolarisAutoServiceRegistration.java index bfba996f7..719eb4e05 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/registry/PolarisAutoServiceRegistration.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/registry/PolarisAutoServiceRegistration.java @@ -31,11 +31,9 @@ import org.springframework.util.StringUtils; * * @author Haotian Zhang, Andrew Shan, Jie Cheng */ -public class PolarisAutoServiceRegistration - extends AbstractAutoServiceRegistration { +public class PolarisAutoServiceRegistration extends AbstractAutoServiceRegistration { - private static final Logger log = LoggerFactory - .getLogger(PolarisAutoServiceRegistration.class); + private static final Logger LOG = LoggerFactory.getLogger(PolarisAutoServiceRegistration.class); private final PolarisRegistration registration; @@ -62,7 +60,7 @@ public class PolarisAutoServiceRegistration @Override protected void register() { if (!this.registration.isRegisterEnabled()) { - log.debug("Registration disabled."); + LOG.debug("Registration disabled."); return; } if (this.registration.getPort() <= 0) { @@ -96,5 +94,4 @@ public class PolarisAutoServiceRegistration String appName = registration.getPolarisProperties().getService(); return StringUtils.isEmpty(appName) ? super.getAppName() : appName; } - } diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/registry/PolarisRegistration.java b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/registry/PolarisRegistration.java index 558a6b5bf..3af44314e 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/registry/PolarisRegistration.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/registry/PolarisRegistration.java @@ -51,10 +51,8 @@ public class PolarisRegistration implements Registration, ServiceInstance { private final SDKContext polarisContext; private final StaticMetadataManager staticMetadataManager; - - private Map metadata; - private final String host; + private Map metadata; public PolarisRegistration( DiscoveryPropertiesAutoConfiguration discoveryPropertiesAutoConfiguration, @@ -89,8 +87,7 @@ public class PolarisRegistration implements Registration, ServiceInstance { @Override public boolean isSecure() { - return StringUtils.equalsIgnoreCase(polarisDiscoveryProperties.getProtocol(), - "https"); + return StringUtils.equalsIgnoreCase(polarisDiscoveryProperties.getProtocol(), "https"); } @Override diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/registry/PolarisServiceRegistry.java b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/registry/PolarisServiceRegistry.java index b68b2b10f..ce43c8415 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/registry/PolarisServiceRegistry.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/registry/PolarisServiceRegistry.java @@ -51,8 +51,7 @@ import static org.springframework.util.ReflectionUtils.rethrowRuntimeException; */ public class PolarisServiceRegistry implements ServiceRegistry { - private static final Logger log = LoggerFactory - .getLogger(PolarisServiceRegistry.class); + private static final Logger LOG = LoggerFactory.getLogger(PolarisServiceRegistry.class); private static final int ttl = 5; @@ -82,9 +81,8 @@ public class PolarisServiceRegistry implements ServiceRegistry { @Override public void register(Registration registration) { - if (StringUtils.isEmpty(registration.getServiceId())) { - log.warn("No service to register for polaris client..."); + LOG.warn("No service to register for polaris client..."); return; } // Register instance. @@ -107,7 +105,7 @@ public class PolarisServiceRegistry implements ServiceRegistry { try { ProviderAPI providerClient = polarisDiscoveryHandler.getProviderAPI(); providerClient.register(instanceRegisterRequest); - log.info("polaris registry, {} {} {}:{} {} register finished", + LOG.info("polaris registry, {} {} {}:{} {} register finished", polarisDiscoveryProperties.getNamespace(), registration.getServiceId(), registration.getHost(), registration.getPort(), staticMetadataManager.getMergedStaticMetadata()); @@ -120,19 +118,17 @@ public class PolarisServiceRegistry implements ServiceRegistry { } } catch (Exception e) { - log.error("polaris registry, {} register failed...{},", - registration.getServiceId(), registration, e); + LOG.error("polaris registry, {} register failed...{},", registration.getServiceId(), registration, e); rethrowRuntimeException(e); } } @Override public void deregister(Registration registration) { - - log.info("De-registering from Polaris Server now..."); + LOG.info("De-registering from Polaris Server now..."); if (StringUtils.isEmpty(registration.getServiceId())) { - log.warn("No dom to de-register for polaris client..."); + LOG.warn("No dom to de-register for polaris client..."); return; } @@ -148,15 +144,14 @@ public class PolarisServiceRegistry implements ServiceRegistry { providerClient.deRegister(deRegisterRequest); } catch (Exception e) { - log.error("ERR_POLARIS_DEREGISTER, de-register failed...{},", registration, - e); + LOG.error("ERR_POLARIS_DEREGISTER, de-register failed...{},", registration, e); } finally { if (null != heartbeatExecutor) { heartbeatExecutor.shutdown(); } } - log.info("De-registration finished."); + LOG.info("De-registration finished."); } @Override @@ -172,8 +167,7 @@ public class PolarisServiceRegistry implements ServiceRegistry { @Override public Object getStatus(Registration registration) { String serviceName = registration.getServiceId(); - InstancesResponse instancesResponse = polarisDiscoveryHandler - .getInstances(serviceName); + InstancesResponse instancesResponse = polarisDiscoveryHandler.getInstances(serviceName); Instance[] instances = instancesResponse.getInstances(); if (null == instances || instances.length == 0) { return null; @@ -207,13 +201,10 @@ public class PolarisServiceRegistry implements ServiceRegistry { } String healthCheckUrl = String.format("http://%s:%s%s", - heartbeatRequest.getHost(), heartbeatRequest.getPort(), - healthCheckEndpoint); + heartbeatRequest.getHost(), heartbeatRequest.getPort(), healthCheckEndpoint); if (!OkHttpUtil.get(healthCheckUrl, null)) { - log.error( - "backend service health check failed. health check endpoint = {}", - healthCheckEndpoint); + LOG.error("backend service health check failed. health check endpoint = {}", healthCheckEndpoint); return; } } @@ -221,12 +212,11 @@ public class PolarisServiceRegistry implements ServiceRegistry { polarisDiscoveryHandler.getProviderAPI().heartbeat(heartbeatRequest); } catch (PolarisException e) { - log.error("polaris heartbeat[{}]", e.getCode(), e); + LOG.error("polaris heartbeat[{}]", e.getCode(), e); } catch (Exception e) { - log.error("polaris heartbeat runtime error", e); + LOG.error("polaris heartbeat runtime error", e); } }, ttl, ttl, TimeUnit.SECONDS); } - } diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/registry/PolarisServiceRegistryAutoConfiguration.java b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/registry/PolarisServiceRegistryAutoConfiguration.java index 5eadee573..13c75aea7 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/registry/PolarisServiceRegistryAutoConfiguration.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/registry/PolarisServiceRegistryAutoConfiguration.java @@ -43,8 +43,7 @@ import org.springframework.context.annotation.Configuration; @Configuration(proxyBeanMethods = false) @EnableConfigurationProperties @ConditionalOnPolarisRegisterEnabled -@ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", - matchIfMissing = true) +@ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true) @AutoConfigureAfter({AutoServiceRegistrationConfiguration.class, AutoServiceRegistrationAutoConfiguration.class, PolarisDiscoveryAutoConfiguration.class}) @@ -73,7 +72,6 @@ public class PolarisServiceRegistryAutoConfiguration { PolarisServiceRegistry registry, AutoServiceRegistrationProperties autoServiceRegistrationProperties, PolarisRegistration registration) { - return new PolarisAutoServiceRegistration(registry, - autoServiceRegistrationProperties, registration); + return new PolarisAutoServiceRegistration(registry, autoServiceRegistrationProperties, registration); } } diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/registry/RegisterEnabledCondition.java b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/registry/RegisterEnabledCondition.java index c7820fb6a..83ebb1d8b 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/registry/RegisterEnabledCondition.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/registry/RegisterEnabledCondition.java @@ -29,19 +29,16 @@ import org.springframework.core.type.AnnotatedTypeMetadata; public class RegisterEnabledCondition implements Condition { @Override - public boolean matches(ConditionContext conditionContext, - AnnotatedTypeMetadata annotatedTypeMetadata) { + public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) { boolean isRegisterEnabled = Boolean.parseBoolean(conditionContext.getEnvironment() .getProperty("spring.cloud.polaris.discovery.register", "true")); - boolean isConsulRegisterEnabled = Boolean - .parseBoolean(conditionContext.getEnvironment() - .getProperty("spring.cloud.consul.enabled", "false")) + boolean isConsulRegisterEnabled = Boolean.parseBoolean( + conditionContext.getEnvironment().getProperty("spring.cloud.consul.enabled", "false")) && Boolean.parseBoolean(conditionContext.getEnvironment() - .getProperty("spring.cloud.consul.discovery.register", "true")); + .getProperty("spring.cloud.consul.discovery.register", "true")); isRegisterEnabled |= isConsulRegisterEnabled; return isRegisterEnabled; } - } diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/ribbon/PolarisRibbonServerListConfiguration.java b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/ribbon/PolarisRibbonServerListConfiguration.java index f79bd2dba..931f387a0 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/ribbon/PolarisRibbonServerListConfiguration.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/ribbon/PolarisRibbonServerListConfiguration.java @@ -36,12 +36,10 @@ public class PolarisRibbonServerListConfiguration { @Bean @ConditionalOnMissingBean - public ServerList ribbonServerList( - PolarisDiscoveryHandler polarisDiscoveryHandler, + public ServerList ribbonServerList(PolarisDiscoveryHandler polarisDiscoveryHandler, IClientConfig iClientConfig) { PolarisServerList serverList = new PolarisServerList(polarisDiscoveryHandler); serverList.initWithNiwsConfig(iClientConfig); return serverList; } - } diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/ribbon/PolarisServerList.java b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/ribbon/PolarisServerList.java index 71833fde9..6e5b4a006 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/ribbon/PolarisServerList.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/ribbon/PolarisServerList.java @@ -56,8 +56,7 @@ public class PolarisServerList extends AbstractServerList { } private List getServers() { - InstancesResponse allInstances = polarisDiscoveryHandler - .getHealthyInstances(serviceId); + InstancesResponse allInstances = polarisDiscoveryHandler.getHealthyInstances(serviceId); ServiceInstances serviceInstances = allInstances.toServiceInstances(); List polarisServers = new ArrayList<>(); for (Instance instance : serviceInstances.getInstances()) { @@ -74,5 +73,4 @@ public class PolarisServerList extends AbstractServerList { public void initWithNiwsConfig(IClientConfig iClientConfig) { this.serviceId = iClientConfig.getClientName(); } - } diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/util/OkHttpUtil.java b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/util/OkHttpUtil.java index 2a1ba0dc4..b5a275c9a 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/util/OkHttpUtil.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/util/OkHttpUtil.java @@ -62,8 +62,7 @@ public final class OkHttpUtil { if (response.isSuccessful() && Objects.nonNull(response.body())) { String result = response.body().string(); - logger.debug("exec get request, url: {} success,response data: {}", url, - result); + logger.debug("exec get request, url: {} success,response data: {}", url, result); return true; } } @@ -88,5 +87,4 @@ public final class OkHttpUtil { }); } } - } diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/main/resources/META-INF/spring.factories b/spring-cloud-starter-tencent-polaris-discovery/src/main/resources/META-INF/spring.factories index 83b8e001f..e8deb25e8 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/main/resources/META-INF/spring.factories +++ b/spring-cloud-starter-tencent-polaris-discovery/src/main/resources/META-INF/spring.factories @@ -2,6 +2,7 @@ org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ com.tencent.cloud.polaris.DiscoveryPropertiesAutoConfiguration,\ com.tencent.cloud.polaris.discovery.PolarisDiscoveryAutoConfiguration,\ com.tencent.cloud.polaris.ribbon.PolarisDiscoveryRibbonAutoConfiguration,\ - com.tencent.cloud.polaris.registry.PolarisServiceRegistryAutoConfiguration + com.tencent.cloud.polaris.registry.PolarisServiceRegistryAutoConfiguration,\ + com.tencent.cloud.polaris.endpoint.PolarisDiscoveryEndpointAutoConfiguration org.springframework.cloud.bootstrap.BootstrapConfiguration=\ com.tencent.cloud.polaris.DiscoveryPropertiesBootstrapAutoConfiguration diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/DiscoveryPropertiesAutoConfigurationTest.java b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/DiscoveryPropertiesAutoConfigurationTest.java index 8f89a8313..e1ab77ec2 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/DiscoveryPropertiesAutoConfigurationTest.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/DiscoveryPropertiesAutoConfigurationTest.java @@ -41,7 +41,8 @@ public class DiscoveryPropertiesAutoConfigurationTest { @Test public void testDefaultInitialization() { ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner().withConfiguration( - AutoConfigurations.of(PolarisContextAutoConfiguration.class, + AutoConfigurations.of( + PolarisContextAutoConfiguration.class, DiscoveryPropertiesAutoConfiguration.class)); applicationContextRunner.run(context -> { assertThat(context).hasSingleBean(DiscoveryPropertiesAutoConfiguration.class); @@ -57,7 +58,8 @@ public class DiscoveryPropertiesAutoConfigurationTest { @Test public void testInit() { ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner().withConfiguration( - AutoConfigurations.of(PolarisContextAutoConfiguration.class, + AutoConfigurations.of( + PolarisContextAutoConfiguration.class, TestConfiguration.class, DiscoveryPropertiesAutoConfiguration.class)) .withPropertyValues("spring.cloud.polaris.discovery.register=false") @@ -65,7 +67,8 @@ public class DiscoveryPropertiesAutoConfigurationTest { .withPropertyValues("spring.cloud.consul.discovery.enabled=false"); applicationContextRunner.run(context -> { assertThat(context).hasSingleBean(DiscoveryPropertiesAutoConfiguration.class); - DiscoveryPropertiesAutoConfiguration discoveryPropertiesAutoConfiguration = context.getBean(DiscoveryPropertiesAutoConfiguration.class); + DiscoveryPropertiesAutoConfiguration discoveryPropertiesAutoConfiguration = + context.getBean(DiscoveryPropertiesAutoConfiguration.class); assertThat(discoveryPropertiesAutoConfiguration.isRegisterEnabled()).isFalse(); assertThat(discoveryPropertiesAutoConfiguration.isDiscoveryEnabled()).isFalse(); }); diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/DiscoveryPropertiesBootstrapAutoConfigurationTest.java b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/DiscoveryPropertiesBootstrapAutoConfigurationTest.java index 3ef145d0e..74f975a39 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/DiscoveryPropertiesBootstrapAutoConfigurationTest.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/DiscoveryPropertiesBootstrapAutoConfigurationTest.java @@ -35,7 +35,8 @@ public class DiscoveryPropertiesBootstrapAutoConfigurationTest { @Test public void testDefaultInitialization() { ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner().withConfiguration( - AutoConfigurations.of(PolarisContextAutoConfiguration.class, + AutoConfigurations.of( + PolarisContextAutoConfiguration.class, DiscoveryPropertiesBootstrapAutoConfiguration.class)) .withPropertyValues("spring.cloud.polaris.enabled=true"); applicationContextRunner.run(context -> { diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/discovery/PolarisDiscoveryAutoConfigurationTest.java b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/discovery/PolarisDiscoveryAutoConfigurationTest.java index 644cc4b7d..6966d4f6e 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/discovery/PolarisDiscoveryAutoConfigurationTest.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/discovery/PolarisDiscoveryAutoConfigurationTest.java @@ -30,7 +30,6 @@ import org.junit.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.runner.WebApplicationContextRunner; -import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.context.annotation.Configuration; import static com.tencent.polaris.test.common.Consts.PORT; @@ -46,12 +45,12 @@ public class PolarisDiscoveryAutoConfigurationTest { private static NamingServer namingServer; - private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(PolarisContextAutoConfiguration.class, - PolarisDiscoveryAutoConfiguration.class, - PolarisDiscoveryClientConfiguration.class, - PolarisContextAutoConfiguration.class)) + private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() + .withConfiguration(AutoConfigurations.of( + PolarisContextAutoConfiguration.class, + PolarisDiscoveryAutoConfiguration.class, + PolarisDiscoveryClientConfiguration.class, + PolarisContextAutoConfiguration.class)) .withPropertyValues("spring.application.name=" + SERVICE_PROVIDER) .withPropertyValues("server.port=" + PORT) .withPropertyValues("spring.cloud.polaris.address=grpc://127.0.0.1:10081"); @@ -62,7 +61,7 @@ public class PolarisDiscoveryAutoConfigurationTest { } @AfterClass - public static void afterClass() throws Exception { + public static void afterClass() { if (null != namingServer) { namingServer.terminate(); } @@ -80,9 +79,7 @@ public class PolarisDiscoveryAutoConfigurationTest { @Configuration @EnableAutoConfiguration - @EnableDiscoveryClient static class PolarisDiscoveryAutoConfiguration { } - } diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/discovery/PolarisDiscoveryClientConfigurationTest.java b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/discovery/PolarisDiscoveryClientConfigurationTest.java index c98000f81..4a0667686 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/discovery/PolarisDiscoveryClientConfigurationTest.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/discovery/PolarisDiscoveryClientConfigurationTest.java @@ -26,7 +26,6 @@ import org.junit.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.runner.WebApplicationContextRunner; -import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.context.annotation.Configuration; import static com.tencent.polaris.test.common.Consts.PORT; @@ -42,11 +41,11 @@ public class PolarisDiscoveryClientConfigurationTest { private static NamingServer namingServer; - private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(PolarisContextAutoConfiguration.class, - PolarisDiscoveryClientConfiguration.class, - PolarisContextAutoConfiguration.class)) + private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() + .withConfiguration(AutoConfigurations.of( + PolarisContextAutoConfiguration.class, + PolarisDiscoveryClientConfiguration.class, + PolarisContextAutoConfiguration.class)) .withPropertyValues("spring.application.name=" + SERVICE_PROVIDER) .withPropertyValues("server.port=" + PORT) .withPropertyValues("spring.cloud.polaris.address=grpc://127.0.0.1:10081"); @@ -57,7 +56,7 @@ public class PolarisDiscoveryClientConfigurationTest { } @AfterClass - public static void afterClass() throws Exception { + public static void afterClass() { if (null != namingServer) { namingServer.terminate(); } @@ -65,23 +64,18 @@ public class PolarisDiscoveryClientConfigurationTest { @Test public void testDefaultInitialization() { - this.contextRunner.run(context -> assertThat(context) - .hasSingleBean(PolarisDiscoveryClient.class)); + this.contextRunner.run(context -> assertThat(context).hasSingleBean(PolarisDiscoveryClient.class)); } @Test public void testDiscoveryBlockingDisabled() { - this.contextRunner - .withPropertyValues("spring.cloud.discovery.blocking.enabled=false") - .run(context -> assertThat(context) - .doesNotHaveBean(PolarisDiscoveryClient.class)); + this.contextRunner.withPropertyValues("spring.cloud.discovery.blocking.enabled=false") + .run(context -> assertThat(context).doesNotHaveBean(PolarisDiscoveryClient.class)); } @Configuration @EnableAutoConfiguration - @EnableDiscoveryClient static class PolarisDiscoveryClientConfiguration { } - } diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/discovery/PolarisDiscoveryClientTest.java b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/discovery/PolarisDiscoveryClientTest.java index b678593d9..e4a07de05 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/discovery/PolarisDiscoveryClientTest.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/discovery/PolarisDiscoveryClientTest.java @@ -51,7 +51,6 @@ public class PolarisDiscoveryClientTest { @Test public void testGetInstances() { - when(polarisServiceDiscovery.getInstances(anyString())) .thenReturn(singletonList(mock(PolarisServiceInstance.class))); @@ -62,9 +61,7 @@ public class PolarisDiscoveryClientTest { @Test public void testGetServices() { - - when(polarisServiceDiscovery.getServices()) - .thenReturn(singletonList(SERVICE_PROVIDER)); + when(polarisServiceDiscovery.getServices()).thenReturn(singletonList(SERVICE_PROVIDER)); List services = client.getServices(); diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/discovery/PolarisServiceDiscoveryTest.java b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/discovery/PolarisServiceDiscoveryTest.java index 4b03882d1..78004f0e8 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/discovery/PolarisServiceDiscoveryTest.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/discovery/PolarisServiceDiscoveryTest.java @@ -32,7 +32,6 @@ import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.runner.WebApplicationContextRunner; import org.springframework.cloud.client.ServiceInstance; -import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.context.annotation.Configuration; import static com.tencent.polaris.test.common.Consts.NAMESPACE_TEST; @@ -49,7 +48,7 @@ public class PolarisServiceDiscoveryTest { private static NamingServer namingServer; - private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() + private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() .withConfiguration(AutoConfigurations.of( PolarisContextAutoConfiguration.class, PolarisServiceDiscoveryTest.PolarisPropertiesConfiguration.class, @@ -73,12 +72,11 @@ public class PolarisServiceDiscoveryTest { instanceParameter.setIsolated(false); instanceParameter.setWeight(100); ServiceKey serviceKey = new ServiceKey(NAMESPACE_TEST, SERVICE_PROVIDER); - namingServer.getNamingService().batchAddInstances(serviceKey, PORT, 3, - instanceParameter); + namingServer.getNamingService().batchAddInstances(serviceKey, PORT, 3, instanceParameter); } @AfterClass - public static void afterClass() throws Exception { + public static void afterClass() { if (null != namingServer) { namingServer.terminate(); } @@ -87,10 +85,8 @@ public class PolarisServiceDiscoveryTest { @Test public void testGetInstances() { this.contextRunner.run(context -> { - PolarisServiceDiscovery polarisServiceDiscovery = context - .getBean(PolarisServiceDiscovery.class); - List serviceInstances = polarisServiceDiscovery - .getInstances(SERVICE_PROVIDER); + PolarisServiceDiscovery polarisServiceDiscovery = context.getBean(PolarisServiceDiscovery.class); + List serviceInstances = polarisServiceDiscovery.getInstances(SERVICE_PROVIDER); assertThat(serviceInstances.isEmpty()).isFalse(); assertThat(serviceInstances).hasSize(3); assertThat(serviceInstances.get(0).getPort()).isEqualTo(PORT); @@ -102,8 +98,7 @@ public class PolarisServiceDiscoveryTest { @Test public void testGetServices() throws PolarisException { this.contextRunner.run(context -> { - PolarisServiceDiscovery polarisServiceDiscovery = context - .getBean(PolarisServiceDiscovery.class); + PolarisServiceDiscovery polarisServiceDiscovery = context.getBean(PolarisServiceDiscovery.class); List services = polarisServiceDiscovery.getServices(); assertThat(services.size()).isEqualTo(1); }); @@ -112,9 +107,7 @@ public class PolarisServiceDiscoveryTest { @Configuration @EnableAutoConfiguration - @EnableDiscoveryClient static class PolarisPropertiesConfiguration { } - } diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/discovery/reactive/PolarisReactiveDiscoveryClientConfigurationTest.java b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/discovery/reactive/PolarisReactiveDiscoveryClientConfigurationTest.java index 8588c77af..11a61eb5a 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/discovery/reactive/PolarisReactiveDiscoveryClientConfigurationTest.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/discovery/reactive/PolarisReactiveDiscoveryClientConfigurationTest.java @@ -27,7 +27,6 @@ import org.junit.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.runner.WebApplicationContextRunner; -import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.context.annotation.Configuration; import static com.tencent.polaris.test.common.Consts.PORT; @@ -43,12 +42,12 @@ public class PolarisReactiveDiscoveryClientConfigurationTest { private static NamingServer namingServer; - private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(PolarisContextAutoConfiguration.class, - PolarisReactiveDiscoveryClientConfiguration.class, - PolarisDiscoveryClientConfiguration.class, - PolarisContextAutoConfiguration.class)) + private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() + .withConfiguration(AutoConfigurations.of( + PolarisContextAutoConfiguration.class, + PolarisReactiveDiscoveryClientConfiguration.class, + PolarisDiscoveryClientConfiguration.class, + PolarisContextAutoConfiguration.class)) .withPropertyValues("spring.application.name=" + SERVICE_PROVIDER) .withPropertyValues("server.port=" + PORT) .withPropertyValues("spring.cloud.polaris.address=grpc://127.0.0.1:10081"); @@ -59,7 +58,7 @@ public class PolarisReactiveDiscoveryClientConfigurationTest { } @AfterClass - public static void afterClass() throws Exception { + public static void afterClass() { if (null != namingServer) { namingServer.terminate(); } @@ -73,9 +72,7 @@ public class PolarisReactiveDiscoveryClientConfigurationTest { @Configuration @EnableAutoConfiguration - @EnableDiscoveryClient static class PolarisReactiveDiscoveryClientConfiguration { } - } diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/discovery/reactive/PolarisReactiveDiscoveryClientTest.java b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/discovery/reactive/PolarisReactiveDiscoveryClientTest.java index ac5f2088a..65516822f 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/discovery/reactive/PolarisReactiveDiscoveryClientTest.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/discovery/reactive/PolarisReactiveDiscoveryClientTest.java @@ -57,7 +57,6 @@ public class PolarisReactiveDiscoveryClientTest { @Test public void testGetInstances() throws PolarisException { - when(serviceDiscovery.getInstances(anyString())).thenAnswer(invocation -> { String serviceName = invocation.getArgument(0); if (SERVICE_PROVIDER.equalsIgnoreCase(serviceName)) { @@ -79,7 +78,6 @@ public class PolarisReactiveDiscoveryClientTest { @Test public void testGetServices() throws PolarisException { - when(serviceDiscovery.getServices()).thenAnswer(invocation -> { if (count == 0) { count++; diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/discovery/refresh/PolarisServiceStatusChangeListenerTest.java b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/discovery/refresh/PolarisServiceStatusChangeListenerTest.java index e468a46ed..7366e210a 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/discovery/refresh/PolarisServiceStatusChangeListenerTest.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/discovery/refresh/PolarisServiceStatusChangeListenerTest.java @@ -64,7 +64,8 @@ public class PolarisServiceStatusChangeListenerTest { polarisServiceStatusChangeListener.setApplicationEventPublisher(publisher); // Service update event - ServiceEventKey serviceUpdateEventKey = new ServiceEventKey(new ServiceKey(NAMESPACE_TEST, SERVICE_PROVIDER), ServiceEventKey.EventType.SERVICE); + ServiceEventKey serviceUpdateEventKey = new ServiceEventKey( + new ServiceKey(NAMESPACE_TEST, SERVICE_PROVIDER), ServiceEventKey.EventType.SERVICE); ServiceInfo serviceInfo = new ServiceInfo(); serviceInfo.setNamespace(NAMESPACE_TEST); serviceInfo.setService(SERVICE_PROVIDER); @@ -81,7 +82,8 @@ public class PolarisServiceStatusChangeListenerTest { // Instance update event - ServiceEventKey instanceUpdateEventKey = new ServiceEventKey(new ServiceKey(NAMESPACE_TEST, SERVICE_PROVIDER), ServiceEventKey.EventType.INSTANCE); + ServiceEventKey instanceUpdateEventKey = new ServiceEventKey( + new ServiceKey(NAMESPACE_TEST, SERVICE_PROVIDER), ServiceEventKey.EventType.INSTANCE); DefaultInstance instance = new DefaultInstance(); instance.setNamespace(NAMESPACE_TEST); instance.setService(SERVICE_PROVIDER); @@ -96,7 +98,7 @@ public class PolarisServiceStatusChangeListenerTest { instances.set(oldInstances, Collections.emptyList()); ServiceInstancesByProto newInstances = new ServiceInstancesByProto(); instances.set(newInstances, Collections.singletonList(instance)); - polarisServiceStatusChangeListener.onResourceUpdated(serviceUpdateEventKey, oldInstances, newInstances); + polarisServiceStatusChangeListener.onResourceUpdated(instanceUpdateEventKey, oldInstances, newInstances); verify(publisher, times(2)).publishEvent(any(ApplicationEvent.class)); // No need update @@ -104,7 +106,7 @@ public class PolarisServiceStatusChangeListenerTest { instances.set(oldInstances, Collections.singletonList(instance)); newInstances = new ServiceInstancesByProto(); instances.set(newInstances, Collections.singletonList(instance)); - polarisServiceStatusChangeListener.onResourceUpdated(serviceUpdateEventKey, oldInstances, newInstances); + polarisServiceStatusChangeListener.onResourceUpdated(instanceUpdateEventKey, oldInstances, newInstances); verify(publisher, times(2)).publishEvent(any(ApplicationEvent.class)); } catch (NoSuchFieldException | IllegalAccessException e) { diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/endpoint/PolarisDiscoveryEndPointTest.java b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/endpoint/PolarisDiscoveryEndPointTest.java new file mode 100644 index 000000000..ea5562d11 --- /dev/null +++ b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/endpoint/PolarisDiscoveryEndPointTest.java @@ -0,0 +1,102 @@ +/* + * Tencent is pleased to support the open source community by making Spring Cloud Tencent available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.cloud.polaris.endpoint; + +import java.util.Map; + +import com.tencent.cloud.polaris.PolarisDiscoveryProperties; +import com.tencent.cloud.polaris.discovery.PolarisDiscoveryAutoConfiguration; +import com.tencent.cloud.polaris.discovery.PolarisDiscoveryClient; +import com.tencent.cloud.polaris.discovery.PolarisDiscoveryClientConfiguration; +import com.tencent.cloud.polaris.discovery.PolarisDiscoveryHandler; +import com.tencent.polaris.test.mock.discovery.NamingServer; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.test.context.runner.WebApplicationContextRunner; +import org.springframework.cloud.client.discovery.DiscoveryClient; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.context.annotation.Configuration; + +import static com.tencent.polaris.test.common.Consts.NAMESPACE_TEST; +import static com.tencent.polaris.test.common.Consts.PORT; +import static com.tencent.polaris.test.common.Consts.SERVICE_PROVIDER; +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Test for polaris discovery endpoint. + * + * @author shuiqingliu + */ +public class PolarisDiscoveryEndPointTest { + + private static NamingServer namingServer; + + private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() + .withConfiguration(AutoConfigurations.of( + PolarisDiscoveryEndPointTest.PolarisPropertiesConfiguration.class, + PolarisDiscoveryClientConfiguration.class, + PolarisDiscoveryAutoConfiguration.class, + PolarisDiscoveryEndpointAutoConfiguration.class)) + .withPropertyValues("spring.application.name=" + SERVICE_PROVIDER) + .withPropertyValues("server.port=" + PORT) + .withPropertyValues("spring.cloud.polaris.address=grpc://127.0.0.1:10081") + .withPropertyValues( + "spring.cloud.polaris.discovery.namespace=" + NAMESPACE_TEST) + .withPropertyValues("spring.cloud.polaris.discovery.token=xxxxxx"); + + @BeforeClass + public static void beforeClass() throws Exception { + namingServer = NamingServer.startNamingServer(10081); + } + + @AfterClass + public static void afterClass() throws Exception { + if (null != namingServer) { + namingServer.terminate(); + } + } + + @Test + public void testPolarisDiscoveryEndpoint() { + this.contextRunner.run(context -> { + PolarisDiscoveryProperties polarisDiscoveryProperties = context + .getBean(PolarisDiscoveryProperties.class); + DiscoveryClient discoveryClient = context + .getBean(PolarisDiscoveryClient.class); + PolarisDiscoveryHandler polarisDiscoveryHandler = context.getBean(PolarisDiscoveryHandler.class); + PolarisDiscoveryEndPoint polarisDiscoveryEndPoint = new PolarisDiscoveryEndPoint(polarisDiscoveryProperties, discoveryClient, polarisDiscoveryHandler); + + Map mapInfo = polarisDiscoveryEndPoint.polarisDiscovery("java_provider_test"); + + assertThat(polarisDiscoveryProperties).isEqualTo(mapInfo.get("PolarisDiscoveryProperties")); + + }); + } + + @Configuration + @EnableAutoConfiguration + @EnableDiscoveryClient + static class PolarisPropertiesConfiguration { + + } + +} diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/registry/PolarisAutoServiceRegistrationTest.java b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/registry/PolarisAutoServiceRegistrationTest.java index 26aaf8efa..1414b3d27 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/registry/PolarisAutoServiceRegistrationTest.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/registry/PolarisAutoServiceRegistrationTest.java @@ -140,5 +140,4 @@ public class PolarisAutoServiceRegistrationTest { doReturn(SERVICE_PROVIDER).when(polarisDiscoveryProperties).getService(); assertThat(polarisAutoServiceRegistration.getAppName()).isEqualTo(SERVICE_PROVIDER); } - } diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/registry/PolarisServiceRegistryAutoConfigurationTest.java b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/registry/PolarisServiceRegistryAutoConfigurationTest.java index 96b6b3fe8..9535e4fb4 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/registry/PolarisServiceRegistryAutoConfigurationTest.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/registry/PolarisServiceRegistryAutoConfigurationTest.java @@ -28,7 +28,6 @@ import org.junit.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.runner.WebApplicationContextRunner; -import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationAutoConfiguration; import org.springframework.context.annotation.Configuration; @@ -45,11 +44,11 @@ public class PolarisServiceRegistryAutoConfigurationTest { private static NamingServer namingServer; - private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(PolarisContextAutoConfiguration.class, - PolarisServiceRegistryAutoConfiguration.class, - PolarisDiscoveryClientConfiguration.class)) + private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() + .withConfiguration(AutoConfigurations.of( + PolarisContextAutoConfiguration.class, + PolarisServiceRegistryAutoConfiguration.class, + PolarisDiscoveryClientConfiguration.class)) .withPropertyValues("spring.application.name=" + SERVICE_PROVIDER) .withPropertyValues("server.port=" + PORT) .withPropertyValues("spring.cloud.polaris.address=grpc://127.0.0.1:10081"); @@ -60,7 +59,7 @@ public class PolarisServiceRegistryAutoConfigurationTest { } @AfterClass - public static void afterClass() throws Exception { + public static void afterClass() { if (null != namingServer) { namingServer.terminate(); } @@ -70,16 +69,13 @@ public class PolarisServiceRegistryAutoConfigurationTest { public void testDefaultInitialization() { this.contextRunner.run(context -> { assertThat(context).hasSingleBean(PolarisDiscoveryAutoConfiguration.class); - assertThat(context) - .hasSingleBean(AutoServiceRegistrationAutoConfiguration.class); + assertThat(context).hasSingleBean(AutoServiceRegistrationAutoConfiguration.class); }); } @Configuration @EnableAutoConfiguration - @EnableDiscoveryClient static class PolarisServiceRegistryAutoConfiguration { } - } diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/registry/PolarisServiceRegistryTest.java b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/registry/PolarisServiceRegistryTest.java index d6f751d2f..8a6797b7b 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/registry/PolarisServiceRegistryTest.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/registry/PolarisServiceRegistryTest.java @@ -49,17 +49,16 @@ public class PolarisServiceRegistryTest { private static NamingServer namingServer; - private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(PolarisContextAutoConfiguration.class, - PolarisPropertiesConfiguration.class, - PolarisDiscoveryClientConfiguration.class, - PolarisDiscoveryAutoConfiguration.class)) + private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() + .withConfiguration(AutoConfigurations.of( + PolarisContextAutoConfiguration.class, + PolarisPropertiesConfiguration.class, + PolarisDiscoveryClientConfiguration.class, + PolarisDiscoveryAutoConfiguration.class)) .withPropertyValues("spring.application.name=" + SERVICE_PROVIDER) .withPropertyValues("server.port=" + PORT) .withPropertyValues("spring.cloud.polaris.address=grpc://127.0.0.1:10081") - .withPropertyValues( - "spring.cloud.polaris.discovery.namespace=" + NAMESPACE_TEST) + .withPropertyValues("spring.cloud.polaris.discovery.namespace=" + NAMESPACE_TEST) .withPropertyValues("spring.cloud.polaris.discovery.token=xxxxxx"); @BeforeClass @@ -67,12 +66,11 @@ public class PolarisServiceRegistryTest { namingServer = NamingServer.startNamingServer(10081); // add service - namingServer.getNamingService() - .addService(new ServiceKey(NAMESPACE_TEST, SERVICE_PROVIDER)); + namingServer.getNamingService().addService(new ServiceKey(NAMESPACE_TEST, SERVICE_PROVIDER)); } @AfterClass - public static void afterClass() throws Exception { + public static void afterClass() { if (null != namingServer) { namingServer.terminate(); } @@ -81,8 +79,7 @@ public class PolarisServiceRegistryTest { @Test public void testRegister() { this.contextRunner.run(context -> { - PolarisServiceRegistry registry = context - .getBean(PolarisServiceRegistry.class); + PolarisServiceRegistry registry = context.getBean(PolarisServiceRegistry.class); PolarisRegistration registration = Mockito.mock(PolarisRegistration.class); when(registration.getHost()).thenReturn("127.0.0.1"); when(registration.getPort()).thenReturn(PORT); @@ -114,8 +111,7 @@ public class PolarisServiceRegistryTest { @Test public void testDeRegister() { this.contextRunner.run(context -> { - PolarisServiceRegistry registry = context - .getBean(PolarisServiceRegistry.class); + PolarisServiceRegistry registry = context.getBean(PolarisServiceRegistry.class); PolarisRegistration registration = Mockito.mock(PolarisRegistration.class); doReturn(null).when(registration).getServiceId(); try { @@ -132,5 +128,4 @@ public class PolarisServiceRegistryTest { static class PolarisPropertiesConfiguration { } - } diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/ribbon/PolarisDiscoveryRibbonAutoConfigurationTest.java b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/ribbon/PolarisDiscoveryRibbonAutoConfigurationTest.java index e14d9be7d..7f9253a09 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/ribbon/PolarisDiscoveryRibbonAutoConfigurationTest.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/ribbon/PolarisDiscoveryRibbonAutoConfigurationTest.java @@ -31,7 +31,7 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class PolarisDiscoveryRibbonAutoConfigurationTest { - private ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner(); + private final ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner(); @Test public void testDefaultInitialization() { diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/ribbon/PolarisRibbonServerListConfigurationTest.java b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/ribbon/PolarisRibbonServerListConfigurationTest.java index 277555901..8d2d286fc 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/ribbon/PolarisRibbonServerListConfigurationTest.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/ribbon/PolarisRibbonServerListConfigurationTest.java @@ -37,7 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class PolarisRibbonServerListConfigurationTest { - private ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner(); + private final ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner(); @Test public void testDefaultInitialization() { diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/ribbon/PolarisServerListTest.java b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/ribbon/PolarisServerListTest.java index e441786e6..b617d8579 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/ribbon/PolarisServerListTest.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/ribbon/PolarisServerListTest.java @@ -54,18 +54,17 @@ public class PolarisServerListTest { private static NamingServer namingServer; - private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(PolarisContextAutoConfiguration.class, - PolarisServerListTest.PolarisPropertiesConfiguration.class, - PolarisDiscoveryClientConfiguration.class, - PolarisDiscoveryAutoConfiguration.class, - PolarisContextAutoConfiguration.class)) + private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() + .withConfiguration(AutoConfigurations.of( + PolarisContextAutoConfiguration.class, + PolarisServerListTest.PolarisPropertiesConfiguration.class, + PolarisDiscoveryClientConfiguration.class, + PolarisDiscoveryAutoConfiguration.class, + PolarisContextAutoConfiguration.class)) .withPropertyValues("spring.application.name=" + SERVICE_PROVIDER) .withPropertyValues("server.port=" + PORT) .withPropertyValues("spring.cloud.polaris.address=grpc://127.0.0.1:10081") - .withPropertyValues( - "spring.cloud.polaris.discovery.namespace=" + NAMESPACE_TEST) + .withPropertyValues("spring.cloud.polaris.discovery.namespace=" + NAMESPACE_TEST) .withPropertyValues("spring.cloud.polaris.discovery.token=xxxxxx"); private IClientConfig iClientConfig; @@ -75,12 +74,11 @@ public class PolarisServerListTest { namingServer = NamingServer.startNamingServer(10081); // add service - namingServer.getNamingService() - .addService(new ServiceKey(NAMESPACE_TEST, SERVICE_PROVIDER)); + namingServer.getNamingService().addService(new ServiceKey(NAMESPACE_TEST, SERVICE_PROVIDER)); } @AfterClass - public static void afterClass() throws Exception { + public static void afterClass() { if (null != namingServer) { namingServer.terminate(); } @@ -97,8 +95,7 @@ public class PolarisServerListTest { @Test public void testGetInitialListOfServers() { this.contextRunner.run(context -> { - PolarisDiscoveryHandler polarisDiscoveryHandler = context - .getBean(PolarisDiscoveryHandler.class); + PolarisDiscoveryHandler polarisDiscoveryHandler = context.getBean(PolarisDiscoveryHandler.class); PolarisServerList serverList = new PolarisServerList(polarisDiscoveryHandler); serverList.initWithNiwsConfig(iClientConfig); @@ -110,8 +107,7 @@ public class PolarisServerListTest { @Test public void testGetUpdatedListOfServers() { this.contextRunner.run(context -> { - PolarisDiscoveryHandler polarisDiscoveryHandler = context - .getBean(PolarisDiscoveryHandler.class); + PolarisDiscoveryHandler polarisDiscoveryHandler = context.getBean(PolarisDiscoveryHandler.class); PolarisServerList serverList = new PolarisServerList(polarisDiscoveryHandler); serverList.initWithNiwsConfig(iClientConfig); @@ -121,8 +117,7 @@ public class PolarisServerListTest { instanceParameter.setIsolated(false); instanceParameter.setWeight(100); ServiceKey serviceKey = new ServiceKey(NAMESPACE_TEST, SERVICE_PROVIDER); - namingServer.getNamingService().batchAddInstances(serviceKey, PORT, 3, - instanceParameter); + namingServer.getNamingService().batchAddInstances(serviceKey, PORT, 3, instanceParameter); List servers = serverList.getUpdatedListOfServers(); assertThat(servers).hasSize(3); @@ -135,8 +130,7 @@ public class PolarisServerListTest { @Test public void testProperties() { this.contextRunner.run(context -> { - PolarisDiscoveryHandler polarisDiscoveryHandler = context - .getBean(PolarisDiscoveryHandler.class); + PolarisDiscoveryHandler polarisDiscoveryHandler = context.getBean(PolarisDiscoveryHandler.class); PolarisServerList serverList = new PolarisServerList(polarisDiscoveryHandler); serverList.initWithNiwsConfig(iClientConfig); @@ -149,5 +143,4 @@ public class PolarisServerListTest { static class PolarisPropertiesConfiguration { } - } diff --git a/spring-cloud-starter-tencent-polaris-ratelimit/pom.xml b/spring-cloud-starter-tencent-polaris-ratelimit/pom.xml index aaccef814..d3499deee 100644 --- a/spring-cloud-starter-tencent-polaris-ratelimit/pom.xml +++ b/spring-cloud-starter-tencent-polaris-ratelimit/pom.xml @@ -90,6 +90,18 @@ test + + org.springframework.boot + spring-boot-actuator + true + + + + org.springframework.boot + spring-boot-actuator-autoconfigure + true + + org.mockito mockito-inline diff --git a/spring-cloud-starter-tencent-polaris-ratelimit/src/main/java/com/tencent/cloud/polaris/ratelimit/RateLimitRuleLabelResolver.java b/spring-cloud-starter-tencent-polaris-ratelimit/src/main/java/com/tencent/cloud/polaris/ratelimit/RateLimitRuleLabelResolver.java index 4c29cb3ad..bee50dc5c 100644 --- a/spring-cloud-starter-tencent-polaris-ratelimit/src/main/java/com/tencent/cloud/polaris/ratelimit/RateLimitRuleLabelResolver.java +++ b/spring-cloud-starter-tencent-polaris-ratelimit/src/main/java/com/tencent/cloud/polaris/ratelimit/RateLimitRuleLabelResolver.java @@ -34,7 +34,7 @@ import org.springframework.util.CollectionUtils; /** * resolve labels from rate limit rule. * - *@author lepdou 2022-05-13 + * @author lepdou 2022-05-13 */ public class RateLimitRuleLabelResolver { diff --git a/spring-cloud-starter-tencent-polaris-ratelimit/src/main/java/com/tencent/cloud/polaris/ratelimit/config/PolarisRateLimitAutoConfiguration.java b/spring-cloud-starter-tencent-polaris-ratelimit/src/main/java/com/tencent/cloud/polaris/ratelimit/config/PolarisRateLimitAutoConfiguration.java index 83cc00c91..5cd34b9d4 100644 --- a/spring-cloud-starter-tencent-polaris-ratelimit/src/main/java/com/tencent/cloud/polaris/ratelimit/config/PolarisRateLimitAutoConfiguration.java +++ b/spring-cloud-starter-tencent-polaris-ratelimit/src/main/java/com/tencent/cloud/polaris/ratelimit/config/PolarisRateLimitAutoConfiguration.java @@ -95,7 +95,6 @@ public class PolarisRateLimitAutoConfiguration { registrationBean.setOrder(RateLimitConstant.FILTER_ORDER); return registrationBean; } - } /** @@ -113,7 +112,5 @@ public class PolarisRateLimitAutoConfiguration { return new QuotaCheckReactiveFilter(limitAPI, labelResolver, polarisRateLimitProperties, rateLimitRuleLabelResolver); } - } - } diff --git a/spring-cloud-starter-tencent-polaris-ratelimit/src/main/java/com/tencent/cloud/polaris/ratelimit/config/RateLimitConfigModifier.java b/spring-cloud-starter-tencent-polaris-ratelimit/src/main/java/com/tencent/cloud/polaris/ratelimit/config/RateLimitConfigModifier.java index b0c097a68..a91e9c7c9 100644 --- a/spring-cloud-starter-tencent-polaris-ratelimit/src/main/java/com/tencent/cloud/polaris/ratelimit/config/RateLimitConfigModifier.java +++ b/spring-cloud-starter-tencent-polaris-ratelimit/src/main/java/com/tencent/cloud/polaris/ratelimit/config/RateLimitConfigModifier.java @@ -37,13 +37,11 @@ public class RateLimitConfigModifier implements PolarisConfigModifier { @Override public void modify(ConfigurationImpl configuration) { // Update MaxQueuingTime. - configuration.getProvider().getRateLimit() - .setMaxQueuingTime(polarisRateLimitProperties.getMaxQueuingTime()); + configuration.getProvider().getRateLimit().setMaxQueuingTime(polarisRateLimitProperties.getMaxQueuingTime()); } @Override public int getOrder() { return ContextConstant.ModifierOrder.CIRCUIT_BREAKER_ORDER; } - } diff --git a/spring-cloud-starter-tencent-polaris-ratelimit/src/main/java/com/tencent/cloud/polaris/ratelimit/constant/RateLimitConstant.java b/spring-cloud-starter-tencent-polaris-ratelimit/src/main/java/com/tencent/cloud/polaris/ratelimit/constant/RateLimitConstant.java index 814134527..22f11ed04 100644 --- a/spring-cloud-starter-tencent-polaris-ratelimit/src/main/java/com/tencent/cloud/polaris/ratelimit/constant/RateLimitConstant.java +++ b/spring-cloud-starter-tencent-polaris-ratelimit/src/main/java/com/tencent/cloud/polaris/ratelimit/constant/RateLimitConstant.java @@ -44,5 +44,4 @@ public final class RateLimitConstant { private RateLimitConstant() { } - } diff --git a/spring-cloud-starter-tencent-polaris-ratelimit/src/main/java/com/tencent/cloud/polaris/ratelimit/endpoint/PolarisRateLimitRuleEndpoint.java b/spring-cloud-starter-tencent-polaris-ratelimit/src/main/java/com/tencent/cloud/polaris/ratelimit/endpoint/PolarisRateLimitRuleEndpoint.java new file mode 100644 index 000000000..28bbae229 --- /dev/null +++ b/spring-cloud-starter-tencent-polaris-ratelimit/src/main/java/com/tencent/cloud/polaris/ratelimit/endpoint/PolarisRateLimitRuleEndpoint.java @@ -0,0 +1,101 @@ +/* + * Tencent is pleased to support the open source community by making Spring Cloud Tencent available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.cloud.polaris.ratelimit.endpoint; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.tencent.cloud.polaris.context.ServiceRuleManager; +import com.tencent.cloud.polaris.ratelimit.config.PolarisRateLimitProperties; +import com.tencent.polaris.client.pb.RateLimitProto; +import com.tencent.polaris.client.pb.RoutingProto; +import org.apache.commons.lang.StringUtils; + +import org.springframework.boot.actuate.endpoint.annotation.Endpoint; +import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; +import org.springframework.boot.actuate.endpoint.annotation.Selector; +import org.springframework.lang.Nullable; +import org.springframework.util.CollectionUtils; + +/** + * Endpoint of Polaris RateLimit rule. + * + * @author shuiqingliu + **/ +@Endpoint(id = "polaris-ratelimit") +public class PolarisRateLimitRuleEndpoint { + + private final ServiceRuleManager serviceRuleManager; + private final PolarisRateLimitProperties polarisRateLimitProperties; + + public PolarisRateLimitRuleEndpoint(ServiceRuleManager serviceRuleManager, PolarisRateLimitProperties polarisRateLimitProperties) { + this.serviceRuleManager = serviceRuleManager; + this.polarisRateLimitProperties = polarisRateLimitProperties; + } + + @ReadOperation + public Map rateLimit(@Selector String namespace, @Selector String service, @Nullable String dstService) { + Map result = new HashMap<>(); + RateLimitProto.RateLimit rateLimit = serviceRuleManager.getServiceRateLimitRule(namespace, service); + result.put("properties", polarisRateLimitProperties); + result.put("namespace", namespace); + result.put("service", service); + result.put("rateLimits", parseRateLimitRule(rateLimit)); + + if (StringUtils.isEmpty(dstService)) { + return result; + } + List routes = serviceRuleManager.getServiceRouterRule(namespace, service, dstService); + result.put("routes", routes); + return result; + } + + private List parseRateLimitRule(RateLimitProto.RateLimit rateLimit) { + List rateLimitRule = new ArrayList<>(); + if (rateLimit == null || CollectionUtils.isEmpty(rateLimit.getRulesList())) { + return rateLimitRule; + } + + for (RateLimitProto.Rule rule : rateLimit.getRulesList()) { + Map ruleMap = new HashMap<>(); + ruleMap.put("id", rule.getId()); + ruleMap.put("priority", rule.getPriority()); + ruleMap.put("resource", rule.getResource()); + ruleMap.put("type", rule.getType()); + ruleMap.put("labels", rule.getLabelsMap()); + ruleMap.put("amounts", rule.getAmountsList()); + ruleMap.put("action", rule.getAction()); + ruleMap.put("disable", rule.getDisable()); + ruleMap.put("report", rule.getReport()); + ruleMap.put("create_time", rule.getCtime()); + ruleMap.put("modify_time", rule.getMtime()); + ruleMap.put("revision", rule.getRevision()); + ruleMap.put("service_token", rule.getServiceToken()); + ruleMap.put("adjuster", rule.getAdjuster()); + ruleMap.put("regex_combine", rule.getRegexCombine()); + ruleMap.put("amount_mode", rule.getAmountMode()); + ruleMap.put("failover", rule.getFailover()); + ruleMap.put("cluster", rule.getCluster()); + rateLimitRule.add(ruleMap); + } + return rateLimitRule; + } + +} diff --git a/spring-cloud-starter-tencent-polaris-ratelimit/src/main/java/com/tencent/cloud/polaris/ratelimit/endpoint/PolarisRateLimitRuleEndpointAutoConfiguration.java b/spring-cloud-starter-tencent-polaris-ratelimit/src/main/java/com/tencent/cloud/polaris/ratelimit/endpoint/PolarisRateLimitRuleEndpointAutoConfiguration.java new file mode 100644 index 000000000..d16832989 --- /dev/null +++ b/spring-cloud-starter-tencent-polaris-ratelimit/src/main/java/com/tencent/cloud/polaris/ratelimit/endpoint/PolarisRateLimitRuleEndpointAutoConfiguration.java @@ -0,0 +1,50 @@ +/* + * Tencent is pleased to support the open source community by making Spring Cloud Tencent available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.cloud.polaris.ratelimit.endpoint; + +import com.tencent.cloud.polaris.context.ConditionalOnPolarisEnabled; +import com.tencent.cloud.polaris.context.ServiceRuleManager; +import com.tencent.cloud.polaris.ratelimit.config.PolarisRateLimitProperties; + +import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnAvailableEndpoint; +import org.springframework.boot.actuate.endpoint.annotation.Endpoint; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * The AutoConfiguration for Polaris RateLimit endpoint. + * + * @author shuiqingliu + **/ +@Configuration(proxyBeanMethods = false) +@ConditionalOnClass(Endpoint.class) +@ConditionalOnPolarisEnabled +@ConditionalOnProperty(name = "spring.cloud.polaris.ratelimit.enabled", matchIfMissing = true) +public class PolarisRateLimitRuleEndpointAutoConfiguration { + + @Bean + @ConditionalOnMissingBean + @ConditionalOnAvailableEndpoint + public PolarisRateLimitRuleEndpoint polarisRateLimitRuleEndpoint(ServiceRuleManager serviceRuleManager, PolarisRateLimitProperties properties) { + return new PolarisRateLimitRuleEndpoint(serviceRuleManager, properties); + } + +} diff --git a/spring-cloud-starter-tencent-polaris-ratelimit/src/main/java/com/tencent/cloud/polaris/ratelimit/filter/QuotaCheckReactiveFilter.java b/spring-cloud-starter-tencent-polaris-ratelimit/src/main/java/com/tencent/cloud/polaris/ratelimit/filter/QuotaCheckReactiveFilter.java index 31320dda0..fb547bb55 100644 --- a/spring-cloud-starter-tencent-polaris-ratelimit/src/main/java/com/tencent/cloud/polaris/ratelimit/filter/QuotaCheckReactiveFilter.java +++ b/spring-cloud-starter-tencent-polaris-ratelimit/src/main/java/com/tencent/cloud/polaris/ratelimit/filter/QuotaCheckReactiveFilter.java @@ -162,5 +162,4 @@ public class QuotaCheckReactiveFilter implements WebFilter, Ordered { Set expressionLabels = rateLimitRuleLabelResolver.getExpressionLabelKeys(namespace, service); return ExpressionLabelUtils.resolve(exchange, expressionLabels); } - } diff --git a/spring-cloud-starter-tencent-polaris-ratelimit/src/main/java/com/tencent/cloud/polaris/ratelimit/filter/QuotaCheckServletFilter.java b/spring-cloud-starter-tencent-polaris-ratelimit/src/main/java/com/tencent/cloud/polaris/ratelimit/filter/QuotaCheckServletFilter.java index f3e4c3b07..766f38b88 100644 --- a/spring-cloud-starter-tencent-polaris-ratelimit/src/main/java/com/tencent/cloud/polaris/ratelimit/filter/QuotaCheckServletFilter.java +++ b/spring-cloud-starter-tencent-polaris-ratelimit/src/main/java/com/tencent/cloud/polaris/ratelimit/filter/QuotaCheckServletFilter.java @@ -144,8 +144,7 @@ public class QuotaCheckServletFilter extends OncePerRequestFilter { return labelResolver.resolve(request); } catch (Throwable e) { - LOG.error("resolve custom label failed. resolver = {}", - labelResolver.getClass().getName(), e); + LOG.error("resolve custom label failed. resolver = {}", labelResolver.getClass().getName(), e); } } return Collections.emptyMap(); diff --git a/spring-cloud-starter-tencent-polaris-ratelimit/src/main/java/com/tencent/cloud/polaris/ratelimit/spi/PolarisRateLimiterLabelReactiveResolver.java b/spring-cloud-starter-tencent-polaris-ratelimit/src/main/java/com/tencent/cloud/polaris/ratelimit/spi/PolarisRateLimiterLabelReactiveResolver.java index 4ebcc1921..6f63cbc93 100644 --- a/spring-cloud-starter-tencent-polaris-ratelimit/src/main/java/com/tencent/cloud/polaris/ratelimit/spi/PolarisRateLimiterLabelReactiveResolver.java +++ b/spring-cloud-starter-tencent-polaris-ratelimit/src/main/java/com/tencent/cloud/polaris/ratelimit/spi/PolarisRateLimiterLabelReactiveResolver.java @@ -35,5 +35,4 @@ public interface PolarisRateLimiterLabelReactiveResolver { * @return resolved labels */ Map resolve(ServerWebExchange exchange); - } diff --git a/spring-cloud-starter-tencent-polaris-ratelimit/src/main/java/com/tencent/cloud/polaris/ratelimit/spi/PolarisRateLimiterLabelServletResolver.java b/spring-cloud-starter-tencent-polaris-ratelimit/src/main/java/com/tencent/cloud/polaris/ratelimit/spi/PolarisRateLimiterLabelServletResolver.java index 253b67b5c..1ec3a7a0c 100644 --- a/spring-cloud-starter-tencent-polaris-ratelimit/src/main/java/com/tencent/cloud/polaris/ratelimit/spi/PolarisRateLimiterLabelServletResolver.java +++ b/spring-cloud-starter-tencent-polaris-ratelimit/src/main/java/com/tencent/cloud/polaris/ratelimit/spi/PolarisRateLimiterLabelServletResolver.java @@ -35,5 +35,4 @@ public interface PolarisRateLimiterLabelServletResolver { * @return resolved labels */ Map resolve(HttpServletRequest request); - } diff --git a/spring-cloud-starter-tencent-polaris-ratelimit/src/main/java/com/tencent/cloud/polaris/ratelimit/utils/QuotaCheckUtils.java b/spring-cloud-starter-tencent-polaris-ratelimit/src/main/java/com/tencent/cloud/polaris/ratelimit/utils/QuotaCheckUtils.java index bceb49e9a..f0e5ec10a 100644 --- a/spring-cloud-starter-tencent-polaris-ratelimit/src/main/java/com/tencent/cloud/polaris/ratelimit/utils/QuotaCheckUtils.java +++ b/spring-cloud-starter-tencent-polaris-ratelimit/src/main/java/com/tencent/cloud/polaris/ratelimit/utils/QuotaCheckUtils.java @@ -57,5 +57,4 @@ public final class QuotaCheckUtils { "get quota failed")); } } - } diff --git a/spring-cloud-starter-tencent-polaris-ratelimit/src/main/java/com/tencent/cloud/polaris/ratelimit/utils/RateLimitUtils.java b/spring-cloud-starter-tencent-polaris-ratelimit/src/main/java/com/tencent/cloud/polaris/ratelimit/utils/RateLimitUtils.java index 4a67aea01..428254e37 100644 --- a/spring-cloud-starter-tencent-polaris-ratelimit/src/main/java/com/tencent/cloud/polaris/ratelimit/utils/RateLimitUtils.java +++ b/spring-cloud-starter-tencent-polaris-ratelimit/src/main/java/com/tencent/cloud/polaris/ratelimit/utils/RateLimitUtils.java @@ -63,5 +63,4 @@ public final class RateLimitUtils { return RateLimitConstant.QUOTA_LIMITED_INFO; } - } diff --git a/spring-cloud-starter-tencent-polaris-ratelimit/src/main/resources/META-INF/spring.factories b/spring-cloud-starter-tencent-polaris-ratelimit/src/main/resources/META-INF/spring.factories index 4abd34766..563704410 100644 --- a/spring-cloud-starter-tencent-polaris-ratelimit/src/main/resources/META-INF/spring.factories +++ b/spring-cloud-starter-tencent-polaris-ratelimit/src/main/resources/META-INF/spring.factories @@ -1,5 +1,6 @@ org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ com.tencent.cloud.polaris.ratelimit.config.PolarisRateLimitAutoConfiguration,\ - com.tencent.cloud.polaris.ratelimit.config.PolarisRateLimitPropertiesAutoConfiguration + com.tencent.cloud.polaris.ratelimit.config.PolarisRateLimitPropertiesAutoConfiguration,\ + com.tencent.cloud.polaris.ratelimit.endpoint.PolarisRateLimitRuleEndpointAutoConfiguration org.springframework.cloud.bootstrap.BootstrapConfiguration=\ com.tencent.cloud.polaris.ratelimit.config.PolarisRateLimitPropertiesBootstrapConfiguration diff --git a/spring-cloud-starter-tencent-polaris-ratelimit/src/test/java/com/tencent/cloud/polaris/ratelimit/config/PolarisRateLimitAutoConfigurationTest.java b/spring-cloud-starter-tencent-polaris-ratelimit/src/test/java/com/tencent/cloud/polaris/ratelimit/config/PolarisRateLimitAutoConfigurationTest.java index 387fe510d..7ba83ee33 100644 --- a/spring-cloud-starter-tencent-polaris-ratelimit/src/test/java/com/tencent/cloud/polaris/ratelimit/config/PolarisRateLimitAutoConfigurationTest.java +++ b/spring-cloud-starter-tencent-polaris-ratelimit/src/test/java/com/tencent/cloud/polaris/ratelimit/config/PolarisRateLimitAutoConfigurationTest.java @@ -39,11 +39,12 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class PolarisRateLimitAutoConfigurationTest { - private ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner(); + private final ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner(); - private WebApplicationContextRunner webApplicationContextRunner = new WebApplicationContextRunner(); + private final WebApplicationContextRunner webApplicationContextRunner = new WebApplicationContextRunner(); - private ReactiveWebApplicationContextRunner reactiveWebApplicationContextRunner = new ReactiveWebApplicationContextRunner(); + private final ReactiveWebApplicationContextRunner reactiveWebApplicationContextRunner = + new ReactiveWebApplicationContextRunner(); @Test public void testNoWebApplication() { @@ -58,7 +59,8 @@ public class PolarisRateLimitAutoConfigurationTest { assertThat(context).doesNotHaveBean(PolarisRateLimitAutoConfiguration.QuotaCheckFilterConfig.class); assertThat(context).doesNotHaveBean(QuotaCheckServletFilter.class); assertThat(context).doesNotHaveBean(FilterRegistrationBean.class); - assertThat(context).doesNotHaveBean(PolarisRateLimitAutoConfiguration.MetadataReactiveFilterConfig.class); + assertThat(context).doesNotHaveBean( + PolarisRateLimitAutoConfiguration.MetadataReactiveFilterConfig.class); assertThat(context).doesNotHaveBean(QuotaCheckReactiveFilter.class); }); } @@ -66,7 +68,8 @@ public class PolarisRateLimitAutoConfigurationTest { @Test public void testServletWebApplication() { this.webApplicationContextRunner - .withConfiguration(AutoConfigurations.of(PolarisContextAutoConfiguration.class, + .withConfiguration(AutoConfigurations.of( + PolarisContextAutoConfiguration.class, PolarisRateLimitProperties.class, PolarisRateLimitAutoConfiguration.class)) .run(context -> { @@ -75,7 +78,8 @@ public class PolarisRateLimitAutoConfigurationTest { assertThat(context).hasSingleBean(PolarisRateLimitAutoConfiguration.QuotaCheckFilterConfig.class); assertThat(context).hasSingleBean(QuotaCheckServletFilter.class); assertThat(context).hasSingleBean(FilterRegistrationBean.class); - assertThat(context).doesNotHaveBean(PolarisRateLimitAutoConfiguration.MetadataReactiveFilterConfig.class); + assertThat(context).doesNotHaveBean( + PolarisRateLimitAutoConfiguration.MetadataReactiveFilterConfig.class); assertThat(context).doesNotHaveBean(QuotaCheckReactiveFilter.class); }); } @@ -83,7 +87,8 @@ public class PolarisRateLimitAutoConfigurationTest { @Test public void testReactiveWebApplication() { this.reactiveWebApplicationContextRunner - .withConfiguration(AutoConfigurations.of(PolarisContextAutoConfiguration.class, + .withConfiguration(AutoConfigurations.of( + PolarisContextAutoConfiguration.class, PolarisRateLimitProperties.class, PolarisRateLimitAutoConfiguration.class)) .run(context -> { @@ -92,7 +97,8 @@ public class PolarisRateLimitAutoConfigurationTest { assertThat(context).doesNotHaveBean(PolarisRateLimitAutoConfiguration.QuotaCheckFilterConfig.class); assertThat(context).doesNotHaveBean(QuotaCheckServletFilter.class); assertThat(context).doesNotHaveBean(FilterRegistrationBean.class); - assertThat(context).hasSingleBean(PolarisRateLimitAutoConfiguration.MetadataReactiveFilterConfig.class); + assertThat(context).hasSingleBean( + PolarisRateLimitAutoConfiguration.MetadataReactiveFilterConfig.class); assertThat(context).hasSingleBean(QuotaCheckReactiveFilter.class); }); } diff --git a/spring-cloud-starter-tencent-polaris-ratelimit/src/test/java/com/tencent/cloud/polaris/ratelimit/config/PolarisRateLimitPropertiesAutoConfigurationTest.java b/spring-cloud-starter-tencent-polaris-ratelimit/src/test/java/com/tencent/cloud/polaris/ratelimit/config/PolarisRateLimitPropertiesAutoConfigurationTest.java index 258dd557b..f3130ed7a 100644 --- a/spring-cloud-starter-tencent-polaris-ratelimit/src/test/java/com/tencent/cloud/polaris/ratelimit/config/PolarisRateLimitPropertiesAutoConfigurationTest.java +++ b/spring-cloud-starter-tencent-polaris-ratelimit/src/test/java/com/tencent/cloud/polaris/ratelimit/config/PolarisRateLimitPropertiesAutoConfigurationTest.java @@ -31,9 +31,8 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class PolarisRateLimitPropertiesAutoConfigurationTest { - private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(PolarisRateLimitPropertiesAutoConfiguration.class)); + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(PolarisRateLimitPropertiesAutoConfiguration.class)); @Test public void testDefaultInitialization() { diff --git a/spring-cloud-starter-tencent-polaris-ratelimit/src/test/java/com/tencent/cloud/polaris/ratelimit/config/PolarisRateLimitPropertiesBootstrapConfigurationTest.java b/spring-cloud-starter-tencent-polaris-ratelimit/src/test/java/com/tencent/cloud/polaris/ratelimit/config/PolarisRateLimitPropertiesBootstrapConfigurationTest.java index 71e7334cc..90c88f98c 100644 --- a/spring-cloud-starter-tencent-polaris-ratelimit/src/test/java/com/tencent/cloud/polaris/ratelimit/config/PolarisRateLimitPropertiesBootstrapConfigurationTest.java +++ b/spring-cloud-starter-tencent-polaris-ratelimit/src/test/java/com/tencent/cloud/polaris/ratelimit/config/PolarisRateLimitPropertiesBootstrapConfigurationTest.java @@ -31,9 +31,8 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class PolarisRateLimitPropertiesBootstrapConfigurationTest { - private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(PolarisRateLimitPropertiesBootstrapConfiguration.class)) + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(PolarisRateLimitPropertiesBootstrapConfiguration.class)) .withPropertyValues("spring.cloud.polaris.enabled=true"); @Test diff --git a/spring-cloud-starter-tencent-polaris-ratelimit/src/test/java/com/tencent/cloud/polaris/ratelimit/controller/CalleeControllerTests.java b/spring-cloud-starter-tencent-polaris-ratelimit/src/test/java/com/tencent/cloud/polaris/ratelimit/controller/CalleeControllerTests.java index 4aabf24c2..72ee0c80b 100644 --- a/spring-cloud-starter-tencent-polaris-ratelimit/src/test/java/com/tencent/cloud/polaris/ratelimit/controller/CalleeControllerTests.java +++ b/spring-cloud-starter-tencent-polaris-ratelimit/src/test/java/com/tencent/cloud/polaris/ratelimit/controller/CalleeControllerTests.java @@ -88,7 +88,7 @@ public class CalleeControllerTests { } @AfterClass - public static void afterClass() throws Exception { + public static void afterClass() { if (null != namingServer) { namingServer.terminate(); } @@ -111,10 +111,8 @@ public class CalleeControllerTests { try { if (i > 9) { QuotaResponse quotaResponse = mock(QuotaResponse.class); - when(quotaResponse.getCode()) - .thenReturn(QuotaResultCode.QuotaResultLimited); - when(quotaResponse.getInfo()) - .thenReturn("Testing rate limit after 10 times success."); + when(quotaResponse.getCode()).thenReturn(QuotaResultCode.QuotaResultLimited); + when(quotaResponse.getInfo()).thenReturn("Testing rate limit after 10 times success."); when(limitAPI.getQuota(any())).thenReturn(quotaResponse); } String result = restTemplate.getForObject(url, String.class); @@ -146,5 +144,4 @@ public class CalleeControllerTests { } } - } diff --git a/spring-cloud-starter-tencent-polaris-ratelimit/src/test/java/com/tencent/cloud/polaris/ratelimit/controller/TestController.java b/spring-cloud-starter-tencent-polaris-ratelimit/src/test/java/com/tencent/cloud/polaris/ratelimit/controller/TestController.java index 1ede96b48..1bca56bc0 100644 --- a/spring-cloud-starter-tencent-polaris-ratelimit/src/test/java/com/tencent/cloud/polaris/ratelimit/controller/TestController.java +++ b/spring-cloud-starter-tencent-polaris-ratelimit/src/test/java/com/tencent/cloud/polaris/ratelimit/controller/TestController.java @@ -31,8 +31,7 @@ import org.springframework.web.bind.annotation.RestController; public class TestController { @GetMapping("/info") - public String info() throws Exception { + public String info() { return "hello service info"; } - } diff --git a/spring-cloud-starter-tencent-polaris-ratelimit/src/test/java/com/tencent/cloud/polaris/ratelimit/endpoint/PolarisRateLimitRuleEndpointTests.java b/spring-cloud-starter-tencent-polaris-ratelimit/src/test/java/com/tencent/cloud/polaris/ratelimit/endpoint/PolarisRateLimitRuleEndpointTests.java new file mode 100644 index 000000000..d5d7e6fd0 --- /dev/null +++ b/spring-cloud-starter-tencent-polaris-ratelimit/src/test/java/com/tencent/cloud/polaris/ratelimit/endpoint/PolarisRateLimitRuleEndpointTests.java @@ -0,0 +1,110 @@ +/* + * Tencent is pleased to support the open source community by making Spring Cloud Tencent available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.cloud.polaris.ratelimit.endpoint; + +import java.util.Map; + +import com.google.protobuf.StringValue; +import com.tencent.cloud.polaris.context.ServiceRuleManager; +import com.tencent.cloud.polaris.ratelimit.config.PolarisRateLimitProperties; +import com.tencent.polaris.client.pb.ModelProto; +import com.tencent.polaris.client.pb.RateLimitProto; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.junit.MockitoJUnitRunner; + +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.test.context.runner.WebApplicationContextRunner; +import org.springframework.context.annotation.Configuration; + +import static com.tencent.polaris.test.common.Consts.NAMESPACE_TEST; +import static com.tencent.polaris.test.common.Consts.PORT; +import static com.tencent.polaris.test.common.Consts.SERVICE_PROVIDER; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * Test for polaris rete limit rule endpoint. + * + * @author shuiqingliu + */ +@RunWith(MockitoJUnitRunner.class) +public class PolarisRateLimitRuleEndpointTests { + + private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() + .withConfiguration(AutoConfigurations.of( + PolarisRateLimitRuleEndpointTests.PolarisRateLimitAutoConfiguration.class, + PolarisRateLimitRuleEndpointAutoConfiguration.class, + PolarisRateLimitAutoConfiguration.class, + PolarisRateLimitAutoConfiguration.class)) + .withPropertyValues("spring.application.name=" + SERVICE_PROVIDER) + .withPropertyValues("server.port=" + PORT) + .withPropertyValues("spring.cloud.polaris.address=grpc://127.0.0.1:10081") + .withPropertyValues( + "spring.cloud.polaris.discovery.namespace=" + NAMESPACE_TEST) + .withPropertyValues("spring.cloud.polaris.discovery.token=xxxxxx"); + + private ServiceRuleManager serviceRuleManager; + private PolarisRateLimitProperties polarisRateLimitProperties; + + @Before + public void setUp() { + serviceRuleManager = mock(ServiceRuleManager.class); + when(serviceRuleManager.getServiceRateLimitRule(any(), anyString())).thenAnswer(invocationOnMock -> { + String serviceName = invocationOnMock.getArgument(1).toString(); + if (serviceName.equals("TestApp1")) { + return null; + } + else if (serviceName.equals("TestApp2")) { + return RateLimitProto.RateLimit.newBuilder().build(); + } + else if (serviceName.equals("TestApp3")) { + RateLimitProto.Rule rule = RateLimitProto.Rule.newBuilder().build(); + return RateLimitProto.RateLimit.newBuilder().addRules(rule).build(); + } + else { + ModelProto.MatchString matchString = ModelProto.MatchString.newBuilder() + .setType(ModelProto.MatchString.MatchStringType.EXACT) + .setValue(StringValue.of("value")) + .setValueType(ModelProto.MatchString.ValueType.TEXT).build(); + RateLimitProto.Rule rule = RateLimitProto.Rule.newBuilder() + .putLabels("${http.method}", matchString).build(); + return RateLimitProto.RateLimit.newBuilder().addRules(rule).build(); + } + }); + } + + @Test + public void testPolarisRateLimit() { + this.contextRunner.run(context -> polarisRateLimitProperties = context.getBean(PolarisRateLimitProperties.class)); + PolarisRateLimitRuleEndpoint polarisRateLimitRuleEndpoint = new PolarisRateLimitRuleEndpoint(serviceRuleManager, polarisRateLimitProperties); + Map rateLimit = polarisRateLimitRuleEndpoint.rateLimit("namespaceTest", "TestApp2", "TestApp3"); + assertThat(polarisRateLimitProperties).isEqualTo(rateLimit.get("properties")); + } + + @Configuration + @EnableAutoConfiguration + static class PolarisRateLimitAutoConfiguration { + + } +} diff --git a/spring-cloud-starter-tencent-polaris-ratelimit/src/test/java/com/tencent/cloud/polaris/ratelimit/filter/QuotaCheckReactiveFilterTest.java b/spring-cloud-starter-tencent-polaris-ratelimit/src/test/java/com/tencent/cloud/polaris/ratelimit/filter/QuotaCheckReactiveFilterTest.java index 6d3ef804f..b54ffec6f 100644 --- a/spring-cloud-starter-tencent-polaris-ratelimit/src/test/java/com/tencent/cloud/polaris/ratelimit/filter/QuotaCheckReactiveFilterTest.java +++ b/spring-cloud-starter-tencent-polaris-ratelimit/src/test/java/com/tencent/cloud/polaris/ratelimit/filter/QuotaCheckReactiveFilterTest.java @@ -74,17 +74,17 @@ import static org.mockito.Mockito.when; }) public class QuotaCheckReactiveFilterTest { - private PolarisRateLimiterLabelReactiveResolver labelResolver = exchange -> Collections.singletonMap("ReactiveResolver", "ReactiveResolver"); - - private QuotaCheckReactiveFilter quotaCheckReactiveFilter; - private static MockedStatic mockedApplicationContextAwareUtils; private static MockedStatic expressionLabelUtilsMockedStatic; + private final PolarisRateLimiterLabelReactiveResolver labelResolver = + exchange -> Collections.singletonMap("ReactiveResolver", "ReactiveResolver"); + private QuotaCheckReactiveFilter quotaCheckReactiveFilter; @BeforeClass public static void beforeClass() { expressionLabelUtilsMockedStatic = mockStatic(ExpressionLabelUtils.class); - when(ExpressionLabelUtils.resolve(any(ServerWebExchange.class), anySet())).thenReturn(Collections.singletonMap("RuleLabelResolver", "RuleLabelResolver")); + when(ExpressionLabelUtils.resolve(any(ServerWebExchange.class), anySet())) + .thenReturn(Collections.singletonMap("RuleLabelResolver", "RuleLabelResolver")); mockedApplicationContextAwareUtils = Mockito.mockStatic(ApplicationContextAwareUtils.class); mockedApplicationContextAwareUtils.when(() -> ApplicationContextAwareUtils.getProperties(anyString())) @@ -125,7 +125,8 @@ public class QuotaCheckReactiveFilterTest { RateLimitRuleLabelResolver rateLimitRuleLabelResolver = mock(RateLimitRuleLabelResolver.class); when(rateLimitRuleLabelResolver.getExpressionLabelKeys(anyString(), anyString())).thenReturn(Collections.EMPTY_SET); - this.quotaCheckReactiveFilter = new QuotaCheckReactiveFilter(limitAPI, labelResolver, polarisRateLimitProperties, rateLimitRuleLabelResolver); + this.quotaCheckReactiveFilter = new QuotaCheckReactiveFilter( + limitAPI, labelResolver, polarisRateLimitProperties, rateLimitRuleLabelResolver); } @Test diff --git a/spring-cloud-starter-tencent-polaris-ratelimit/src/test/java/com/tencent/cloud/polaris/ratelimit/filter/QuotaCheckServletFilterTest.java b/spring-cloud-starter-tencent-polaris-ratelimit/src/test/java/com/tencent/cloud/polaris/ratelimit/filter/QuotaCheckServletFilterTest.java index 7ff8e8793..cd68a8fdb 100644 --- a/spring-cloud-starter-tencent-polaris-ratelimit/src/test/java/com/tencent/cloud/polaris/ratelimit/filter/QuotaCheckServletFilterTest.java +++ b/spring-cloud-starter-tencent-polaris-ratelimit/src/test/java/com/tencent/cloud/polaris/ratelimit/filter/QuotaCheckServletFilterTest.java @@ -73,27 +73,26 @@ import static org.mockito.Mockito.when; }) public class QuotaCheckServletFilterTest { - private PolarisRateLimiterLabelServletResolver labelResolver = exchange -> Collections.singletonMap("ServletResolver", "ServletResolver"); - + private static MockedStatic mockedApplicationContextAwareUtils; + private static MockedStatic expressionLabelUtilsMockedStatic; + private PolarisRateLimiterLabelServletResolver labelResolver = + exchange -> Collections.singletonMap("ServletResolver", "ServletResolver"); private QuotaCheckServletFilter quotaCheckServletFilter; - private QuotaCheckServletFilter quotaCheckWithHtmlRejectTipsServletFilter; - private static MockedStatic mockedApplicationContextAwareUtils; - private static MockedStatic expressionLabelUtilsMockedStatic; @BeforeClass public static void beforeClass() { expressionLabelUtilsMockedStatic = mockStatic(ExpressionLabelUtils.class); - when(ExpressionLabelUtils.resolve(any(ServerWebExchange.class), anySet())).thenReturn(Collections.singletonMap("RuleLabelResolver", "RuleLabelResolver")); + when(ExpressionLabelUtils.resolve(any(ServerWebExchange.class), anySet())) + .thenReturn(Collections.singletonMap("RuleLabelResolver", "RuleLabelResolver")); mockedApplicationContextAwareUtils = Mockito.mockStatic(ApplicationContextAwareUtils.class); mockedApplicationContextAwareUtils.when(() -> ApplicationContextAwareUtils.getProperties(anyString())) .thenReturn("unit-test"); - } @AfterClass - public static void afterClass() throws Exception { + public static void afterClass() { mockedApplicationContextAwareUtils.close(); expressionLabelUtilsMockedStatic.close(); } @@ -128,10 +127,11 @@ public class QuotaCheckServletFilterTest { polarisRateLimitWithHtmlRejectTipsProperties.setRejectHttpCode(419); RateLimitRuleLabelResolver rateLimitRuleLabelResolver = mock(RateLimitRuleLabelResolver.class); - when(rateLimitRuleLabelResolver.getExpressionLabelKeys(anyString(), anyString())).thenReturn(Collections.EMPTY_SET); + when(rateLimitRuleLabelResolver.getExpressionLabelKeys(anyString(), anyString())).thenReturn(Collections.emptySet()); this.quotaCheckServletFilter = new QuotaCheckServletFilter(limitAPI, labelResolver, polarisRateLimitProperties, rateLimitRuleLabelResolver); - this.quotaCheckWithHtmlRejectTipsServletFilter = new QuotaCheckServletFilter(limitAPI, labelResolver, polarisRateLimitWithHtmlRejectTipsProperties, rateLimitRuleLabelResolver); + this.quotaCheckWithHtmlRejectTipsServletFilter = new QuotaCheckServletFilter( + limitAPI, labelResolver, polarisRateLimitWithHtmlRejectTipsProperties, rateLimitRuleLabelResolver); } @Test diff --git a/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/PolarisRouterContext.java b/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/PolarisRouterContext.java index 114548722..1e05d2ec6 100644 --- a/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/PolarisRouterContext.java +++ b/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/PolarisRouterContext.java @@ -27,7 +27,7 @@ import org.springframework.util.CollectionUtils; /** * the context for router. * - *@author lepdou 2022-05-17 + * @author lepdou 2022-05-17 */ public class PolarisRouterContext { diff --git a/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/RouterConstants.java b/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/RouterConstants.java index 6437c83e8..cff733e59 100644 --- a/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/RouterConstants.java +++ b/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/RouterConstants.java @@ -21,12 +21,15 @@ package com.tencent.cloud.polaris.router; /** * Router constants. * - *@author lepdou 2022-05-17 + * @author lepdou 2022-05-17 */ -public class RouterConstants { +public final class RouterConstants { /** * the header of router label. */ public static final String ROUTER_LABEL_HEADER = "internal-router-label"; + + private RouterConstants() { + } } diff --git a/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/RouterRuleLabelResolver.java b/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/RouterRuleLabelResolver.java index 5ab6e549f..ded1784f4 100644 --- a/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/RouterRuleLabelResolver.java +++ b/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/RouterRuleLabelResolver.java @@ -33,6 +33,7 @@ import org.springframework.util.CollectionUtils; /** * Resolve label expressions from routing rules. + * * @author lepdou 2022-05-19 */ public class RouterRuleLabelResolver { diff --git a/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/SimpleLoadBalancer.java b/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/SimpleLoadBalancer.java index d509c1bbf..3ccaf01a9 100644 --- a/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/SimpleLoadBalancer.java +++ b/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/SimpleLoadBalancer.java @@ -27,7 +27,7 @@ import com.netflix.loadbalancer.Server; /** * Simple load balancer only for getting and setting servers. * - *@author lepdou 2022-05-17 + * @author lepdou 2022-05-17 */ public class SimpleLoadBalancer implements ILoadBalancer { private List servers; diff --git a/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/beanprocessor/LoadBalancerClientFilterBeanPostProcessor.java b/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/beanprocessor/LoadBalancerClientFilterBeanPostProcessor.java index 5111bda51..5b4c7b71f 100644 --- a/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/beanprocessor/LoadBalancerClientFilterBeanPostProcessor.java +++ b/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/beanprocessor/LoadBalancerClientFilterBeanPostProcessor.java @@ -36,7 +36,8 @@ import org.springframework.cloud.gateway.filter.LoadBalancerClientFilter; /** * Replace LoadBalancerClientFilter with PolarisLoadBalancerClientFilter. - *@author lepdou 2022-06-15 + * + * @author lepdou 2022-06-15 */ public class LoadBalancerClientFilterBeanPostProcessor implements BeanPostProcessor, BeanFactoryAware { diff --git a/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/beanprocessor/LoadBalancerInterceptorBeanPostProcessor.java b/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/beanprocessor/LoadBalancerInterceptorBeanPostProcessor.java index 0b383a682..05625a2b7 100644 --- a/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/beanprocessor/LoadBalancerInterceptorBeanPostProcessor.java +++ b/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/beanprocessor/LoadBalancerInterceptorBeanPostProcessor.java @@ -37,7 +37,8 @@ import org.springframework.cloud.client.loadbalancer.LoadBalancerRequestFactory; /** * Replace LoadBalancerInterceptor with PolarisLoadBalancerInterceptor. * PolarisLoadBalancerInterceptor can pass routing context information. - *@author lepdou 2022-05-18 + * + * @author lepdou 2022-05-18 */ public class LoadBalancerInterceptorBeanPostProcessor implements BeanPostProcessor, BeanFactoryAware { diff --git a/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/config/FeignAutoConfiguration.java b/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/config/FeignAutoConfiguration.java index 5b87668ea..6de5f5399 100644 --- a/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/config/FeignAutoConfiguration.java +++ b/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/config/FeignAutoConfiguration.java @@ -36,7 +36,8 @@ import org.springframework.lang.Nullable; /** * configuration for feign singleton components. * Feign-related components need to be loaded only in the feign environment. - *@author lepdou 2022-06-10 + * + * @author lepdou 2022-06-10 */ @Configuration @ConditionalOnClass(name = {"org.springframework.cloud.openfeign.ribbon.FeignLoadBalancer"}) @@ -54,5 +55,4 @@ public class FeignAutoConfiguration { public PolarisCachingSpringLoadBalanceFactory polarisCachingSpringLoadBalanceFactory(SpringClientFactory factory) { return new PolarisCachingSpringLoadBalanceFactory(factory); } - } diff --git a/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/config/FeignLoadBalancerConfiguration.java b/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/config/FeignLoadBalancerConfiguration.java index e6368cc85..c49ea3a26 100644 --- a/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/config/FeignLoadBalancerConfiguration.java +++ b/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/config/FeignLoadBalancerConfiguration.java @@ -27,8 +27,10 @@ import org.springframework.cloud.netflix.ribbon.ServerIntrospector; import org.springframework.context.annotation.Bean; /** - * configuration for feign load balance components. PolarisFeignLoadBalancer is not singleton bean, Each service corresponds to a PolarisFeignLoadBalancer. - *@author lepdou 2022-05-16 + * configuration for feign load balance components. PolarisFeignLoadBalancer is not singleton bean, + * Each service corresponds to a PolarisFeignLoadBalancer. + * + * @author lepdou 2022-05-16 */ public class FeignLoadBalancerConfiguration { diff --git a/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/config/RibbonConfiguration.java b/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/config/RibbonConfiguration.java index 9bc17b276..e8fe2f06b 100644 --- a/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/config/RibbonConfiguration.java +++ b/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/config/RibbonConfiguration.java @@ -31,6 +31,7 @@ import org.springframework.context.annotation.Bean; /** * Configuration for ribbon components. IRule is not singleton bean, Each service corresponds to an IRule. + * * @author lepdou 2022-05-17 */ public class RibbonConfiguration { diff --git a/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/config/RouterAutoConfiguration.java b/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/config/RouterAutoConfiguration.java index 690ba9f0c..c3a3d40cb 100644 --- a/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/config/RouterAutoConfiguration.java +++ b/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/config/RouterAutoConfiguration.java @@ -38,7 +38,7 @@ import static org.springframework.core.Ordered.HIGHEST_PRECEDENCE; /** * configuration for router module singleton beans. * - *@author lepdou 2022-05-11 + * @author lepdou 2022-05-11 */ @Configuration @RibbonClients(defaultConfiguration = {RibbonConfiguration.class}) diff --git a/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/config/properties/PolarisMetadataRouterProperties.java b/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/config/properties/PolarisMetadataRouterProperties.java index 70ded3a8c..949edc54a 100644 --- a/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/config/properties/PolarisMetadataRouterProperties.java +++ b/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/config/properties/PolarisMetadataRouterProperties.java @@ -22,6 +22,7 @@ import org.springframework.boot.context.properties.ConfigurationProperties; /** * the configuration for metadata router. + * * @author lepdou 2022-05-23 */ @ConfigurationProperties(prefix = "spring.cloud.polaris.router.metadata-router") diff --git a/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/feign/FeignExpressionLabelUtils.java b/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/feign/FeignExpressionLabelUtils.java index 92b8a6608..152ffcc9c 100644 --- a/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/feign/FeignExpressionLabelUtils.java +++ b/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/feign/FeignExpressionLabelUtils.java @@ -33,9 +33,13 @@ import org.springframework.util.CollectionUtils; /** * Resolve rule expression label from feign request. + * * @author lepdou 2022-05-20 */ -public class FeignExpressionLabelUtils { +public final class FeignExpressionLabelUtils { + + private FeignExpressionLabelUtils() { + } public static Map resolve(RequestTemplate request, Set labelKeys) { if (CollectionUtils.isEmpty(labelKeys)) { diff --git a/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/feign/PolarisCachingSpringLoadBalanceFactory.java b/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/feign/PolarisCachingSpringLoadBalanceFactory.java index 2c15ce790..59044c3ba 100644 --- a/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/feign/PolarisCachingSpringLoadBalanceFactory.java +++ b/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/feign/PolarisCachingSpringLoadBalanceFactory.java @@ -33,7 +33,7 @@ import org.springframework.util.ConcurrentReferenceHashMap; /** * Extends CachingSpringLoadBalancerFactory to be able to create PolarisFeignLoadBalance. * - *@author lepdou 2022-05-16 + * @author lepdou 2022-05-16 */ public class PolarisCachingSpringLoadBalanceFactory extends CachingSpringLoadBalancerFactory { diff --git a/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/feign/PolarisFeignLoadBalancer.java b/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/feign/PolarisFeignLoadBalancer.java index 76c824f62..129e9b2fd 100644 --- a/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/feign/PolarisFeignLoadBalancer.java +++ b/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/feign/PolarisFeignLoadBalancer.java @@ -41,8 +41,7 @@ import org.springframework.util.CollectionUtils; /** * In order to pass router context for {@link com.tencent.cloud.polaris.router.PolarisLoadBalancerCompositeRule}. * - * @author lepdou 2022-05-16 - * @author cheese8 2022-06-18 + * @author lepdou, cheese8 */ public class PolarisFeignLoadBalancer extends FeignLoadBalancer { diff --git a/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/feign/RouterLabelFeignInterceptor.java b/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/feign/RouterLabelFeignInterceptor.java index 4eb59a208..00c4fe392 100644 --- a/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/feign/RouterLabelFeignInterceptor.java +++ b/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/feign/RouterLabelFeignInterceptor.java @@ -46,8 +46,7 @@ import org.springframework.util.CollectionUtils; /** * Resolver labels from request. * - * @author lepdou 2022-05-12 - * @author cheese8 2022-06-18 + * @author lepdou, cheese8 */ public class RouterLabelFeignInterceptor implements RequestInterceptor, Ordered { private static final Logger LOGGER = LoggerFactory.getLogger(RouterLabelFeignInterceptor.class); @@ -131,5 +130,4 @@ public class RouterLabelFeignInterceptor implements RequestInterceptor, Ordered return FeignExpressionLabelUtils.resolve(requestTemplate, labelKeys); } - } diff --git a/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/resttemplate/PolarisLoadBalancerInterceptor.java b/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/resttemplate/PolarisLoadBalancerInterceptor.java index de474c3f1..ddb215149 100644 --- a/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/resttemplate/PolarisLoadBalancerInterceptor.java +++ b/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/resttemplate/PolarisLoadBalancerInterceptor.java @@ -52,7 +52,7 @@ import org.springframework.util.CollectionUtils; * PolarisLoadBalancerInterceptor extends LoadBalancerInterceptor capabilities. * Parses the label from the request and puts it into the RouterContext for routing. * - *@author lepdou 2022-05-18 + * @author lepdou 2022-05-18 */ public class PolarisLoadBalancerInterceptor extends LoadBalancerInterceptor { private static final Logger LOGGER = LoggerFactory.getLogger(PolarisLoadBalancerInterceptor.class); diff --git a/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/scg/PolarisLoadBalancerClientFilter.java b/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/scg/PolarisLoadBalancerClientFilter.java index 35de57737..c46bc6e55 100644 --- a/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/scg/PolarisLoadBalancerClientFilter.java +++ b/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/scg/PolarisLoadBalancerClientFilter.java @@ -49,7 +49,8 @@ import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.G /** * Replaces the default LoadBalancerClientFilter implementation. - *@author lepdou 2022-06-10 + * + * @author lepdou 2022-06-10 */ public class PolarisLoadBalancerClientFilter extends LoadBalancerClientFilter { private final static Logger LOGGER = LoggerFactory.getLogger(PolarisLoadBalancerClientFilter.class); diff --git a/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/PolarisLoadBalancerCompositeRuleTest.java b/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/PolarisLoadBalancerCompositeRuleTest.java index 0d55e9cde..4caf5d08e 100644 --- a/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/PolarisLoadBalancerCompositeRuleTest.java +++ b/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/PolarisLoadBalancerCompositeRuleTest.java @@ -69,12 +69,14 @@ import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when; /** - * test for {@link PolarisLoadBalancerCompositeRule} - *@author lepdou 2022-05-26 + * test for {@link PolarisLoadBalancerCompositeRule}. + * + * @author lepdou 2022-05-26 */ @RunWith(MockitoJUnitRunner.class) public class PolarisLoadBalancerCompositeRuleTest { + private static AtomicBoolean initTransitiveMetadata = new AtomicBoolean(false); @Mock private PolarisLoadBalancerProperties polarisLoadBalancerProperties; @Mock @@ -85,11 +87,7 @@ public class PolarisLoadBalancerCompositeRuleTest { private PolarisRuleBasedRouterProperties polarisRuleBasedRouterProperties; @Mock private RouterAPI routerAPI; - private IClientConfig config; - - private static AtomicBoolean initTransitiveMetadata = new AtomicBoolean(false); - private String testNamespace = "testNamespace"; private String testCallerService = "testCallerService"; private String testCalleeService = "testCalleeService"; diff --git a/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/PolarisRouterContextTest.java b/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/PolarisRouterContextTest.java index 2a8d38752..0f2094233 100644 --- a/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/PolarisRouterContextTest.java +++ b/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/PolarisRouterContextTest.java @@ -25,9 +25,9 @@ import org.junit.Assert; import org.junit.Test; /** - * test for {@link PolarisRouterContext} + * test for {@link PolarisRouterContext}. * - *@author lepdou 2022-05-26 + * @author lepdou 2022-05-26 */ public class PolarisRouterContextTest { diff --git a/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/RouterRuleLabelResolverTest.java b/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/RouterRuleLabelResolverTest.java index 26c1dfb13..a910473ac 100644 --- a/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/RouterRuleLabelResolverTest.java +++ b/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/RouterRuleLabelResolverTest.java @@ -38,18 +38,18 @@ import org.mockito.junit.MockitoJUnitRunner; import static org.mockito.Mockito.when; /** - * test for {@link RouterRuleLabelResolver} - *@author lepdou 2022-05-26 + * test for {@link RouterRuleLabelResolver}. + * + * @author lepdou 2022-05-26 */ @RunWith(MockitoJUnitRunner.class) public class RouterRuleLabelResolverTest { - @Mock - private ServiceRuleManager serviceRuleManager; - private final String testNamespace = "testNamespace"; private final String testSourceService = "sourceService"; private final String testDstService = "dstService"; + @Mock + private ServiceRuleManager serviceRuleManager; @Test public void test() { diff --git a/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/SimpleLoadBalancerTest.java b/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/SimpleLoadBalancerTest.java index 36e512b4c..316539095 100644 --- a/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/SimpleLoadBalancerTest.java +++ b/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/SimpleLoadBalancerTest.java @@ -27,8 +27,9 @@ import org.junit.Test; import org.mockito.Mockito; /** - * test for {@link SimpleLoadBalancer} - *@author lepdou 2022-05-26 + * test for {@link SimpleLoadBalancer}. + * + * @author lepdou 2022-05-26 */ public class SimpleLoadBalancerTest { diff --git a/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/feign/FeignExpressionLabelUtilsTest.java b/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/feign/FeignExpressionLabelUtilsTest.java index 6078be75c..fa9086d5d 100644 --- a/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/feign/FeignExpressionLabelUtilsTest.java +++ b/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/feign/FeignExpressionLabelUtilsTest.java @@ -30,8 +30,9 @@ import org.junit.Test; import org.springframework.util.StringUtils; /** - * Test for {@link FeignExpressionLabelUtils} - *@author lepdou 2022-05-26 + * Test for {@link FeignExpressionLabelUtils}. + * + * @author lepdou 2022-05-26 */ public class FeignExpressionLabelUtilsTest { diff --git a/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/feign/PolarisCachingSpringLoadBalanceFactoryTest.java b/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/feign/PolarisCachingSpringLoadBalanceFactoryTest.java index c259e3b60..f84dec3eb 100644 --- a/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/feign/PolarisCachingSpringLoadBalanceFactoryTest.java +++ b/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/feign/PolarisCachingSpringLoadBalanceFactoryTest.java @@ -37,18 +37,18 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** - * Test for {@link PolarisCachingSpringLoadBalanceFactory} - *@author lepdou 2022-05-26 + * Test for {@link PolarisCachingSpringLoadBalanceFactory}. + * + * @author lepdou 2022-05-26 */ @RunWith(MockitoJUnitRunner.class) public class PolarisCachingSpringLoadBalanceFactoryTest { + private final String service1 = "service1"; + private final String service2 = "service2"; @Mock private SpringClientFactory factory; - private String service1 = "service1"; - private String service2 = "service2"; - @Test public void test() { PolarisCachingSpringLoadBalanceFactory polarisCachingSpringLoadBalanceFactory = diff --git a/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/feign/PolarisFeignLoadBalancerTest.java b/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/feign/PolarisFeignLoadBalancerTest.java index 52be650b6..5feda8a90 100644 --- a/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/feign/PolarisFeignLoadBalancerTest.java +++ b/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/feign/PolarisFeignLoadBalancerTest.java @@ -46,7 +46,8 @@ import org.springframework.cloud.netflix.ribbon.ServerIntrospector; import static org.mockito.Mockito.anyString; /** - * test for {@link PolarisFeignLoadBalancer} + * test for {@link PolarisFeignLoadBalancer}. + * * @author lepdou 2022-05-26 */ @RunWith(MockitoJUnitRunner.class) @@ -73,7 +74,8 @@ public class PolarisFeignLoadBalancerTest { // mock ApplicationContextAwareUtils#getProperties try (MockedStatic mockedApplicationContextAwareUtils = Mockito.mockStatic(ApplicationContextAwareUtils.class)) { - mockedApplicationContextAwareUtils.when(() -> ApplicationContextAwareUtils.getProperties(anyString())).thenReturn("unit-test"); + mockedApplicationContextAwareUtils.when(() -> ApplicationContextAwareUtils.getProperties(anyString())) + .thenReturn("unit-test"); MetadataContext metadataContext = Mockito.mock(MetadataContext.class); // mock MetadataContextHolder#get @@ -105,8 +107,8 @@ public class PolarisFeignLoadBalancerTest { // mock ApplicationContextAwareUtils#getProperties try (MockedStatic mockedApplicationContextAwareUtils = Mockito.mockStatic(ApplicationContextAwareUtils.class)) { - mockedApplicationContextAwareUtils.when(() -> ApplicationContextAwareUtils.getProperties(anyString())).thenReturn("unit-test"); - + mockedApplicationContextAwareUtils.when(() -> ApplicationContextAwareUtils.getProperties(anyString())) + .thenReturn("unit-test"); MetadataContext metadataContext = Mockito.mock(MetadataContext.class); // mock MetadataContextHolder#get try (MockedStatic mockedMetadataContextHolder = Mockito.mockStatic(MetadataContextHolder.class)) { diff --git a/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/feign/RouterLabelFeignInterceptorTest.java b/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/feign/RouterLabelFeignInterceptorTest.java index 16f15c372..f2db4641e 100644 --- a/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/feign/RouterLabelFeignInterceptorTest.java +++ b/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/feign/RouterLabelFeignInterceptorTest.java @@ -50,9 +50,9 @@ import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when; /** - * test for {@link RouterLabelFeignInterceptor} - * @author lepdou 2022-05-26 - * @author cheese8 2022-06-18 + * test for {@link RouterLabelFeignInterceptor}. + * + * @author lepdou, cheese8 */ @RunWith(MockitoJUnitRunner.class) public class RouterLabelFeignInterceptorTest { @@ -67,8 +67,7 @@ public class RouterLabelFeignInterceptorTest { @Test public void testResolveRouterLabel() { RouterLabelFeignInterceptor routerLabelFeignInterceptor = new RouterLabelFeignInterceptor( - Collections.singletonList(routerLabelResolver), - metadataLocalProperties, routerRuleLabelResolver); + Collections.singletonList(routerLabelResolver), metadataLocalProperties, routerRuleLabelResolver); // mock request template RequestTemplate requestTemplate = new RequestTemplate(); @@ -122,7 +121,8 @@ public class RouterLabelFeignInterceptorTest { Map routerLabelsMap = new HashMap<>(); try { String routerLabelContent = routerLabels.stream().findFirst().get(); - routerLabelsMap.putAll(JacksonUtils.deserialize2Map(URLDecoder.decode(routerLabelContent, StandardCharsets.UTF_8.name()))); + routerLabelsMap.putAll(JacksonUtils.deserialize2Map( + URLDecoder.decode(routerLabelContent, StandardCharsets.UTF_8.name()))); } catch (UnsupportedEncodingException e) { throw new RuntimeException("unsupported charset exception " + StandardCharsets.UTF_8.name()); diff --git a/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/resttemplate/PolarisLoadBalancerBeanPostProcessorTest.java b/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/resttemplate/PolarisLoadBalancerBeanPostProcessorTest.java index 18229efa6..1bc65659e 100644 --- a/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/resttemplate/PolarisLoadBalancerBeanPostProcessorTest.java +++ b/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/resttemplate/PolarisLoadBalancerBeanPostProcessorTest.java @@ -39,7 +39,8 @@ import org.springframework.cloud.client.loadbalancer.LoadBalancerRequestFactory; import static org.mockito.Mockito.when; /** - * Test for ${@link LoadBalancerInterceptorBeanPostProcessor} + * Test for ${@link LoadBalancerInterceptorBeanPostProcessor}. + * * @author lepdou 2022-05-26 */ @RunWith(MockitoJUnitRunner.class) diff --git a/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/resttemplate/PolarisLoadBalancerInterceptorTest.java b/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/resttemplate/PolarisLoadBalancerInterceptorTest.java index edbe8f240..0514c5b6b 100644 --- a/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/resttemplate/PolarisLoadBalancerInterceptorTest.java +++ b/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/resttemplate/PolarisLoadBalancerInterceptorTest.java @@ -59,7 +59,8 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** - * test for {@link PolarisLoadBalancerInterceptor} + * test for {@link PolarisLoadBalancerInterceptor}. + * * @author lepdou 2022-05-26 */ @RunWith(MockitoJUnitRunner.class) @@ -196,8 +197,10 @@ public class PolarisLoadBalancerInterceptorTest { try (MockedStatic mockedMetadataContextHolder = Mockito.mockStatic(MetadataContextHolder.class)) { mockedMetadataContextHolder.when(MetadataContextHolder::get).thenReturn(metadataContext); - PolarisLoadBalancerInterceptor polarisLoadBalancerInterceptor = new PolarisLoadBalancerInterceptor(loadBalancerClient, - loadBalancerRequestFactory, Collections.singletonList(routerLabelResolver), metadataLocalProperties, routerRuleLabelResolver); + PolarisLoadBalancerInterceptor polarisLoadBalancerInterceptor = + new PolarisLoadBalancerInterceptor(loadBalancerClient, loadBalancerRequestFactory, + Collections.singletonList(routerLabelResolver), metadataLocalProperties, + routerRuleLabelResolver); PolarisRouterContext routerContext = polarisLoadBalancerInterceptor.genRouterContext(request, null, calleeService); @@ -219,7 +222,7 @@ public class PolarisLoadBalancerInterceptorTest { static class MockedLoadBalancerRequest implements LoadBalancerRequest { @Override - public T apply(ServiceInstance instance) throws Exception { + public T apply(ServiceInstance instance) { return null; } } diff --git a/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/scg/PolarisLoadBalancerClientFilterTest.java b/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/scg/PolarisLoadBalancerClientFilterTest.java index 6010689af..b4c22b04f 100644 --- a/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/scg/PolarisLoadBalancerClientFilterTest.java +++ b/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/scg/PolarisLoadBalancerClientFilterTest.java @@ -57,12 +57,17 @@ import static org.mockito.Mockito.when; import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR; /** - * test for ${@link PolarisLoadBalancerClientFilter} - *@author lepdou 2022-06-13 + * test for ${@link PolarisLoadBalancerClientFilter}. + * + * @author lepdou 2022-06-13 */ @RunWith(MockitoJUnitRunner.class) public class PolarisLoadBalancerClientFilterTest { + private static final String callerService = "callerService"; + private static final String calleeService = "calleeService"; + private static MockedStatic mockedApplicationContextAwareUtils; + private static MockedStatic mockedMetadataContextHolder; @Mock private MetadataLocalProperties metadataLocalProperties; @Mock @@ -74,12 +79,6 @@ public class PolarisLoadBalancerClientFilterTest { @Mock private LoadBalancerProperties loadBalancerProperties; - private static final String callerService = "callerService"; - private static final String calleeService = "calleeService"; - - private static MockedStatic mockedApplicationContextAwareUtils; - private static MockedStatic mockedMetadataContextHolder; - @BeforeClass public static void beforeClass() { mockedApplicationContextAwareUtils = Mockito.mockStatic(ApplicationContextAwareUtils.class); diff --git a/spring-cloud-tencent-commons/pom.xml b/spring-cloud-tencent-commons/pom.xml index 1ad46ae56..495fc4a15 100644 --- a/spring-cloud-tencent-commons/pom.xml +++ b/spring-cloud-tencent-commons/pom.xml @@ -93,6 +93,18 @@ spring-boot-starter-test test + + + org.springframework.boot + spring-boot-actuator + true + + + + org.springframework.boot + spring-boot-actuator-autoconfigure + true + diff --git a/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/constant/ContextConstant.java b/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/constant/ContextConstant.java index 71ce1e886..41ed7544a 100644 --- a/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/constant/ContextConstant.java +++ b/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/constant/ContextConstant.java @@ -61,7 +61,5 @@ public final class ContextConstant { * Order of configuration modifier. */ public static Integer CONFIG_ORDER = 1; - } - } diff --git a/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/constant/MetadataConstant.java b/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/constant/MetadataConstant.java index d45c71568..09e17e1e8 100644 --- a/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/constant/MetadataConstant.java +++ b/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/constant/MetadataConstant.java @@ -39,14 +39,12 @@ public final class MetadataConstant { /** * Order of MetadataFirstFeignInterceptor. */ - public static int METADATA_FIRST_FEIGN_INTERCEPTOR_ORDER = Ordered.HIGHEST_PRECEDENCE - + 1; + public static int METADATA_FIRST_FEIGN_INTERCEPTOR_ORDER = Ordered.HIGHEST_PRECEDENCE + 1; /** * Order of Metadata2HeaderInterceptor. */ public static int METADATA_2_HEADER_INTERCEPTOR_ORDER = Ordered.LOWEST_PRECEDENCE; - } /** @@ -68,7 +66,5 @@ public final class MetadataConstant { * Metadata context. */ public static final String METADATA_CONTEXT = "SCT-METADATA-CONTEXT"; - } - } diff --git a/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/metadata/MetadataContext.java b/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/metadata/MetadataContext.java index 90148cd22..c172e4832 100644 --- a/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/metadata/MetadataContext.java +++ b/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/metadata/MetadataContext.java @@ -52,30 +52,25 @@ public class MetadataContext { public static String LOCAL_SERVICE; static { - String namespace = ApplicationContextAwareUtils - .getProperties("spring.cloud.polaris.namespace"); + String namespace = ApplicationContextAwareUtils.getProperties("spring.cloud.polaris.namespace"); if (StringUtils.isEmpty(namespace)) { namespace = ApplicationContextAwareUtils .getProperties("spring.cloud.polaris.discovery.namespace", "default"); } - if (StringUtils.isEmpty(namespace)) { LOG.error("namespace should not be blank. please configure spring.cloud.polaris.namespace or " + "spring.cloud.polaris.discovery.namespace"); throw new RuntimeException("namespace should not be blank. please configure spring.cloud.polaris.namespace or " + "spring.cloud.polaris.discovery.namespace"); } - LOCAL_NAMESPACE = namespace; - String serviceName = ApplicationContextAwareUtils - .getProperties("spring.cloud.polaris.service"); + String serviceName = ApplicationContextAwareUtils.getProperties("spring.cloud.polaris.service"); if (StringUtils.isEmpty(serviceName)) { serviceName = ApplicationContextAwareUtils.getProperties( "spring.cloud.polaris.discovery.service", ApplicationContextAwareUtils .getProperties("spring.application.name", null)); } - if (StringUtils.isEmpty(serviceName)) { LOG.error("service name should not be blank. please configure spring.cloud.polaris.service or " + "spring.cloud.polaris.discovery.service or spring.application.name"); @@ -91,7 +86,6 @@ public class MetadataContext { this.fragmentContexts = new ConcurrentHashMap<>(); } - public Map getFragmentContext(String fragment) { Map fragmentContext = fragmentContexts.get(fragment); if (fragmentContext == null) { diff --git a/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/metadata/MetadataContextHolder.java b/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/metadata/MetadataContextHolder.java index b270c368b..e92c526b3 100644 --- a/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/metadata/MetadataContextHolder.java +++ b/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/metadata/MetadataContextHolder.java @@ -89,7 +89,8 @@ public final class MetadataContextHolder { // Save transitive metadata to ThreadLocal. if (!CollectionUtils.isEmpty(dynamicTransitiveMetadata)) { - Map staticTransitiveMetadata = metadataContext.getFragmentContext(MetadataContext.FRAGMENT_TRANSITIVE); + Map staticTransitiveMetadata = + metadataContext.getFragmentContext(MetadataContext.FRAGMENT_TRANSITIVE); Map mergedTransitiveMetadata = new HashMap<>(); mergedTransitiveMetadata.putAll(staticTransitiveMetadata); mergedTransitiveMetadata.putAll(dynamicTransitiveMetadata); @@ -106,5 +107,4 @@ public final class MetadataContextHolder { public static void remove() { METADATA_CONTEXT.remove(); } - } diff --git a/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/metadata/StaticMetadataManager.java b/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/metadata/StaticMetadataManager.java index 5d4143b73..a717db436 100644 --- a/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/metadata/StaticMetadataManager.java +++ b/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/metadata/StaticMetadataManager.java @@ -35,18 +35,9 @@ import org.springframework.util.CollectionUtils; /** * manage metadata from env/config file/custom spi. * - *@author lepdou 2022-05-20 + * @author lepdou 2022-05-20 */ public class StaticMetadataManager { - private static final Logger LOGGER = LoggerFactory.getLogger(StaticMetadataManager.class); - - private static final String ENV_METADATA_PREFIX = "SCT_METADATA_CONTENT_"; - private static final int ENV_METADATA_PREFIX_LENGTH = ENV_METADATA_PREFIX.length(); - private static final String ENV_METADATA_CONTENT_TRANSITIVE = "SCT_METADATA_CONTENT_TRANSITIVE"; - private static final String ENV_METADATA_ZONE = "SCT_METADATA_ZONE"; - private static final String ENV_METADATA_REGION = "SCT_METADATA_REGION"; - private static final String ENV_METADATA_CAMPUS = "SCT_METADATA_CAMPUS"; - /** * the metadata key of region. */ @@ -59,7 +50,13 @@ public class StaticMetadataManager { * the metadata key of campus/datacenter. */ public static final String LOCATION_KEY_CAMPUS = "campus"; - + private static final Logger LOGGER = LoggerFactory.getLogger(StaticMetadataManager.class); + private static final String ENV_METADATA_PREFIX = "SCT_METADATA_CONTENT_"; + private static final int ENV_METADATA_PREFIX_LENGTH = ENV_METADATA_PREFIX.length(); + private static final String ENV_METADATA_CONTENT_TRANSITIVE = "SCT_METADATA_CONTENT_TRANSITIVE"; + private static final String ENV_METADATA_ZONE = "SCT_METADATA_ZONE"; + private static final String ENV_METADATA_REGION = "SCT_METADATA_REGION"; + private static final String ENV_METADATA_CAMPUS = "SCT_METADATA_CAMPUS"; private Map envMetadata; private Map envTransitiveMetadata; private Map configMetadata; diff --git a/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/metadata/config/MetadataAutoConfiguration.java b/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/metadata/config/MetadataAutoConfiguration.java index 0271297ea..6f815f2ea 100644 --- a/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/metadata/config/MetadataAutoConfiguration.java +++ b/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/metadata/config/MetadataAutoConfiguration.java @@ -62,7 +62,5 @@ public class MetadataAutoConfiguration { public GlobalFilter metadataFirstScgFilter() { return new MetadataFirstScgFilter(); } - } - } diff --git a/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/metadata/config/MetadataLocalProperties.java b/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/metadata/config/MetadataLocalProperties.java index e65a80ccd..0d0039bc3 100644 --- a/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/metadata/config/MetadataLocalProperties.java +++ b/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/metadata/config/MetadataLocalProperties.java @@ -64,5 +64,4 @@ public class MetadataLocalProperties { public void setTransitive(List transitive) { this.transitive = transitive; } - } diff --git a/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/metadata/endpoint/PolarisMetadataEndpoint.java b/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/metadata/endpoint/PolarisMetadataEndpoint.java new file mode 100644 index 000000000..360018ea2 --- /dev/null +++ b/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/metadata/endpoint/PolarisMetadataEndpoint.java @@ -0,0 +1,56 @@ +/* + * Tencent is pleased to support the open source community by making Spring Cloud Tencent available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.cloud.common.metadata.endpoint; + +import java.util.HashMap; +import java.util.Map; + +import com.tencent.cloud.common.metadata.StaticMetadataManager; + +import org.springframework.boot.actuate.endpoint.annotation.Endpoint; +import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; + +/** + * Endpoint of polaris's metadata. + * + * @author shuiqingliu + **/ +@Endpoint(id = "polaris-metadata") +public class PolarisMetadataEndpoint { + + private final StaticMetadataManager staticMetadataManager; + + public PolarisMetadataEndpoint(StaticMetadataManager staticMetadataManager) { + this.staticMetadataManager = staticMetadataManager; + } + + @ReadOperation + public Map metadata() { + Map result = new HashMap<>(); + result.put("Env", staticMetadataManager.getAllEnvMetadata()); + result.put("EnvTransitive", staticMetadataManager.getEnvTransitiveMetadata()); + result.put("ConfigTransitive", staticMetadataManager.getConfigTransitiveMetadata()); + result.put("Config", staticMetadataManager.getAllConfigMetadata()); + result.put("MergeStatic", staticMetadataManager.getMergedStaticMetadata()); + result.put("CustomSPI", staticMetadataManager.getCustomSPITransitiveMetadata()); + result.put("zone", staticMetadataManager.getZone()); + result.put("region", staticMetadataManager.getRegion()); + result.put("campus", staticMetadataManager.getCampus()); + return result; + } +} diff --git a/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/metadata/endpoint/PolarisMetadataEndpointAutoConfiguration.java b/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/metadata/endpoint/PolarisMetadataEndpointAutoConfiguration.java new file mode 100644 index 000000000..9c87587c9 --- /dev/null +++ b/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/metadata/endpoint/PolarisMetadataEndpointAutoConfiguration.java @@ -0,0 +1,44 @@ +/* + * Tencent is pleased to support the open source community by making Spring Cloud Tencent available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.cloud.common.metadata.endpoint; + +import com.tencent.cloud.common.metadata.StaticMetadataManager; + +import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnAvailableEndpoint; +import org.springframework.boot.actuate.endpoint.annotation.Endpoint; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * The AutoConfiguration for metadata endpoint. + * + * @author shuiqingliu + **/ +@Configuration(proxyBeanMethods = false) +@ConditionalOnClass(Endpoint.class) +public class PolarisMetadataEndpointAutoConfiguration { + + @Bean + @ConditionalOnMissingBean + @ConditionalOnAvailableEndpoint + public PolarisMetadataEndpoint metadataEndpoint(StaticMetadataManager staticMetadataManager) { + return new PolarisMetadataEndpoint(staticMetadataManager); + } +} diff --git a/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/metadata/filter/gateway/MetadataFirstScgFilter.java b/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/metadata/filter/gateway/MetadataFirstScgFilter.java index a79ba5323..e73c2bf70 100644 --- a/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/metadata/filter/gateway/MetadataFirstScgFilter.java +++ b/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/metadata/filter/gateway/MetadataFirstScgFilter.java @@ -50,16 +50,13 @@ public class MetadataFirstScgFilter implements GlobalFilter, Ordered { @Override public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) { // get metadata of current thread - MetadataContext metadataContext = exchange - .getAttribute(MetadataConstant.HeaderName.METADATA_CONTEXT); + MetadataContext metadataContext = exchange.getAttribute(MetadataConstant.HeaderName.METADATA_CONTEXT); if (metadataContext == null) { metadataContext = MetadataContextHolder.get(); } - exchange.getAttributes().put(MetadataConstant.HeaderName.METADATA_CONTEXT, - metadataContext); + exchange.getAttributes().put(MetadataConstant.HeaderName.METADATA_CONTEXT, metadataContext); return chain.filter(exchange); } - } diff --git a/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/pojo/PolarisServiceInstance.java b/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/pojo/PolarisServiceInstance.java index ce244db00..72693807a 100644 --- a/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/pojo/PolarisServiceInstance.java +++ b/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/pojo/PolarisServiceInstance.java @@ -89,5 +89,4 @@ public class PolarisServiceInstance implements ServiceInstance { public String getScheme() { return this.scheme; } - } diff --git a/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/spi/InstanceMetadataProvider.java b/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/spi/InstanceMetadataProvider.java index dd5f03e16..5434aa140 100644 --- a/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/spi/InstanceMetadataProvider.java +++ b/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/spi/InstanceMetadataProvider.java @@ -23,8 +23,8 @@ import java.util.Map; import java.util.Set; /** - * * Instance's custom metadata, metadata will be register to polaris server. + * * @author lepdou 2022-06-16 */ public interface InstanceMetadataProvider { diff --git a/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/util/AddressUtils.java b/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/util/AddressUtils.java index 0bda18cde..a27da82e8 100644 --- a/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/util/AddressUtils.java +++ b/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/util/AddressUtils.java @@ -50,5 +50,4 @@ public final class AddressUtils { } return addressList; } - } diff --git a/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/util/ApplicationContextAwareUtils.java b/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/util/ApplicationContextAwareUtils.java index 9c6aff74d..3ad05568a 100644 --- a/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/util/ApplicationContextAwareUtils.java +++ b/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/util/ApplicationContextAwareUtils.java @@ -63,5 +63,4 @@ public class ApplicationContextAwareUtils implements ApplicationContextAware { public static String getProperties(String key, String defaultValue) { return applicationContext.getEnvironment().getProperty(key, defaultValue); } - } diff --git a/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/util/BeanFactoryUtils.java b/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/util/BeanFactoryUtils.java index 715a154fc..a15febe0e 100644 --- a/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/util/BeanFactoryUtils.java +++ b/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/util/BeanFactoryUtils.java @@ -30,7 +30,11 @@ import org.springframework.beans.factory.support.DefaultListableBeanFactory; * the utils for bean factory. * @author lepdou 2022-05-23 */ -public class BeanFactoryUtils { +public final class BeanFactoryUtils { + + private BeanFactoryUtils() { + + } public static List getBeans(BeanFactory beanFactory, Class requiredType) { if (!(beanFactory instanceof DefaultListableBeanFactory)) { diff --git a/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/util/ExpressionLabelUtils.java b/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/util/ExpressionLabelUtils.java index a4c53ccc1..dde5bc254 100644 --- a/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/util/ExpressionLabelUtils.java +++ b/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/util/ExpressionLabelUtils.java @@ -43,7 +43,7 @@ import org.springframework.web.server.ServerWebExchange; * @author lepdou 2022-05-13 * @author cheese8 2022-06-20 */ -public class ExpressionLabelUtils { +public final class ExpressionLabelUtils { /** * the expression prefix of header label. @@ -81,6 +81,8 @@ public class ExpressionLabelUtils { * the suffix of expression. */ public static final String LABEL_SUFFIX = "}"; + private ExpressionLabelUtils() { + } public static boolean isExpressionLabel(String labelKey) { if (StringUtils.isEmpty(labelKey)) { diff --git a/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/util/JacksonUtils.java b/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/util/JacksonUtils.java index 15ca7163b..13f6a6140 100644 --- a/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/util/JacksonUtils.java +++ b/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/util/JacksonUtils.java @@ -79,9 +79,7 @@ public final class JacksonUtils { return new HashMap<>(); } catch (JsonProcessingException e) { - LOG.error( - "Json to map failed. check if the format of the json string[{}] is correct.", - jsonStr, e); + LOG.error("Json to map failed. check if the format of the json string[{}] is correct.", jsonStr, e); throw new RuntimeException("Json to map failed.", e); } } diff --git a/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/util/ReflectionUtils.java b/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/util/ReflectionUtils.java index 6c4a3353e..398fb205b 100644 --- a/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/util/ReflectionUtils.java +++ b/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/util/ReflectionUtils.java @@ -48,5 +48,4 @@ public final class ReflectionUtils { } return null; } - } diff --git a/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/util/ResourceFileUtils.java b/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/util/ResourceFileUtils.java index b5ea45d5d..66f8ae6c6 100644 --- a/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/util/ResourceFileUtils.java +++ b/spring-cloud-tencent-commons/src/main/java/com/tencent/cloud/common/util/ResourceFileUtils.java @@ -46,5 +46,4 @@ public final class ResourceFileUtils { } return ""; } - } diff --git a/spring-cloud-tencent-commons/src/main/resources/META-INF/spring.factories b/spring-cloud-tencent-commons/src/main/resources/META-INF/spring.factories index ba9f2b867..4c54d3372 100644 --- a/spring-cloud-tencent-commons/src/main/resources/META-INF/spring.factories +++ b/spring-cloud-tencent-commons/src/main/resources/META-INF/spring.factories @@ -1,3 +1,4 @@ org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ com.tencent.cloud.common.util.ApplicationContextAwareUtils,\ - com.tencent.cloud.common.metadata.config.MetadataAutoConfiguration + com.tencent.cloud.common.metadata.config.MetadataAutoConfiguration,\ + com.tencent.cloud.common.metadata.endpoint.PolarisMetadataEndpointAutoConfiguration diff --git a/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/metadata/MetadataContextHolderTest.java b/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/metadata/MetadataContextHolderTest.java index 9695b4d48..f2073f21a 100644 --- a/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/metadata/MetadataContextHolderTest.java +++ b/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/metadata/MetadataContextHolderTest.java @@ -37,7 +37,8 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = MetadataContextHolderTest.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 MetadataContextHolderTest { @Test @@ -78,5 +79,4 @@ public class MetadataContextHolderTest { protected static class TestApplication { } - } diff --git a/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/metadata/StaticMetadataManagerTest.java b/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/metadata/StaticMetadataManagerTest.java index 3c8ae438d..b2aa08cd4 100644 --- a/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/metadata/StaticMetadataManagerTest.java +++ b/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/metadata/StaticMetadataManagerTest.java @@ -182,5 +182,4 @@ public class StaticMetadataManagerTest { return null; } } - } diff --git a/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/metadata/config/MetadataAutoConfigurationTest.java b/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/metadata/config/MetadataAutoConfigurationTest.java index fb19efb18..e73ee3a2b 100644 --- a/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/metadata/config/MetadataAutoConfigurationTest.java +++ b/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/metadata/config/MetadataAutoConfigurationTest.java @@ -38,7 +38,8 @@ public class MetadataAutoConfigurationTest { private final WebApplicationContextRunner webApplicationContextRunner = new WebApplicationContextRunner(); - private final ReactiveWebApplicationContextRunner reactiveWebApplicationContextRunner = new ReactiveWebApplicationContextRunner(); + private final ReactiveWebApplicationContextRunner reactiveWebApplicationContextRunner = + new ReactiveWebApplicationContextRunner(); /** * No any web application. @@ -84,5 +85,4 @@ public class MetadataAutoConfigurationTest { Assertions.assertThat(context).hasSingleBean(MetadataFirstScgFilter.class); }); } - } diff --git a/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/metadata/config/MetadataLocalPropertiesTest.java b/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/metadata/config/MetadataLocalPropertiesTest.java index 3fdb2f441..a4a9a4e29 100644 --- a/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/metadata/config/MetadataLocalPropertiesTest.java +++ b/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/metadata/config/MetadataLocalPropertiesTest.java @@ -34,7 +34,8 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = MetadataLocalPropertiesTest.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 MetadataLocalPropertiesTest { @Autowired @@ -59,5 +60,4 @@ public class MetadataLocalPropertiesTest { protected static class TestApplication { } - } diff --git a/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/metadata/endpoint/PolarisMetadataEndpointTests.java b/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/metadata/endpoint/PolarisMetadataEndpointTests.java new file mode 100644 index 000000000..d20a2fd4f --- /dev/null +++ b/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/metadata/endpoint/PolarisMetadataEndpointTests.java @@ -0,0 +1,58 @@ +/* + * Tencent is pleased to support the open source community by making Spring Cloud Tencent available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + */ + + +package com.tencent.cloud.common.metadata.endpoint; + +import java.util.HashMap; +import java.util.Map; + +import com.tencent.cloud.common.metadata.StaticMetadataManager; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +/** + * Test for polaris metadata endpoint. + * + * @author shuiqingliu + */ +@RunWith(MockitoJUnitRunner.class) +public class PolarisMetadataEndpointTests { + + @Mock + private StaticMetadataManager staticMetadataManager; + + @Test + public void testPolarisMetadataEndpoint() { + Map envMetadata = new HashMap<>(); + envMetadata.put("k1", "v1"); + envMetadata.put("k2", "v2"); + envMetadata.put("k3", "v3"); + + when(staticMetadataManager.getAllEnvMetadata()).thenReturn(envMetadata); + + PolarisMetadataEndpoint polarisMetadataEndpoint = new PolarisMetadataEndpoint(staticMetadataManager); + Map metaMap = polarisMetadataEndpoint.metadata(); + assertThat(envMetadata).isEqualTo(metaMap.get("Env")); + } +} diff --git a/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/util/AddressUtilsTest.java b/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/util/AddressUtilsTest.java index 8040e7add..ca50c3604 100644 --- a/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/util/AddressUtilsTest.java +++ b/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/util/AddressUtilsTest.java @@ -26,8 +26,9 @@ import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; /** - * test for {@link AddressUtils} - *@author lepdou 2022-05-27 + * test for {@link AddressUtils}. + * + * @author lepdou 2022-05-27 */ @RunWith(MockitoJUnitRunner.class) public class AddressUtilsTest { diff --git a/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/util/ExpressionLabelUtilsTest.java b/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/util/ExpressionLabelUtilsTest.java index 0dedc4698..76666482b 100644 --- a/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/util/ExpressionLabelUtilsTest.java +++ b/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/util/ExpressionLabelUtilsTest.java @@ -37,9 +37,9 @@ import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.server.MockServerWebExchange; /** - * test for {@link ExpressionLabelUtils} - * @author lepdou 2022-05-27 - * @auther cheese8 2022-06-20 + * test for {@link ExpressionLabelUtils}. + * + * @author lepdou 2022-05-27, cheese8 */ @RunWith(MockitoJUnitRunner.class) public class ExpressionLabelUtilsTest { @@ -210,5 +210,4 @@ public class ExpressionLabelUtilsTest { Assert.assertNull(result.get(invalidLabel8)); Assert.assertNull(result.get(invalidLabel9)); } - } diff --git a/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/util/JacksonUtilsTest.java b/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/util/JacksonUtilsTest.java index db0868dff..e07dcceb2 100644 --- a/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/util/JacksonUtilsTest.java +++ b/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/util/JacksonUtilsTest.java @@ -26,12 +26,12 @@ import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatThrownBy; /** * Test for {@link JacksonUtils}. * - * @author lepdou, Haotian Zhang + * @author lepdou, Haotian Zhang, cheese8 */ @RunWith(MockitoJUnitRunner.class) public class JacksonUtilsTest { @@ -42,10 +42,7 @@ public class JacksonUtilsTest { sourceMap.put("k1", "v1"); sourceMap.put("k2", "v2"); sourceMap.put("k3", "v3"); - - String jsonStr = JacksonUtils.serialize2Json(sourceMap); - - assertThat(jsonStr).isEqualTo("{\"k1\":\"v1\",\"k2\":\"v2\",\"k3\":\"v3\"}"); + assertThat(JacksonUtils.serialize2Json(sourceMap)).isEqualTo("{\"k1\":\"v1\",\"k2\":\"v2\",\"k3\":\"v3\"}"); } @Test @@ -56,20 +53,19 @@ public class JacksonUtilsTest { assertThat(map.get("k1")).isEqualTo("v1"); assertThat(map.get("k2")).isEqualTo("v2"); assertThat(map.get("k3")).isEqualTo("v3"); + } - assertThat(JacksonUtils.deserialize2Map("")).isNotNull(); - assertThat(JacksonUtils.deserialize2Map("")).isEmpty(); + @Test + public void testDeserializeBlankIntoEmptyMap() { + Map map = JacksonUtils.deserialize2Map(""); + assertThat(map).isNotNull(); + assertThat(map).isEmpty(); + } - jsonStr = "{\"k1\":\"v1\",\"k2\":\"v2\",\"k3\":\"v3\""; - try { - JacksonUtils.deserialize2Map(jsonStr); - fail("RuntimeException should be thrown."); - } - catch (RuntimeException exception) { - assertThat(exception.getMessage()).isEqualTo("Json to map failed."); - } - catch (Throwable throwable) { - fail("RuntimeException should be thrown."); - } + @Test + public void testDeserializeThrowsRuntimeException() { + String jsonStr = "{\"k1\":\"v1\",\"k2\":\"v2\",\"k3\":\"v3\""; + assertThatThrownBy(() -> JacksonUtils.deserialize2Map(jsonStr)) + .isExactlyInstanceOf(RuntimeException.class).hasMessage("Json to map failed."); } } diff --git a/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/util/ResourceFileUtilsTest.java b/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/util/ResourceFileUtilsTest.java index 769d99ce7..a3cb8a96c 100644 --- a/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/util/ResourceFileUtilsTest.java +++ b/spring-cloud-tencent-commons/src/test/java/com/tencent/cloud/common/util/ResourceFileUtilsTest.java @@ -26,8 +26,9 @@ import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; /** - * test for {@link ResourceFileUtils} - *@author lepdou 2022-05-27 + * test for {@link ResourceFileUtils}. + * + * @author lepdou 2022-05-27 */ @RunWith(MockitoJUnitRunner.class) public class ResourceFileUtilsTest { diff --git a/spring-cloud-tencent-examples/metadata-transfer-example/metadata-caller-service/src/main/java/com/tencent/cloud/metadata/service/caller/MetadataCallerService.java b/spring-cloud-tencent-examples/metadata-transfer-example/metadata-caller-service/src/main/java/com/tencent/cloud/metadata/service/caller/MetadataCallerService.java index a586c7e72..ae1e49c64 100644 --- a/spring-cloud-tencent-examples/metadata-transfer-example/metadata-caller-service/src/main/java/com/tencent/cloud/metadata/service/caller/MetadataCallerService.java +++ b/spring-cloud-tencent-examples/metadata-transfer-example/metadata-caller-service/src/main/java/com/tencent/cloud/metadata/service/caller/MetadataCallerService.java @@ -19,7 +19,6 @@ package com.tencent.cloud.metadata.service.caller; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.context.annotation.Bean; @@ -31,7 +30,6 @@ import org.springframework.web.client.RestTemplate; * @author Palmer Xu */ @SpringBootApplication -@EnableDiscoveryClient @EnableFeignClients public class MetadataCallerService { diff --git a/spring-cloud-tencent-examples/metadata-transfer-example/metadata-caller-service/src/main/resources/bootstrap.yml b/spring-cloud-tencent-examples/metadata-transfer-example/metadata-caller-service/src/main/resources/bootstrap.yml index 89d1f233b..a390f51a6 100644 --- a/spring-cloud-tencent-examples/metadata-transfer-example/metadata-caller-service/src/main/resources/bootstrap.yml +++ b/spring-cloud-tencent-examples/metadata-transfer-example/metadata-caller-service/src/main/resources/bootstrap.yml @@ -24,3 +24,9 @@ spring: # Assigned which metadata key-value will be passed along the link transitive: - CUSTOM-METADATA-KEY-TRANSITIVE +management: + endpoints: + web: + exposure: + include: + - polaris-metadata \ No newline at end of file diff --git a/spring-cloud-tencent-examples/polaris-circuitbreaker-example/polaris-circuitbreaker-example-a/src/main/java/com/tencent/cloud/polaris/circuitbreaker/example/ServiceA.java b/spring-cloud-tencent-examples/polaris-circuitbreaker-example/polaris-circuitbreaker-example-a/src/main/java/com/tencent/cloud/polaris/circuitbreaker/example/ServiceA.java index 1c96db6c9..3db7df8f3 100644 --- a/spring-cloud-tencent-examples/polaris-circuitbreaker-example/polaris-circuitbreaker-example-a/src/main/java/com/tencent/cloud/polaris/circuitbreaker/example/ServiceA.java +++ b/spring-cloud-tencent-examples/polaris-circuitbreaker-example/polaris-circuitbreaker-example-a/src/main/java/com/tencent/cloud/polaris/circuitbreaker/example/ServiceA.java @@ -35,7 +35,7 @@ import org.springframework.web.client.RestTemplate; public class ServiceA { public static void main(String[] args) { - SpringApplication.run(ServiceA.class); + SpringApplication.run(ServiceA.class, args); } @Bean @@ -43,5 +43,4 @@ public class ServiceA { public RestTemplate restTemplate() { return new RestTemplate(); } - } diff --git a/spring-cloud-tencent-examples/polaris-circuitbreaker-example/polaris-circuitbreaker-example-a/src/main/java/com/tencent/cloud/polaris/circuitbreaker/example/ServiceAController.java b/spring-cloud-tencent-examples/polaris-circuitbreaker-example/polaris-circuitbreaker-example-a/src/main/java/com/tencent/cloud/polaris/circuitbreaker/example/ServiceAController.java index 29768d584..79ba2c0ef 100644 --- a/spring-cloud-tencent-examples/polaris-circuitbreaker-example/polaris-circuitbreaker-example-a/src/main/java/com/tencent/cloud/polaris/circuitbreaker/example/ServiceAController.java +++ b/spring-cloud-tencent-examples/polaris-circuitbreaker-example/polaris-circuitbreaker-example-a/src/main/java/com/tencent/cloud/polaris/circuitbreaker/example/ServiceAController.java @@ -64,5 +64,4 @@ public class ServiceAController { String.class); return entity.getBody(); } - } diff --git a/spring-cloud-tencent-examples/polaris-circuitbreaker-example/polaris-circuitbreaker-example-b/src/main/java/com/tencent/cloud/polaris/circuitbreaker/example/ServiceB.java b/spring-cloud-tencent-examples/polaris-circuitbreaker-example/polaris-circuitbreaker-example-b/src/main/java/com/tencent/cloud/polaris/circuitbreaker/example/ServiceB.java index 7354da537..c8c32bf24 100644 --- a/spring-cloud-tencent-examples/polaris-circuitbreaker-example/polaris-circuitbreaker-example-b/src/main/java/com/tencent/cloud/polaris/circuitbreaker/example/ServiceB.java +++ b/spring-cloud-tencent-examples/polaris-circuitbreaker-example/polaris-circuitbreaker-example-b/src/main/java/com/tencent/cloud/polaris/circuitbreaker/example/ServiceB.java @@ -29,7 +29,6 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; public class ServiceB { public static void main(String[] args) { - SpringApplication.run(ServiceB.class); + SpringApplication.run(ServiceB.class, args); } - } diff --git a/spring-cloud-tencent-examples/polaris-circuitbreaker-example/polaris-circuitbreaker-example-b/src/main/java/com/tencent/cloud/polaris/circuitbreaker/example/ServiceBController.java b/spring-cloud-tencent-examples/polaris-circuitbreaker-example/polaris-circuitbreaker-example-b/src/main/java/com/tencent/cloud/polaris/circuitbreaker/example/ServiceBController.java index 67540c2c9..99b8410d8 100644 --- a/spring-cloud-tencent-examples/polaris-circuitbreaker-example/polaris-circuitbreaker-example-b/src/main/java/com/tencent/cloud/polaris/circuitbreaker/example/ServiceBController.java +++ b/spring-cloud-tencent-examples/polaris-circuitbreaker-example/polaris-circuitbreaker-example-b/src/main/java/com/tencent/cloud/polaris/circuitbreaker/example/ServiceBController.java @@ -18,7 +18,6 @@ package com.tencent.cloud.polaris.circuitbreaker.example; -import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @@ -32,21 +31,12 @@ import org.springframework.web.bind.annotation.RestController; @RequestMapping("/example/service/b") public class ServiceBController { - @Value("${is-throw-runtime-exception:#{false}}") - private boolean isThrowRuntimeException; - /** * Get service information. * @return service information */ @GetMapping("/info") public String info() { - if (isThrowRuntimeException) { - throw new RuntimeException("failed for call my service"); - } - else { - return "hello world ! I'm a service B1"; - } + return "hello world ! I'm a service B1"; } - } diff --git a/spring-cloud-tencent-examples/polaris-circuitbreaker-example/polaris-circuitbreaker-example-b/src/main/resources/bootstrap.yml b/spring-cloud-tencent-examples/polaris-circuitbreaker-example/polaris-circuitbreaker-example-b/src/main/resources/bootstrap.yml index 4aba50500..3805dfa5e 100644 --- a/spring-cloud-tencent-examples/polaris-circuitbreaker-example/polaris-circuitbreaker-example-b/src/main/resources/bootstrap.yml +++ b/spring-cloud-tencent-examples/polaris-circuitbreaker-example/polaris-circuitbreaker-example-b/src/main/resources/bootstrap.yml @@ -8,4 +8,3 @@ spring: address: grpc://183.47.111.80:8091 namespace: default enabled: true -is-throw-runtime-exception: false diff --git a/spring-cloud-tencent-examples/polaris-circuitbreaker-example/polaris-circuitbreaker-example-b2/src/main/java/com/tencent/cloud/polaris/ciruitbreaker/example/ServiceB2.java b/spring-cloud-tencent-examples/polaris-circuitbreaker-example/polaris-circuitbreaker-example-b2/src/main/java/com/tencent/cloud/polaris/ciruitbreaker/example/ServiceB2.java index 4aacc0d22..fb6bdc687 100644 --- a/spring-cloud-tencent-examples/polaris-circuitbreaker-example/polaris-circuitbreaker-example-b2/src/main/java/com/tencent/cloud/polaris/ciruitbreaker/example/ServiceB2.java +++ b/spring-cloud-tencent-examples/polaris-circuitbreaker-example/polaris-circuitbreaker-example-b2/src/main/java/com/tencent/cloud/polaris/ciruitbreaker/example/ServiceB2.java @@ -30,7 +30,6 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; public class ServiceB2 { public static void main(String[] args) { - SpringApplication.run(ServiceB2.class); + SpringApplication.run(ServiceB2.class, args); } - } diff --git a/spring-cloud-tencent-examples/polaris-circuitbreaker-example/polaris-circuitbreaker-example-b2/src/main/java/com/tencent/cloud/polaris/ciruitbreaker/example/ServiceBController.java b/spring-cloud-tencent-examples/polaris-circuitbreaker-example/polaris-circuitbreaker-example-b2/src/main/java/com/tencent/cloud/polaris/ciruitbreaker/example/ServiceBController.java index 7e4bb9b4c..83dc45303 100644 --- a/spring-cloud-tencent-examples/polaris-circuitbreaker-example/polaris-circuitbreaker-example-b2/src/main/java/com/tencent/cloud/polaris/ciruitbreaker/example/ServiceBController.java +++ b/spring-cloud-tencent-examples/polaris-circuitbreaker-example/polaris-circuitbreaker-example-b2/src/main/java/com/tencent/cloud/polaris/ciruitbreaker/example/ServiceBController.java @@ -18,9 +18,10 @@ package com.tencent.cloud.polaris.ciruitbreaker.example; -import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; /** @@ -32,21 +33,13 @@ import org.springframework.web.bind.annotation.RestController; @RequestMapping("/example/service/b") public class ServiceBController { - @Value("${is-throw-runtime-exception:#{false}}") - private boolean isThrowRuntimeException; - /** * Get service information. * @return service information */ @GetMapping("/info") + @ResponseStatus(value = HttpStatus.BAD_GATEWAY, reason = "failed for call my service") public String info() { - if (isThrowRuntimeException) { - throw new RuntimeException("failed for call my service"); - } - else { - return "hello world ! I'm a service B2"; - } + return "failed for call service B2"; } - } diff --git a/spring-cloud-tencent-examples/polaris-circuitbreaker-example/polaris-circuitbreaker-example-b2/src/main/resources/bootstrap.yml b/spring-cloud-tencent-examples/polaris-circuitbreaker-example/polaris-circuitbreaker-example-b2/src/main/resources/bootstrap.yml index b150a5424..f3720f09c 100644 --- a/spring-cloud-tencent-examples/polaris-circuitbreaker-example/polaris-circuitbreaker-example-b2/src/main/resources/bootstrap.yml +++ b/spring-cloud-tencent-examples/polaris-circuitbreaker-example/polaris-circuitbreaker-example-b2/src/main/resources/bootstrap.yml @@ -8,4 +8,3 @@ spring: address: grpc://183.47.111.80:8091 namespace: default enabled: true -is-throw-runtime-exception: true diff --git a/spring-cloud-tencent-examples/polaris-config-example/pom.xml b/spring-cloud-tencent-examples/polaris-config-example/pom.xml index cef91e5a3..bb7ef026e 100644 --- a/spring-cloud-tencent-examples/polaris-config-example/pom.xml +++ b/spring-cloud-tencent-examples/polaris-config-example/pom.xml @@ -24,6 +24,41 @@ com.tencent.cloud spring-cloud-starter-tencent-polaris-config + + + org.springframework.boot + spring-boot-starter-actuator + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + + + + org.apache.maven.plugins + maven-source-plugin + 3.2.0 + + + attach-sources + + jar + + + + + + + diff --git a/spring-cloud-tencent-examples/polaris-config-example/src/main/resources/bootstrap.yml b/spring-cloud-tencent-examples/polaris-config-example/src/main/resources/bootstrap.yml index 38ed7eed0..1f257a787 100644 --- a/spring-cloud-tencent-examples/polaris-config-example/src/main/resources/bootstrap.yml +++ b/spring-cloud-tencent-examples/polaris-config-example/src/main/resources/bootstrap.yml @@ -12,3 +12,9 @@ spring: groups: - name: ${spring.application.name} # group name files: [ "config/application.properties", "config/bootstrap.yml" ] # config/application.properties takes precedence over config/bootstrap.yml +management: + endpoints: + web: + exposure: + include: + - polaris-config diff --git a/spring-cloud-tencent-examples/polaris-discovery-example/discovery-caller-service/src/main/java/com/tencent/cloud/polaris/discovery/service/caller/DiscoveryCallerService.java b/spring-cloud-tencent-examples/polaris-discovery-example/discovery-caller-service/src/main/java/com/tencent/cloud/polaris/discovery/service/caller/DiscoveryCallerService.java index 55fcf01ac..0eae4b427 100644 --- a/spring-cloud-tencent-examples/polaris-discovery-example/discovery-caller-service/src/main/java/com/tencent/cloud/polaris/discovery/service/caller/DiscoveryCallerService.java +++ b/spring-cloud-tencent-examples/polaris-discovery-example/discovery-caller-service/src/main/java/com/tencent/cloud/polaris/discovery/service/caller/DiscoveryCallerService.java @@ -19,7 +19,6 @@ package com.tencent.cloud.polaris.discovery.service.caller; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.context.annotation.Bean; @@ -31,7 +30,6 @@ import org.springframework.web.client.RestTemplate; * @author Haotian Zhang */ @SpringBootApplication -@EnableDiscoveryClient @EnableFeignClients public class DiscoveryCallerService { diff --git a/spring-cloud-tencent-examples/polaris-discovery-example/discovery-caller-service/src/main/resources/bootstrap.yml b/spring-cloud-tencent-examples/polaris-discovery-example/discovery-caller-service/src/main/resources/bootstrap.yml index e9ccc1f29..544193b7e 100644 --- a/spring-cloud-tencent-examples/polaris-discovery-example/discovery-caller-service/src/main/resources/bootstrap.yml +++ b/spring-cloud-tencent-examples/polaris-discovery-example/discovery-caller-service/src/main/resources/bootstrap.yml @@ -32,3 +32,9 @@ spring: # client: # serviceUrl: # defaultZone: http://127.0.0.1:7654/eureka/ +management: + endpoints: + web: + exposure: + include: + - polaris-discovery \ No newline at end of file diff --git a/spring-cloud-tencent-examples/polaris-gateway-example/README.md b/spring-cloud-tencent-examples/polaris-gateway-example/README.md index 43bd680f6..b1bb35671 100644 --- a/spring-cloud-tencent-examples/polaris-gateway-example/README.md +++ b/spring-cloud-tencent-examples/polaris-gateway-example/README.md @@ -2,7 +2,7 @@ ## Example Introduction -This example shows how to use ```spring-cloud-tencent-polaris-gateway`` in Spring Cloud project for its features. +This example shows how to use ```spring-cloud-tencent-polaris-gateway``` in Spring Cloud project for its features. This example contains ```gateway-zuul-service```, ```gateway-scg-service``` and ```gateway-callee-service```. ```gateway-zuul-service``` and ```gateway-scg-service``` invoke ```gateway-callee-service```. diff --git a/spring-cloud-tencent-examples/polaris-gateway-example/gateway-zuul-service/src/main/resources/bootstrap.yml b/spring-cloud-tencent-examples/polaris-gateway-example/gateway-zuul-service/src/main/resources/bootstrap.yml index 0ed6cb16c..133406e02 100644 --- a/spring-cloud-tencent-examples/polaris-gateway-example/gateway-zuul-service/src/main/resources/bootstrap.yml +++ b/spring-cloud-tencent-examples/polaris-gateway-example/gateway-zuul-service/src/main/resources/bootstrap.yml @@ -1,6 +1,6 @@ server: session-timeout: 1800 - port: 48082 + port: 48084 spring: application: name: GatewayZuulService diff --git a/spring-cloud-tencent-examples/polaris-ratelimit-example/ratelimit-callee-service/pom.xml b/spring-cloud-tencent-examples/polaris-ratelimit-example/ratelimit-callee-service/pom.xml index cd9f48757..f7cbb1e6f 100644 --- a/spring-cloud-tencent-examples/polaris-ratelimit-example/ratelimit-callee-service/pom.xml +++ b/spring-cloud-tencent-examples/polaris-ratelimit-example/ratelimit-callee-service/pom.xml @@ -28,6 +28,10 @@ spring-cloud-starter-tencent-polaris-ratelimit + + org.springframework.boot + spring-boot-starter-actuator + diff --git a/spring-cloud-tencent-examples/polaris-ratelimit-example/ratelimit-callee-service/src/main/resources/bootstrap.yml b/spring-cloud-tencent-examples/polaris-ratelimit-example/ratelimit-callee-service/src/main/resources/bootstrap.yml index 37c986394..6741bde11 100644 --- a/spring-cloud-tencent-examples/polaris-ratelimit-example/ratelimit-callee-service/src/main/resources/bootstrap.yml +++ b/spring-cloud-tencent-examples/polaris-ratelimit-example/ratelimit-callee-service/src/main/resources/bootstrap.yml @@ -12,3 +12,10 @@ spring: enabled: true rejectRequestTipsFilePath: reject-tips.html maxQueuingTime: 500 + +management: + endpoints: + web: + exposure: + include: + - polaris-ratelimit \ No newline at end of file diff --git a/spring-cloud-tencent-examples/polaris-router-example/router-caller-service/src/main/java/com/tencent/cloud/polaris/router/example/RouterCallerApplication.java b/spring-cloud-tencent-examples/polaris-router-example/router-caller-service/src/main/java/com/tencent/cloud/polaris/router/example/RouterCallerApplication.java index 824a1226f..ac0547a71 100644 --- a/spring-cloud-tencent-examples/polaris-router-example/router-caller-service/src/main/java/com/tencent/cloud/polaris/router/example/RouterCallerApplication.java +++ b/spring-cloud-tencent-examples/polaris-router-example/router-caller-service/src/main/java/com/tencent/cloud/polaris/router/example/RouterCallerApplication.java @@ -20,7 +20,6 @@ package com.tencent.cloud.polaris.router.example; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.context.annotation.Bean; @@ -32,7 +31,6 @@ import org.springframework.web.client.RestTemplate; * @author lepdou 2022-04-06 */ @SpringBootApplication -@EnableDiscoveryClient @EnableFeignClients public class RouterCallerApplication { diff --git a/spring-cloud-tencent-examples/polaris-router-grayrelease-example/router-grayrelease-frontend/src/main/java/com/tencent/cloud/polaris/router/grayrelease/front/GrayReleaseFrontApplication.java b/spring-cloud-tencent-examples/polaris-router-grayrelease-example/router-grayrelease-frontend/src/main/java/com/tencent/cloud/polaris/router/grayrelease/front/GrayReleaseFrontApplication.java index 6d8653eeb..79948b3e7 100644 --- a/spring-cloud-tencent-examples/polaris-router-grayrelease-example/router-grayrelease-frontend/src/main/java/com/tencent/cloud/polaris/router/grayrelease/front/GrayReleaseFrontApplication.java +++ b/spring-cloud-tencent-examples/polaris-router-grayrelease-example/router-grayrelease-frontend/src/main/java/com/tencent/cloud/polaris/router/grayrelease/front/GrayReleaseFrontApplication.java @@ -19,11 +19,9 @@ package com.tencent.cloud.polaris.router.grayrelease.front; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.openfeign.EnableFeignClients; @SpringBootApplication -@EnableDiscoveryClient @EnableFeignClients public class GrayReleaseFrontApplication { diff --git a/spring-cloud-tencent-examples/polaris-router-grayrelease-example/router-grayrelease-gateway/src/main/java/com/tencent/cloud/polaris/router/grayrelease/gateway/GrayReleaseGatewayApplication.java b/spring-cloud-tencent-examples/polaris-router-grayrelease-example/router-grayrelease-gateway/src/main/java/com/tencent/cloud/polaris/router/grayrelease/gateway/GrayReleaseGatewayApplication.java index a7b5a115e..77819ea41 100644 --- a/spring-cloud-tencent-examples/polaris-router-grayrelease-example/router-grayrelease-gateway/src/main/java/com/tencent/cloud/polaris/router/grayrelease/gateway/GrayReleaseGatewayApplication.java +++ b/spring-cloud-tencent-examples/polaris-router-grayrelease-example/router-grayrelease-gateway/src/main/java/com/tencent/cloud/polaris/router/grayrelease/gateway/GrayReleaseGatewayApplication.java @@ -19,11 +19,9 @@ package com.tencent.cloud.polaris.router.grayrelease.gateway; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.openfeign.EnableFeignClients; @SpringBootApplication -@EnableDiscoveryClient @EnableFeignClients public class GrayReleaseGatewayApplication { diff --git a/spring-cloud-tencent-examples/polaris-router-grayrelease-example/router-grayrelease-middle/src/main/java/com/tencent/cloud/polaris/router/grayrelease/middle/GrayReleaseMiddleApplication.java b/spring-cloud-tencent-examples/polaris-router-grayrelease-example/router-grayrelease-middle/src/main/java/com/tencent/cloud/polaris/router/grayrelease/middle/GrayReleaseMiddleApplication.java index 4857030e2..3003093ee 100644 --- a/spring-cloud-tencent-examples/polaris-router-grayrelease-example/router-grayrelease-middle/src/main/java/com/tencent/cloud/polaris/router/grayrelease/middle/GrayReleaseMiddleApplication.java +++ b/spring-cloud-tencent-examples/polaris-router-grayrelease-example/router-grayrelease-middle/src/main/java/com/tencent/cloud/polaris/router/grayrelease/middle/GrayReleaseMiddleApplication.java @@ -19,11 +19,9 @@ package com.tencent.cloud.polaris.router.grayrelease.middle; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.openfeign.EnableFeignClients; @SpringBootApplication -@EnableDiscoveryClient @EnableFeignClients public class GrayReleaseMiddleApplication { diff --git a/spring-cloud-tencent-polaris-context/src/main/java/com/tencent/cloud/polaris/context/ModifyAddress.java b/spring-cloud-tencent-polaris-context/src/main/java/com/tencent/cloud/polaris/context/ModifyAddress.java index b57cbfe91..a7a1e551c 100644 --- a/spring-cloud-tencent-polaris-context/src/main/java/com/tencent/cloud/polaris/context/ModifyAddress.java +++ b/spring-cloud-tencent-polaris-context/src/main/java/com/tencent/cloud/polaris/context/ModifyAddress.java @@ -53,5 +53,4 @@ public class ModifyAddress implements PolarisConfigModifier { public int getOrder() { return ContextConstant.ModifierOrder.FIRST; } - } diff --git a/spring-cloud-tencent-polaris-context/src/main/java/com/tencent/cloud/polaris/context/PolarisConfigModifier.java b/spring-cloud-tencent-polaris-context/src/main/java/com/tencent/cloud/polaris/context/PolarisConfigModifier.java index 0152b7b6b..3cae11cb2 100644 --- a/spring-cloud-tencent-polaris-context/src/main/java/com/tencent/cloud/polaris/context/PolarisConfigModifier.java +++ b/spring-cloud-tencent-polaris-context/src/main/java/com/tencent/cloud/polaris/context/PolarisConfigModifier.java @@ -37,5 +37,4 @@ public interface PolarisConfigModifier { * @return order */ int getOrder(); - } diff --git a/spring-cloud-tencent-polaris-context/src/main/java/com/tencent/cloud/polaris/context/PostInitPolarisSDKContext.java b/spring-cloud-tencent-polaris-context/src/main/java/com/tencent/cloud/polaris/context/PostInitPolarisSDKContext.java index 014ca5ba2..bf41c50bd 100644 --- a/spring-cloud-tencent-polaris-context/src/main/java/com/tencent/cloud/polaris/context/PostInitPolarisSDKContext.java +++ b/spring-cloud-tencent-polaris-context/src/main/java/com/tencent/cloud/polaris/context/PostInitPolarisSDKContext.java @@ -26,7 +26,8 @@ import org.apache.commons.lang.StringUtils; /** * After all configurations are loaded, post-initialize SDKContext. - *@author lepdou 2022-06-28 + * + * @author lepdou 2022-06-28 */ public class PostInitPolarisSDKContext { diff --git a/spring-cloud-tencent-polaris-context/src/main/java/com/tencent/cloud/polaris/context/ServiceRuleManager.java b/spring-cloud-tencent-polaris-context/src/main/java/com/tencent/cloud/polaris/context/ServiceRuleManager.java index 1a0af32b4..06d71f65c 100644 --- a/spring-cloud-tencent-polaris-context/src/main/java/com/tencent/cloud/polaris/context/ServiceRuleManager.java +++ b/spring-cloud-tencent-polaris-context/src/main/java/com/tencent/cloud/polaris/context/ServiceRuleManager.java @@ -38,7 +38,7 @@ import com.tencent.polaris.client.pb.RoutingProto; /** * the manager of service governance rules. for example: rate limit rule, router rules. * - *@author lepdou 2022-05-13 + * @author lepdou 2022-05-13 */ public class ServiceRuleManager { diff --git a/spring-cloud-tencent-polaris-context/src/main/java/com/tencent/cloud/polaris/context/config/PolarisContextPostConfiguration.java b/spring-cloud-tencent-polaris-context/src/main/java/com/tencent/cloud/polaris/context/config/PolarisContextPostConfiguration.java index f55397462..3ee8de395 100644 --- a/spring-cloud-tencent-polaris-context/src/main/java/com/tencent/cloud/polaris/context/config/PolarisContextPostConfiguration.java +++ b/spring-cloud-tencent-polaris-context/src/main/java/com/tencent/cloud/polaris/context/config/PolarisContextPostConfiguration.java @@ -27,13 +27,15 @@ import org.springframework.context.annotation.Configuration; /** * Post-initialization operations after the application initialization phase is completed. - *@author lepdou 2022-06-28 + * + * @author lepdou 2022-06-28 */ @Configuration public class PolarisContextPostConfiguration { @Bean - public PostInitPolarisSDKContext postInitPolarisSDKContext(SDKContext sdkContext, StaticMetadataManager staticMetadataManager) { + public PostInitPolarisSDKContext postInitPolarisSDKContext( + SDKContext sdkContext, StaticMetadataManager staticMetadataManager) { return new PostInitPolarisSDKContext(sdkContext, staticMetadataManager); } } diff --git a/spring-cloud-tencent-polaris-context/src/test/java/com/tencent/cloud/polaris/context/PolarisContextAutoConfigurationTest.java b/spring-cloud-tencent-polaris-context/src/test/java/com/tencent/cloud/polaris/context/PolarisContextAutoConfigurationTest.java index 2a926cc12..21e0868b3 100644 --- a/spring-cloud-tencent-polaris-context/src/test/java/com/tencent/cloud/polaris/context/PolarisContextAutoConfigurationTest.java +++ b/spring-cloud-tencent-polaris-context/src/test/java/com/tencent/cloud/polaris/context/PolarisContextAutoConfigurationTest.java @@ -27,6 +27,8 @@ import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.cloud.commons.util.UtilAutoConfiguration; /** + * Test for {@link PolarisContextAutoConfiguration}. + * * @author liaochuntao */ public class PolarisContextAutoConfigurationTest { @@ -44,5 +46,4 @@ public class PolarisContextAutoConfigurationTest { Assert.assertNotNull(sdkContext); }); } - } diff --git a/spring-cloud-tencent-polaris-context/src/test/java/com/tencent/cloud/polaris/context/PolarisContextGetHostTest.java b/spring-cloud-tencent-polaris-context/src/test/java/com/tencent/cloud/polaris/context/PolarisContextGetHostTest.java index 9985113df..1bf745f5c 100644 --- a/spring-cloud-tencent-polaris-context/src/test/java/com/tencent/cloud/polaris/context/PolarisContextGetHostTest.java +++ b/spring-cloud-tencent-polaris-context/src/test/java/com/tencent/cloud/polaris/context/PolarisContextGetHostTest.java @@ -49,5 +49,4 @@ public class PolarisContextGetHostTest { Assert.assertEquals(bindIP, "192.168.1.1"); Assert.assertEquals(polarisContextProperties.getNamespace(), "dev"); } - } diff --git a/spring-cloud-tencent-polaris-loadbalancer/pom.xml b/spring-cloud-tencent-polaris-loadbalancer/pom.xml index 7475e83fb..2a26fcd8f 100644 --- a/spring-cloud-tencent-polaris-loadbalancer/pom.xml +++ b/spring-cloud-tencent-polaris-loadbalancer/pom.xml @@ -55,7 +55,12 @@ mockito-inline test + + com.tencent.polaris + polaris-discovery-client + test + - + diff --git a/spring-cloud-tencent-polaris-loadbalancer/src/main/java/com/tencent/cloud/polaris/loadbalancer/LoadBalancerUtils.java b/spring-cloud-tencent-polaris-loadbalancer/src/main/java/com/tencent/cloud/polaris/loadbalancer/LoadBalancerUtils.java index d7295447e..c30da7cff 100644 --- a/spring-cloud-tencent-polaris-loadbalancer/src/main/java/com/tencent/cloud/polaris/loadbalancer/LoadBalancerUtils.java +++ b/spring-cloud-tencent-polaris-loadbalancer/src/main/java/com/tencent/cloud/polaris/loadbalancer/LoadBalancerUtils.java @@ -32,9 +32,12 @@ import com.tencent.polaris.api.pojo.ServiceKey; /** * load balancer utils. * - *@author lepdou 2022-05-17 + * @author lepdou 2022-05-17 */ -public class LoadBalancerUtils { +public final class LoadBalancerUtils { + + private LoadBalancerUtils() { + } public static ServiceInstances transferServersToServiceInstances(List servers) { List instances = new ArrayList<>(servers.size()); diff --git a/spring-cloud-tencent-polaris-loadbalancer/src/main/java/com/tencent/cloud/polaris/loadbalancer/PolarisLoadBalancer.java b/spring-cloud-tencent-polaris-loadbalancer/src/main/java/com/tencent/cloud/polaris/loadbalancer/PolarisLoadBalancer.java index 5f83c5aec..d1c4e3ae1 100644 --- a/spring-cloud-tencent-polaris-loadbalancer/src/main/java/com/tencent/cloud/polaris/loadbalancer/PolarisLoadBalancer.java +++ b/spring-cloud-tencent-polaris-loadbalancer/src/main/java/com/tencent/cloud/polaris/loadbalancer/PolarisLoadBalancer.java @@ -136,5 +136,4 @@ public class PolarisLoadBalancer extends DynamicServerListLoadBalancer { request.setService(serviceName); return consumerAPI.getHealthyInstances(request); } - } diff --git a/spring-cloud-tencent-polaris-loadbalancer/src/main/java/com/tencent/cloud/polaris/loadbalancer/PolarisWeightedRule.java b/spring-cloud-tencent-polaris-loadbalancer/src/main/java/com/tencent/cloud/polaris/loadbalancer/PolarisWeightedRule.java index 124085717..31278f558 100644 --- a/spring-cloud-tencent-polaris-loadbalancer/src/main/java/com/tencent/cloud/polaris/loadbalancer/PolarisWeightedRule.java +++ b/spring-cloud-tencent-polaris-loadbalancer/src/main/java/com/tencent/cloud/polaris/loadbalancer/PolarisWeightedRule.java @@ -36,7 +36,7 @@ import org.springframework.util.CollectionUtils; /** * Polaris weighted load balancer. * - *@author lepdou 2022-05-17 + * @author lepdou 2022-05-17 */ public class PolarisWeightedRule extends AbstractLoadBalancerRule { diff --git a/spring-cloud-tencent-polaris-loadbalancer/src/main/java/com/tencent/cloud/polaris/loadbalancer/config/PolarisLoadBalancerProperties.java b/spring-cloud-tencent-polaris-loadbalancer/src/main/java/com/tencent/cloud/polaris/loadbalancer/config/PolarisLoadBalancerProperties.java index 9d4d06059..00b5fe4f2 100644 --- a/spring-cloud-tencent-polaris-loadbalancer/src/main/java/com/tencent/cloud/polaris/loadbalancer/config/PolarisLoadBalancerProperties.java +++ b/spring-cloud-tencent-polaris-loadbalancer/src/main/java/com/tencent/cloud/polaris/loadbalancer/config/PolarisLoadBalancerProperties.java @@ -73,5 +73,4 @@ public class PolarisLoadBalancerProperties { return "PolarisLoadBalancerProperties{" + "loadbalancerEnabled=" + enabled + ", strategy='" + strategy + '\'' + '}'; } - } diff --git a/spring-cloud-tencent-polaris-loadbalancer/src/main/java/com/tencent/cloud/polaris/loadbalancer/config/PolarisRibbonClientConfiguration.java b/spring-cloud-tencent-polaris-loadbalancer/src/main/java/com/tencent/cloud/polaris/loadbalancer/config/PolarisRibbonClientConfiguration.java index 3fbc2c76d..75b684da4 100644 --- a/spring-cloud-tencent-polaris-loadbalancer/src/main/java/com/tencent/cloud/polaris/loadbalancer/config/PolarisRibbonClientConfiguration.java +++ b/spring-cloud-tencent-polaris-loadbalancer/src/main/java/com/tencent/cloud/polaris/loadbalancer/config/PolarisRibbonClientConfiguration.java @@ -45,5 +45,4 @@ public class PolarisRibbonClientConfiguration { return new PolarisLoadBalancer(iClientConfig, iRule, iPing, serverList, consumerAPI, polarisLoadBalancerProperties); } - } diff --git a/spring-cloud-tencent-polaris-loadbalancer/src/test/java/com/tencent/cloud/polaris/loadbalancer/config/PolarisLoadBalancerAutoConfigurationTest.java b/spring-cloud-tencent-polaris-loadbalancer/src/test/java/com/tencent/cloud/polaris/loadbalancer/config/PolarisLoadBalancerAutoConfigurationTest.java index eab96ee76..5004959f7 100644 --- a/spring-cloud-tencent-polaris-loadbalancer/src/test/java/com/tencent/cloud/polaris/loadbalancer/config/PolarisLoadBalancerAutoConfigurationTest.java +++ b/spring-cloud-tencent-polaris-loadbalancer/src/test/java/com/tencent/cloud/polaris/loadbalancer/config/PolarisLoadBalancerAutoConfigurationTest.java @@ -17,13 +17,32 @@ package com.tencent.cloud.polaris.loadbalancer.config; +import com.netflix.client.config.DefaultClientConfigImpl; +import com.netflix.client.config.IClientConfig; +import com.netflix.loadbalancer.ILoadBalancer; +import com.netflix.loadbalancer.IPing; +import com.netflix.loadbalancer.IRule; +import com.netflix.loadbalancer.NoOpPing; +import com.netflix.loadbalancer.RandomRule; +import com.netflix.loadbalancer.Server; +import com.netflix.loadbalancer.ServerList; import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration; +import com.tencent.cloud.polaris.loadbalancer.PolarisLoadBalancer; +import com.tencent.polaris.api.core.ConsumerAPI; +import com.tencent.polaris.client.api.SDKContext; +import com.tencent.polaris.discovery.client.api.DefaultConsumerAPI; import com.tencent.polaris.router.api.core.RouterAPI; import org.junit.Test; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.cloud.netflix.ribbon.RibbonAutoConfiguration; +import org.springframework.cloud.netflix.ribbon.SpringClientFactory; +import org.springframework.cloud.netflix.ribbon.StaticServerList; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import static com.tencent.polaris.test.common.Consts.PORT; @@ -37,10 +56,11 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class PolarisLoadBalancerAutoConfigurationTest { - private ApplicationContextRunner contextRunner = new ApplicationContextRunner() + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(PolarisRibbonTest.class, PolarisLoadBalancerAutoConfiguration.class, - PolarisContextAutoConfiguration.class)) + PolarisContextAutoConfiguration.class, + RibbonAutoConfiguration.class)) .withPropertyValues("spring.application.name=" + SERVICE_PROVIDER) .withPropertyValues("server.port=" + PORT) .withPropertyValues("spring.cloud.polaris.address=grpc://127.0.0.1:10081"); @@ -50,13 +70,49 @@ public class PolarisLoadBalancerAutoConfigurationTest { this.contextRunner.run(context -> { assertThat(context).hasSingleBean(RouterAPI.class); assertThat(context).hasSingleBean(PolarisLoadBalancerProperties.class); + assertThat(hasSinglePolarisLoadBalancer(context)).isTrue(); }); } + private boolean hasSinglePolarisLoadBalancer(BeanFactory beanFactory) { + SpringClientFactory contextBean = beanFactory.getBean(SpringClientFactory.class); + ILoadBalancer loadBalancer = contextBean.getLoadBalancer(SERVICE_PROVIDER); + return loadBalancer instanceof PolarisLoadBalancer; + } + @Configuration @EnableAutoConfiguration static class PolarisRibbonTest { - } + @Autowired + private SDKContext sdkContext; + + @Bean + public IClientConfig iClientConfig() { + DefaultClientConfigImpl config = new DefaultClientConfigImpl(); + config.setClientName(SERVICE_PROVIDER); + return config; + } + + @Bean + public IRule iRule() { + return new RandomRule(); + } + @Bean + public IPing iPing() { + return new NoOpPing(); + } + + @Bean + public ServerList serverList() { + return new StaticServerList<>(); + } + + @Bean + public ConsumerAPI consumerAPI() { + return new DefaultConsumerAPI(sdkContext); + } + + } } diff --git a/spring-cloud-tencent-polaris-loadbalancer/src/test/java/com/tencent/cloud/polaris/loadbalancer/config/PolarisRibbonClientConfigurationTest.java b/spring-cloud-tencent-polaris-loadbalancer/src/test/java/com/tencent/cloud/polaris/loadbalancer/config/PolarisRibbonClientConfigurationTest.java new file mode 100644 index 000000000..d514af6db --- /dev/null +++ b/spring-cloud-tencent-polaris-loadbalancer/src/test/java/com/tencent/cloud/polaris/loadbalancer/config/PolarisRibbonClientConfigurationTest.java @@ -0,0 +1,55 @@ +/* + * Tencent is pleased to support the open source community by making Spring Cloud Tencent available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ + +package com.tencent.cloud.polaris.loadbalancer.config; + +import com.tencent.cloud.polaris.loadbalancer.PolarisLoadBalancer; +import org.junit.Test; + +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Test for {@link PolarisRibbonClientConfiguration}. + * + * @author wlx + * @date 2022/7/2 10:36 上午 + */ +public class PolarisRibbonClientConfigurationTest { + + private final ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner(); + + @Test + public void testDefaultInitialization() { + this.applicationContextRunner + .withConfiguration(AutoConfigurations.of( + TestApplication.class, + PolarisRibbonClientConfiguration.class)) + .run(context -> { + assertThat(context).hasSingleBean(PolarisRibbonClientConfiguration.class); + assertThat(context).hasSingleBean(PolarisLoadBalancer.class); + }); + } + + @SpringBootApplication + static class TestApplication { + } + +} diff --git a/src/checkstyle/checkstyle-suppressions.xml b/src/checkstyle/checkstyle-suppressions.xml index ace6b329d..452aaa5f7 100644 --- a/src/checkstyle/checkstyle-suppressions.xml +++ b/src/checkstyle/checkstyle-suppressions.xml @@ -4,6 +4,5 @@ "https://www.puppycrawl.com/dtds/suppressions_1_1.dtd"> - \ No newline at end of file