refactor:optimize project and code. (#407)

* refactor:optimize project and code.

* fix:fix junit error.

* fix:fix code style.
pull/415/head
Haotian Zhang 3 years ago committed by GitHub
parent dc6f986c34
commit e95901eb53
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -29,4 +29,4 @@
- [Feature: support spring cloud gateway routers](https://github.com/Tencent/spring-cloud-tencent/pull/390)
- [Optimize starter's auto-configuration](https://github.com/Tencent/spring-cloud-tencent/pull/396)
- [test: add PostInitPolarisSDKContextTest](https://github.com/Tencent/spring-cloud-tencent/pull/403)
- [refactor:optimize project and code](https://github.com/Tencent/spring-cloud-tencent/pull/407)

@ -3,11 +3,11 @@
[![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)
[![Maven Central](https://img.shields.io/maven-central/v/com.tencent.cloud/spring-cloud-tencent?label=Maven%20Central)](https://search.maven.org/search?q=g:com.tencent.cloud%20AND%20a:spring-cloud-tencent)
[![codecov.io](https://codecov.io/gh/Tencent/spring-cloud-tencent/branch/main/graph/badge.svg)](https://codecov.io/gh/Tencent/spring-cloud-tencent?branch=main)
[![codecov.io](https://codecov.io/gh/Tencent/spring-cloud-tencent/branch/2021.0/graph/badge.svg)](https://codecov.io/gh/Tencent/spring-cloud-tencent?branch=2021.0)
[![Contributors](https://img.shields.io/github/contributors/Tencent/spring-cloud-tencent)](https://github.com/Tencent/spring-cloud-tencent/graphs/contributors)
[![License](https://img.shields.io/badge/License-BSD%203--Clause-blue.svg)](https://opensource.org/licenses/BSD-3-Clause)
[English](./README.md) | 简体中文
[English](./README.md) | 简体中文
---
@ -29,20 +29,23 @@ Spring Cloud Tencent提供的能力包括但不限于
- 服务注册和发现
- 动态配置管理
- 服务治理
- 服务限流
- 服务熔断
- 服务路由
- ...
- 服务限流
- 服务熔断
- 服务路由
- ...
- 标签透传
## 体验环境
- 管控台地址: http://14.116.241.63:8080/
- 账号polaris
- 密码polaris
- 账号polaris
- 密码polaris
- 控制面地址: `grpc://183.47.111.80:8091`
-
`spring-cloud-tencent-example` 下 example 地址都默认指向了体验服务地址(`grpc://183.47.111.80:8091`),如果您只是体验 Spring Cloud Tencent可直接一键运行任何 example。
-
`spring-cloud-tencent-example` 下 example 地址都默认指向了体验服务地址(`grpc://183.47.111.80:8091`),如果您只是体验 Spring Cloud
Tencent可直接一键运行任何 example。
## 管控台
<img width="1792" alt="image" src="https://user-images.githubusercontent.com/4991116/163402268-48493802-4555-4b93-8e31-011410f2166b.png">
@ -88,8 +91,8 @@ Spring Cloud Tencent 所有组件都已上传到 Maven 中央仓库,只需要
- [Spring Cloud Tencent 标签传递](https://github.com/Tencent/spring-cloud-tencent/wiki/Spring-Cloud-Tencent-Metadata-Transfer-%E4%BD%BF%E7%94%A8%E6%8C%87%E5%8D%97)
- ### 开发文档
- [项目概览](https://github.com/Tencent/spring-cloud-tencent/wiki/%E9%A1%B9%E7%9B%AE%E6%A6%82%E8%A7%88)
- [参与共建](https://github.com/Tencent/spring-cloud-tencent/wiki/%E5%8F%82%E4%B8%8E%E5%85%B1%E5%BB%BA)
- [项目概览](https://github.com/Tencent/spring-cloud-tencent/wiki/%E9%A1%B9%E7%9B%AE%E6%A6%82%E8%A7%88)
- [参与共建](https://github.com/Tencent/spring-cloud-tencent/wiki/%E5%8F%82%E4%B8%8E%E5%85%B1%E5%BB%BA)
## 交流群
@ -97,9 +100,10 @@ Spring Cloud Tencent 所有组件都已上传到 Maven 中央仓库,只需要
<img src="https://user-images.githubusercontent.com/24446200/169198148-d4cc3494-3485-4515-9897-c8cb5504f706.png" width="30%" height="30%" />
## License
The spring-cloud-tencent is licensed under the BSD 3-Clause License. Copyright and license information can be found in the file [LICENSE](LICENSE)
The spring-cloud-tencent is licensed under the BSD 3-Clause License. Copyright and license information can be found in
the file [LICENSE](LICENSE)
## Stargazers over time

@ -4,7 +4,7 @@
[![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)
[![Maven Central](https://img.shields.io/maven-central/v/com.tencent.cloud/spring-cloud-tencent?label=Maven%20Central)](https://search.maven.org/search?q=g:com.tencent.cloud%20AND%20a:spring-cloud-tencent)
[![codecov.io](https://codecov.io/gh/Tencent/spring-cloud-tencent/branch/main/graph/badge.svg)](https://codecov.io/gh/Tencent/spring-cloud-tencent?branch=main)
[![codecov.io](https://codecov.io/gh/Tencent/spring-cloud-tencent/branch/2021.0/graph/badge.svg)](https://codecov.io/gh/Tencent/spring-cloud-tencent?branch=2021.0)
[![Contributors](https://img.shields.io/github/contributors/Tencent/spring-cloud-tencent)](https://github.com/Tencent/spring-cloud-tencent/graphs/contributors)
[![License](https://img.shields.io/badge/License-BSD%203--Clause-blue.svg)](https://opensource.org/licenses/BSD-3-Clause)
@ -14,9 +14,11 @@ English | [简体中文](./README-zh.md)
Spring Cloud Tencent is a open source one-stop microservice solution from Tencent.
Spring Cloud Tencent implements the Spring Cloud standard microservice SPI, so developers can quickly develop Spring Cloud cloud-native distributed applications based on Spring Cloud Tencent.
Spring Cloud Tencent implements the Spring Cloud standard microservice SPI, so developers can quickly develop Spring
Cloud cloud-native distributed applications based on Spring Cloud Tencent.
The core of Spring Cloud Tencent relies on Tencent's open-source one-stop service discovery and governance platform [Polaris](https://github.com/polarismesh/polaris) to realize various distributed microservice scenarios.
The core of Spring Cloud Tencent relies on Tencent's open-source one-stop service discovery and governance
platform [Polaris](https://github.com/polarismesh/polaris) to realize various distributed microservice scenarios.
- [Polaris Github home page](https://github.com/polarismesh/polaris)
- [Polaris official website](https://polarismesh.cn/)
@ -28,21 +30,22 @@ The capabilities provided by Spring Cloud Tencent include but are not limited to
- Service registration and discovery
- Dynamic configuration management
- Service Governance
- Service rate limit
- Service circuit breaker
- Service routing
- ...
- Service rate limit
- Service circuit breaker
- Service routing
- ...
- Label transparent transmission
## Demo Environment
- Console Address : http://14.116.241.63:8080/
- Username: polaris
- Password: polaris
- Username: polaris
- Password: polaris
- Server Address: `grpc://183.47.111.80:8091`
The example addresses under `spring-cloud-tencent-example` all point to the experience service address (`grpc://183.47.111.80:8091`) by default.
If you only experience Spring Cloud Tencent, you can run any example directly with one click.
The example addresses under `spring-cloud-tencent-example` all point to the experience service
address (`grpc://183.47.111.80:8091`) by default. If you only experience Spring Cloud Tencent, you can run any example
directly with one click.
## Screenshots
@ -50,7 +53,8 @@ If you only experience Spring Cloud Tencent, you can run any example directly wi
## Use Guide
All the components of Spring Cloud Tencent have been uploaded to the Maven central repository, just need to introduce dependencies.
All the components of Spring Cloud Tencent have been uploaded to the Maven central repository, just need to introduce
dependencies.
For example:
@ -79,7 +83,7 @@ For example:
````
- ### Quick Start
- ### Quick Start
- [Spring Cloud Tencent Version Management](https://github.com/Tencent/spring-cloud-tencent/wiki/Spring-Cloud-Tencent-%E7%89%88%E6%9C%AC%E7%AE%A1%E7%90%86)
- [Spring Cloud Tencent Discovery](https://github.com/Tencent/spring-cloud-tencent/wiki/Spring-Cloud-Tencent-Discovery-%E4%BD%BF%E7%94%A8%E6%96%87%E6%A1%A3)
- [Spring Cloud Tencent Config](https://github.com/Tencent/spring-cloud-tencent/wiki/Spring-Cloud-Tencent-Config-%E4%BD%BF%E7%94%A8%E6%96%87%E6%A1%A3)
@ -89,9 +93,9 @@ For example:
- [Spring Cloud Tencent Metadata Transfer](https://github.com/Tencent/spring-cloud-tencent/wiki/Spring-Cloud-Tencent-Metadata-Transfer-%E4%BD%BF%E7%94%A8%E6%8C%87%E5%8D%97)
- ### Development Documentation
- [Project Structure Overview](https://github.com/Tencent/spring-cloud-tencent/wiki/%E9%A1%B9%E7%9B%AE%E6%A6%82%E8%A7%88)
- [Participate in co-construction](https://github.com/Tencent/spring-cloud-tencent/wiki/%E5%8F%82%E4%B8%8E%E5%85%B1%E5%BB%BA)
- [Project Structure Overview](https://github.com/Tencent/spring-cloud-tencent/wiki/%E9%A1%B9%E7%9B%AE%E6%A6%82%E8%A7%88)
- [Participate in co-construction](https://github.com/Tencent/spring-cloud-tencent/wiki/%E5%8F%82%E4%B8%8E%E5%85%B1%E5%BB%BA)
## Chat Group
Please scan the QR code to join the chat group.
@ -99,8 +103,9 @@ Please scan the QR code to join the chat group.
<img src="https://user-images.githubusercontent.com/24446200/169198148-d4cc3494-3485-4515-9897-c8cb5504f706.png" width="30%" height="30%" />
## License
The spring-cloud-tencent is licensed under the BSD 3-Clause License. Copyright and license information can be found in the file [LICENSE](LICENSE)
The spring-cloud-tencent is licensed under the BSD 3-Clause License. Copyright and license information can be found in
the file [LICENSE](LICENSE)
## Stargazers over time

@ -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/289)

@ -67,12 +67,10 @@ public class MetadataTransferAutoConfiguration {
@Bean
public FilterRegistrationBean<DecodeTransferMetadataServletFilter> metadataServletFilterRegistrationBean(
DecodeTransferMetadataServletFilter decodeTransferMetadataServletFilter) {
FilterRegistrationBean<DecodeTransferMetadataServletFilter> filterRegistrationBean = new FilterRegistrationBean<>(
decodeTransferMetadataServletFilter);
filterRegistrationBean.setDispatcherTypes(ASYNC, ERROR, FORWARD, INCLUDE,
REQUEST);
filterRegistrationBean
.setOrder(MetadataConstant.OrderConstant.WEB_FILTER_ORDER);
FilterRegistrationBean<DecodeTransferMetadataServletFilter> filterRegistrationBean =
new FilterRegistrationBean<>(decodeTransferMetadataServletFilter);
filterRegistrationBean.setDispatcherTypes(ASYNC, ERROR, FORWARD, INCLUDE, REQUEST);
filterRegistrationBean.setOrder(MetadataConstant.OrderConstant.WEB_FILTER_ORDER);
return filterRegistrationBean;
}
@ -146,8 +144,7 @@ public class MetadataTransferAutoConfiguration {
// is initialized, then manually set the interceptor.
if (!CollectionUtils.isEmpty(beans)) {
for (RestTemplate restTemplate : beans.values()) {
List<ClientHttpRequestInterceptor> interceptors = restTemplate
.getInterceptors();
List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors();
// Avoid setting interceptor repeatedly.
if (!interceptors.contains(encodeTransferMedataRestTemplateInterceptor)) {
interceptors.add(encodeTransferMedataRestTemplateInterceptor);
@ -155,8 +152,7 @@ public class MetadataTransferAutoConfiguration {
}
}
}
return new EncodeTransferMetadataRestTemplatePostProcessor(
encodeTransferMedataRestTemplateInterceptor);
return new EncodeTransferMetadataRestTemplatePostProcessor(encodeTransferMedataRestTemplateInterceptor);
}
@Override
@ -183,8 +179,7 @@ public class MetadataTransferAutoConfiguration {
public Object postProcessAfterInitialization(@NonNull Object bean, @NonNull String beanName) {
if (bean instanceof RestTemplate) {
RestTemplate restTemplate = (RestTemplate) bean;
List<ClientHttpRequestInterceptor> interceptors = restTemplate
.getInterceptors();
List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors();
// Avoid setting interceptor repeatedly.
if (!interceptors.contains(encodeTransferMedataRestTemplateInterceptor)) {
interceptors.add(this.encodeTransferMedataRestTemplateInterceptor);

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

@ -70,13 +70,11 @@ public class DecodeTransferMetadataReactiveFilter implements WebFilter, Ordered
MetadataContextHolder.init(mergedTransitiveMetadata);
// Save to ServerWebExchange.
serverWebExchange.getAttributes().put(
MetadataConstant.HeaderName.METADATA_CONTEXT,
MetadataContextHolder.get());
serverWebExchange.getAttributes()
.put(MetadataConstant.HeaderName.METADATA_CONTEXT, MetadataContextHolder.get());
return webFilterChain.filter(serverWebExchange)
.doOnError(throwable -> LOG.error("handle metadata[{}] error.",
MetadataContextHolder.get(), throwable))
.doOnError(throwable -> LOG.error("handle metadata[{}] error.", MetadataContextHolder.get(), throwable))
.doFinally((type) -> MetadataContextHolder.remove());
}

@ -54,8 +54,7 @@ public class DecodeTransferMetadataServletFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse, FilterChain filterChain)
throws ServletException, IOException {
HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
Map<String, String> internalTransitiveMetadata = getInternalTransitiveMetadata(httpServletRequest);
Map<String, String> customTransitiveMetadata = CustomTransitiveMetadataResolver.resolve(httpServletRequest);
@ -89,5 +88,4 @@ public class DecodeTransferMetadataServletFilter extends OncePerRequestFilter {
// create custom metadata.
return JacksonUtils.deserialize2Map(customMetadataStr);
}
}

@ -62,8 +62,7 @@ public class EncodeTransferMedataFeignInterceptor implements RequestInterceptor,
String encodedTransitiveMetadata = JacksonUtils.serialize2Json(customMetadata);
requestTemplate.removeHeader(CUSTOM_METADATA);
try {
requestTemplate.header(CUSTOM_METADATA,
URLEncoder.encode(encodedTransitiveMetadata, UTF_8));
requestTemplate.header(CUSTOM_METADATA, URLEncoder.encode(encodedTransitiveMetadata, UTF_8));
}
catch (UnsupportedEncodingException e) {
LOG.error("Set header failed.", e);

@ -68,8 +68,7 @@ public class EncodeTransferMedataScgFilter implements GlobalFilter, Ordered {
if (!CollectionUtils.isEmpty(customMetadata)) {
String metadataStr = JacksonUtils.serialize2Json(customMetadata);
try {
builder.header(MetadataConstant.HeaderName.CUSTOM_METADATA,
URLEncoder.encode(metadataStr, UTF_8));
builder.header(MetadataConstant.HeaderName.CUSTOM_METADATA, URLEncoder.encode(metadataStr, UTF_8));
}
catch (UnsupportedEncodingException e) {
builder.header(MetadataConstant.HeaderName.CUSTOM_METADATA, metadataStr);
@ -78,5 +77,4 @@ public class EncodeTransferMedataScgFilter implements GlobalFilter, Ordered {
return chain.filter(exchange.mutate().request(builder.build()).build());
}
}

@ -50,11 +50,11 @@ public class MetadataTransferAutoConfigurationTest {
.hasSingleBean(MetadataTransferAutoConfiguration.MetadataTransferRestTemplateConfig.class);
Assertions.assertThat(context).hasSingleBean(EncodeTransferMedataRestTemplateInterceptor.class);
Assertions.assertThat(context).hasSingleBean(
MetadataTransferAutoConfiguration.MetadataTransferRestTemplateConfig.EncodeTransferMetadataRestTemplatePostProcessor.class);
MetadataTransferAutoConfiguration.MetadataTransferRestTemplateConfig
.EncodeTransferMetadataRestTemplatePostProcessor.class);
Assertions.assertThat(context)
.hasSingleBean(MetadataTransferAutoConfiguration.MetadataTransferScgFilterConfig.class);
Assertions.assertThat(context).hasSingleBean(GlobalFilter.class);
});
}
}

@ -43,7 +43,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = MOCK,
classes = DecodeTransferMetadataServletFilterTest.TestApplication.class,
properties = { "spring.config.location = classpath:application-test.yml" })
properties = {"spring.config.location = classpath:application-test.yml"})
public class DecodeTransferMetadataReactiveFilterTest {
@Autowired
@ -74,11 +74,8 @@ public class DecodeTransferMetadataReactiveFilterTest {
ServerWebExchange exchange = MockServerWebExchange.from(request);
metadataReactiveFilter.filter(exchange, webFilterChain);
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();
}
}

@ -45,7 +45,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = RANDOM_PORT,
classes = DecodeTransferMetadataServletFilterTest.TestApplication.class,
properties = { "spring.config.location = classpath:application-test.yml" })
properties = {"spring.config.location = classpath:application-test.yml"})
public class DecodeTransferMetadataServletFilterTest {
@Autowired
@ -66,10 +66,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();
}
@ -77,5 +75,4 @@ public class DecodeTransferMetadataServletFilterTest {
protected static class TestApplication {
}
}

@ -17,8 +17,6 @@
package com.tencent.cloud.metadata.core;
import java.io.UnsupportedEncodingException;
import com.tencent.cloud.common.constant.MetadataConstant;
import com.tencent.cloud.common.metadata.MetadataContext;
import com.tencent.cloud.common.metadata.MetadataContextHolder;
@ -36,7 +34,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;
@ -63,10 +60,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
@ -75,9 +70,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() {
return MetadataContextHolder.get().getContext(MetadataContext.FRAGMENT_TRANSITIVE, "b");
}
@ -86,7 +79,6 @@ public class EncodeTransferMedataFeignInterceptorTest {
@RequestMapping("/test")
String test();
}
@Configuration
@ -94,8 +86,7 @@ public class EncodeTransferMedataFeignInterceptorTest {
@Override
public void apply(RequestTemplate template) {
template.header(MetadataConstant.HeaderName.CUSTOM_METADATA,
"{\"a\":\"11\",\"b\":\"22\",\"c\":\"33\"}");
template.header(MetadataConstant.HeaderName.CUSTOM_METADATA, "{\"a\":\"11\",\"b\":\"22\",\"c\":\"33\"}");
}
}
}

@ -17,9 +17,6 @@
package com.tencent.cloud.metadata.core;
import java.io.UnsupportedEncodingException;
import com.tencent.cloud.common.constant.MetadataConstant;
import com.tencent.cloud.common.metadata.MetadataContext;
import com.tencent.cloud.common.metadata.MetadataContextHolder;
import org.assertj.core.api.Assertions;
@ -35,7 +32,6 @@ import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@ -50,7 +46,7 @@ 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" })
properties = {"spring.config.location = classpath:application-test.yml"})
public class EncodeTransferMedataRestTemplateInterceptorTest {
@Autowired
@ -64,8 +60,7 @@ public class EncodeTransferMedataRestTemplateInterceptorTest {
HttpHeaders httpHeaders = new HttpHeaders();
HttpEntity<String> httpEntity = new HttpEntity<>(httpHeaders);
String metadata = restTemplate
.exchange("http://localhost:" + localServerPort + "/test", HttpMethod.GET,
httpEntity, String.class)
.exchange("http://localhost:" + localServerPort + "/test", HttpMethod.GET, httpEntity, String.class)
.getBody();
Assertions.assertThat(metadata).isEqualTo("2");
}
@ -80,12 +75,8 @@ public class EncodeTransferMedataRestTemplateInterceptorTest {
}
@RequestMapping("/test")
public String test(
@RequestHeader(MetadataConstant.HeaderName.CUSTOM_METADATA) String customMetadataStr)
throws UnsupportedEncodingException {
public String test() {
return MetadataContextHolder.get().getContext(MetadataContext.FRAGMENT_TRANSITIVE, "b");
}
}
}

@ -46,9 +46,9 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
* @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"})
@SpringBootTest(webEnvironment = RANDOM_PORT, classes = EncodeTransferMedataScgFilterTest.TestApplication.class,
properties = {"spring.config.location = classpath:application-test.yml",
"spring.main.web-application-type = reactive"})
public class EncodeTransferMedataScgFilterTest {
@Autowired

@ -84,5 +84,4 @@ public class PolarisFeignBeanPostProcessor implements BeanPostProcessor, BeanFac
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.factory = beanFactory;
}
}

@ -42,7 +42,6 @@ import static feign.Util.checkNotNull;
*/
public class PolarisFeignClient implements Client {
private static final Logger LOG = LoggerFactory.getLogger(PolarisFeignClient.class);
private final Client delegate;
@ -60,7 +59,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=[{}].",
@ -96,5 +95,4 @@ public class PolarisFeignClient implements Client {
return resultRequest;
}
}

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

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

@ -31,7 +31,7 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Haotian Zhang
*/
public class PolarisCircuitBreakerBootstrapConfigurationTest {
private ApplicationContextRunner contextRunner = new ApplicationContextRunner()
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(
AutoConfigurations.of(PolarisCircuitBreakerBootstrapConfiguration.class))
.withPropertyValues("spring.cloud.polaris.circuitbreaker.enabled=true");

@ -71,9 +71,7 @@ public class PolarisFeignBeanPostProcessorTest {
// isNeedWrap(bean) == false
Object bean1 = new Object();
Object bean = polarisFeignBeanPostProcessor.postProcessBeforeInitialization(bean1, "bean1");
assertThat(bean).isNotInstanceOfAny(
PolarisFeignClient.class,
PolarisFeignBlockingLoadBalancerClient.class);
assertThat(bean).isNotInstanceOfAny(PolarisFeignClient.class, PolarisFeignBlockingLoadBalancerClient.class);
// bean instanceOf Client.class
Client bean2 = mock(Client.class);

@ -90,7 +90,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 +113,10 @@ public class PolarisFeignClientTest {
Maps.newHashMap(), null, requestTemplate), null);
assertThat(response.status()).isEqualTo(200);
// 200
// 502
response = polarisFeignClient.execute(Request.create(Request.HttpMethod.POST, "http://localhost:8080/test",
Maps.newHashMap(), null, requestTemplate), null);
assertThat(response.status()).isEqualTo(500);
assertThat(response.status()).isEqualTo(502);
// Exception
try {

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

@ -172,9 +172,8 @@ public class PolarisConfigFileLocator implements PropertySourceLocator {
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);
}
}
}
@ -204,5 +203,4 @@ public class PolarisConfigFileLocator implements PropertySourceLocator {
return new PolarisPropertySource(namespace, group, fileName, configKVFile, map);
}
}

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

@ -51,12 +51,9 @@ public class PolarisPropertySourceAutoRefresher
private final PolarisConfigProperties polarisConfigProperties;
private final PolarisPropertySourceManager polarisPropertySourceManager;
private ApplicationContext applicationContext;
private final ContextRefresher contextRefresher;
private final AtomicBoolean registered = new AtomicBoolean(false);
private ApplicationContext applicationContext;
public PolarisPropertySourceAutoRefresher(PolarisConfigProperties polarisConfigProperties,
PolarisPropertySourceManager polarisPropertySourceManager, ContextRefresher contextRefresher) {
@ -125,5 +122,4 @@ public class PolarisPropertySourceAutoRefresher
});
}
}
}

@ -39,5 +39,4 @@ public class PolarisPropertySourceManager {
public List<PolarisPropertySource> getAllPropertySources() {
return new ArrayList<>(polarisPropertySources.values());
}
}

@ -101,5 +101,4 @@ public class PolarisConfigAnnotationProcessor implements BeanPostProcessor, Prio
addChangeListener(configChangeListener, interestedKeys, interestedKeyPrefixes);
}
}

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

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

@ -40,7 +40,8 @@ public class PolarisConfigEndpoint {
private final PolarisConfigProperties polarisConfigProperties;
private final PolarisPropertySourceManager polarisPropertySourceManager;
public PolarisConfigEndpoint(PolarisConfigProperties polarisConfigProperties, PolarisPropertySourceManager polarisPropertySourceManager) {
public PolarisConfigEndpoint(PolarisConfigProperties polarisConfigProperties,
PolarisPropertySourceManager polarisPropertySourceManager) {
this.polarisConfigProperties = polarisConfigProperties;
this.polarisPropertySourceManager = polarisPropertySourceManager;
}

@ -42,7 +42,8 @@ public class PolarisConfigEndpointAutoConfiguration {
@Bean
@ConditionalOnAvailableEndpoint
@ConditionalOnMissingBean
public PolarisConfigEndpoint polarisConfigEndpoint(PolarisConfigProperties polarisConfigProperties, PolarisPropertySourceManager polarisPropertySourceManager) {
public PolarisConfigEndpoint polarisConfigEndpoint(PolarisConfigProperties polarisConfigProperties,
PolarisPropertySourceManager polarisPropertySourceManager) {
return new PolarisConfigEndpoint(polarisConfigProperties, polarisPropertySourceManager);
}
}

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

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

@ -55,7 +55,6 @@ public final class PolarisConfigChangeEventListener implements ApplicationListen
*/
@Override
public void onApplicationEvent(@NonNull ApplicationEvent event) {
// Initialize application all environment properties .
if (event instanceof ApplicationStartedEvent && started.compareAndSet(false, true)) {
ApplicationStartedEvent applicationStartedEvent = (ApplicationStartedEvent) event;
@ -107,5 +106,4 @@ public final class PolarisConfigChangeEventListener implements ApplicationListen
});
return ret;
}
}

@ -55,37 +55,34 @@ import static com.tencent.polaris.configuration.api.core.ChangeType.MODIFIED;
* @author Palmer Xu 2022-06-06
*/
public final class PolarisConfigListenerContext {
/**
* Logger instance.
*/
private static final Logger LOG = LoggerFactory.getLogger(PolarisConfigListenerContext.class);
/**
* Execute service Atomic Reference Cache .
*/
private static final AtomicReference<ExecutorService> EAR = new AtomicReference<>();
/**
* All custom {@link ConfigChangeListener} instance defined in application .
*/
private static final List<ConfigChangeListener> listeners = Lists.newCopyOnWriteArrayList();
/**
* All custom interested keys defined in application .
*/
private static final Map<ConfigChangeListener, Set<String>> interestedKeys = Maps.newHashMap();
/**
* All custom interested key prefixes defined in application .
*/
private static final Map<ConfigChangeListener, Set<String>> interestedKeyPrefixes = Maps.newHashMap();
/**
* Cache all latest configuration information for users in the application environment .
*/
private static final Cache<String, Object> properties = CacheBuilder.newBuilder().build();
private PolarisConfigListenerContext() {
}
/**
* Get or Created new execute server .
* @return execute service instance of {@link ExecutorService}
@ -273,5 +270,4 @@ public final class PolarisConfigListenerContext {
return Collections.unmodifiableSet(interestedChangedKeys);
}
}

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

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

@ -38,12 +38,16 @@ import static org.mockito.Mockito.verify;
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
@ -51,10 +55,6 @@ public class PolarisPropertiesSourceAutoRefresherTest {
@Mock
private ContextRefresher contextRefresher;
private final String testNamespace = "testNamespace";
private final String testServiceName = "testServiceName";
private final String testFileName = "application.properties";
@Test
public void testConfigFileChanged() {
PolarisPropertySourceAutoRefresher refresher = new PolarisPropertySourceAutoRefresher(polarisConfigProperties,
@ -118,5 +118,4 @@ public class PolarisPropertiesSourceAutoRefresherTest {
Assert.assertEquals("v1", polarisPropertySource.getProperty("k1"));
verify(contextRefresher).refresh();
}
}

@ -46,11 +46,11 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
* @author lepdou 2022-06-11
*/
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = DEFINED_PORT,
classes = ConfigChangeListenerTest.TestApplication.class,
@SpringBootTest(webEnvironment = DEFINED_PORT, classes = ConfigChangeListenerTest.TestApplication.class,
properties = {"server.port=8081", "spring.config.location = classpath:application-test.yml"})
public class ConfigChangeListenerTest {
private static final CountDownLatch hits = new CountDownLatch(2);
@Autowired
private ApplicationEventPublisher applicationEventPublisher;
@Autowired
@ -58,8 +58,6 @@ public class ConfigChangeListenerTest {
@Autowired
private TestApplication.TestConfig testConfig;
private static final CountDownLatch hits = new CountDownLatch(2);
@Test
public void test() throws InterruptedException {
//before change

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

@ -28,10 +28,12 @@ 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)
@Target({ ElementType.TYPE, ElementType.METHOD })
@Target({ElementType.TYPE, ElementType.METHOD})
@ConditionalOnDiscoveryEnabled
@ConditionalOnPolarisEnabled
@Conditional(DiscoveryEnabledCondition.class)

@ -34,13 +34,12 @@ public class DiscoveryEnabledCondition implements Condition {
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"));
conditionContext.getEnvironment().getProperty("spring.cloud.consul.discovery.enabled", "true"));
isDiscoveryEnabled |= isConsulDiscoveryEnabled;
return isDiscoveryEnabled;
}
}

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

@ -95,5 +95,4 @@ public class PolarisDiscoveryHandler {
request.setNamespace(namespace);
return polarisConsumer.getServices(request);
}
}

@ -66,5 +66,4 @@ public class PolarisServiceDiscovery {
return polarisDiscoveryHandler.GetServices().getServices().stream().map(ServiceInfo::getService)
.collect(Collectors.toList());
}
}

@ -36,9 +36,8 @@ import org.springframework.context.annotation.Configuration;
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnReactiveDiscoveryEnabled
@AutoConfigureAfter({ PolarisDiscoveryAutoConfiguration.class,
ReactiveCompositeDiscoveryClientAutoConfiguration.class })
@AutoConfigureBefore({ ReactiveCommonsClientAutoConfiguration.class })
@AutoConfigureAfter({PolarisDiscoveryAutoConfiguration.class, ReactiveCompositeDiscoveryClientAutoConfiguration.class})
@AutoConfigureBefore({ReactiveCommonsClientAutoConfiguration.class})
public class PolarisReactiveDiscoveryClientConfiguration {
@Bean

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

@ -39,7 +39,8 @@ import org.springframework.util.CollectionUtils;
*
* @author Haotian Zhang
*/
public class PolarisServiceStatusChangeListener extends AbstractResourceEventListener implements ApplicationEventPublisherAware {
public class PolarisServiceStatusChangeListener extends AbstractResourceEventListener
implements ApplicationEventPublisherAware {
/**
* Index of service info status.

@ -45,7 +45,8 @@ public class PolarisDiscoveryEndPoint {
private final DiscoveryClient polarisDiscoveryClient;
private final PolarisDiscoveryHandler polarisDiscoveryHandler;
public PolarisDiscoveryEndPoint(PolarisDiscoveryProperties polarisDiscoveryProperties, DiscoveryClient polarisDiscoveryClient, PolarisDiscoveryHandler polarisDiscoveryHandler) {
public PolarisDiscoveryEndPoint(PolarisDiscoveryProperties polarisDiscoveryProperties,
DiscoveryClient polarisDiscoveryClient, PolarisDiscoveryHandler polarisDiscoveryHandler) {
this.polarisDiscoveryProperties = polarisDiscoveryProperties;
this.polarisDiscoveryClient = polarisDiscoveryClient;
this.polarisDiscoveryHandler = polarisDiscoveryHandler;

@ -27,10 +27,12 @@ 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)
@Target({ ElementType.TYPE, ElementType.METHOD })
@Target({ElementType.TYPE, ElementType.METHOD})
@ConditionalOnPolarisEnabled
@Conditional(RegisterEnabledCondition.class)
public @interface ConditionalOnPolarisRegisterEnabled {

@ -71,8 +71,8 @@ public class PolarisServiceRegistry implements ServiceRegistry<Registration> {
this.staticMetadataManager = staticMetadataManager;
if (polarisDiscoveryProperties.isHeartbeatEnabled()) {
this.heartbeatExecutor = Executors
.newSingleThreadScheduledExecutor(new NamedThreadFactory("spring-cloud-heartbeat"));
this.heartbeatExecutor = Executors.newSingleThreadScheduledExecutor(
new NamedThreadFactory("spring-cloud-heartbeat"));
}
else {
this.heartbeatExecutor = null;

@ -36,10 +36,9 @@ public class RegisterEnabledCondition implements Condition {
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;
}
}

@ -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")

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

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

@ -26,7 +26,6 @@ import org.junit.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.runner.WebApplicationContextRunner;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Configuration;
import static com.tencent.polaris.test.common.Consts.PORT;
@ -42,10 +41,13 @@ public class PolarisDiscoveryClientConfigurationTest {
private static NamingServer namingServer;
private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(PolarisContextAutoConfiguration.class,
PolarisDiscoveryClientConfiguration.class, PolarisContextAutoConfiguration.class))
.withPropertyValues("spring.application.name=" + SERVICE_PROVIDER).withPropertyValues("server.port=" + PORT)
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");
@BeforeClass
@ -54,7 +56,7 @@ public class PolarisDiscoveryClientConfigurationTest {
}
@AfterClass
public static void afterClass() throws Exception {
public static void afterClass() {
if (null != namingServer) {
namingServer.terminate();
}
@ -73,9 +75,7 @@ public class PolarisDiscoveryClientConfigurationTest {
@Configuration
@EnableAutoConfiguration
@EnableDiscoveryClient
static class PolarisDiscoveryClientConfiguration {
}
}

@ -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,12 +48,15 @@ public class PolarisServiceDiscoveryTest {
private static NamingServer namingServer;
private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(PolarisContextAutoConfiguration.class,
private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(
PolarisContextAutoConfiguration.class,
PolarisServiceDiscoveryTest.PolarisPropertiesConfiguration.class,
PolarisDiscoveryClientConfiguration.class, PolarisDiscoveryAutoConfiguration.class,
PolarisDiscoveryClientConfiguration.class,
PolarisDiscoveryAutoConfiguration.class,
PolarisContextAutoConfiguration.class))
.withPropertyValues("spring.application.name=" + SERVICE_PROVIDER).withPropertyValues("server.port=" + PORT)
.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");
@ -73,7 +75,7 @@ public class PolarisServiceDiscoveryTest {
}
@AfterClass
public static void afterClass() throws Exception {
public static void afterClass() {
if (null != namingServer) {
namingServer.terminate();
}
@ -104,9 +106,7 @@ public class PolarisServiceDiscoveryTest {
@Configuration
@EnableAutoConfiguration
@EnableDiscoveryClient
static class PolarisPropertiesConfiguration {
}
}

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

@ -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) {

@ -33,7 +33,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.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;
@ -50,7 +49,7 @@ public class PolarisDiscoveryEndPointTest {
private static NamingServer namingServer;
private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(
PolarisDiscoveryEndPointTest.PolarisPropertiesConfiguration.class,
PolarisDiscoveryClientConfiguration.class,
@ -59,8 +58,7 @@ public class PolarisDiscoveryEndPointTest {
.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
@ -69,7 +67,7 @@ public class PolarisDiscoveryEndPointTest {
}
@AfterClass
public static void afterClass() throws Exception {
public static void afterClass() {
if (null != namingServer) {
namingServer.terminate();
}
@ -88,15 +86,12 @@ public class PolarisDiscoveryEndPointTest {
Map<String, Object> mapInfo = polarisDiscoveryEndPoint.polarisDiscovery("java_provider_test");
assertThat(polarisDiscoveryProperties).isEqualTo(mapInfo.get("PolarisDiscoveryProperties"));
});
}
@Configuration
@EnableAutoConfiguration
@EnableDiscoveryClient
static class PolarisPropertiesConfiguration {
}
}

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

@ -28,7 +28,6 @@ import org.junit.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.runner.WebApplicationContextRunner;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationAutoConfiguration;
import org.springframework.context.annotation.Configuration;
@ -45,10 +44,13 @@ public class PolarisServiceRegistryAutoConfigurationTest {
private static NamingServer namingServer;
private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(PolarisContextAutoConfiguration.class,
PolarisServiceRegistryAutoConfiguration.class, PolarisDiscoveryClientConfiguration.class))
.withPropertyValues("spring.application.name=" + SERVICE_PROVIDER).withPropertyValues("server.port=" + PORT)
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");
@BeforeClass
@ -57,7 +59,7 @@ public class PolarisServiceRegistryAutoConfigurationTest {
}
@AfterClass
public static void afterClass() throws Exception {
public static void afterClass() {
if (null != namingServer) {
namingServer.terminate();
}
@ -73,9 +75,7 @@ public class PolarisServiceRegistryAutoConfigurationTest {
@Configuration
@EnableAutoConfiguration
@EnableDiscoveryClient
static class PolarisServiceRegistryAutoConfiguration {
}
}

@ -49,11 +49,14 @@ public class PolarisServiceRegistryTest {
private static NamingServer namingServer;
private 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)
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.token=xxxxxx");
@ -67,7 +70,7 @@ public class PolarisServiceRegistryTest {
}
@AfterClass
public static void afterClass() throws Exception {
public static void afterClass() {
if (null != namingServer) {
namingServer.terminate();
}
@ -108,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 {
@ -126,5 +128,4 @@ public class PolarisServiceRegistryTest {
static class PolarisPropertiesConfiguration {
}
}

@ -45,13 +45,15 @@ public class PolarisRateLimitRuleEndpoint {
private final ServiceRuleManager serviceRuleManager;
private final PolarisRateLimitProperties polarisRateLimitProperties;
public PolarisRateLimitRuleEndpoint(ServiceRuleManager serviceRuleManager, PolarisRateLimitProperties polarisRateLimitProperties) {
public PolarisRateLimitRuleEndpoint(ServiceRuleManager serviceRuleManager,
PolarisRateLimitProperties polarisRateLimitProperties) {
this.serviceRuleManager = serviceRuleManager;
this.polarisRateLimitProperties = polarisRateLimitProperties;
}
@ReadOperation
public Map<String, Object> rateLimit(@Selector String namespace, @Selector String service, @Nullable String dstService) {
public Map<String, Object> rateLimit(
@Selector String namespace, @Selector String service, @Nullable String dstService) {
Map<String, Object> result = new HashMap<>();
RateLimitProto.RateLimit rateLimit = serviceRuleManager.getServiceRateLimitRule(namespace, service);
result.put("properties", polarisRateLimitProperties);
@ -97,5 +99,4 @@ public class PolarisRateLimitRuleEndpoint {
}
return rateLimitRule;
}
}

@ -46,5 +46,4 @@ public class PolarisRateLimitRuleEndpointAutoConfiguration {
public PolarisRateLimitRuleEndpoint polarisRateLimitRuleEndpoint(ServiceRuleManager serviceRuleManager, PolarisRateLimitProperties properties) {
return new PolarisRateLimitRuleEndpoint(serviceRuleManager, properties);
}
}

@ -101,8 +101,8 @@ public class QuotaCheckReactiveFilter implements WebFilter, Ordered {
try {
String path = exchange.getRequest().getURI().getPath();
QuotaResponse quotaResponse = QuotaCheckUtils.getQuota(limitAPI,
localNamespace, localService, 1, labels, path);
QuotaResponse quotaResponse = QuotaCheckUtils.getQuota(
limitAPI, localNamespace, localService, 1, labels, path);
if (quotaResponse.getCode() == QuotaResultCode.QuotaResultLimited) {
ServerHttpResponse response = exchange.getResponse();
@ -162,5 +162,4 @@ public class QuotaCheckReactiveFilter implements WebFilter, Ordered {
Set<String> expressionLabels = rateLimitRuleLabelResolver.getExpressionLabelKeys(namespace, service);
return ExpressionLabelUtils.resolve(exchange, expressionLabels);
}
}

@ -58,13 +58,11 @@ import static com.tencent.cloud.polaris.ratelimit.constant.RateLimitConstant.LAB
@Order(RateLimitConstant.FILTER_ORDER)
public class QuotaCheckServletFilter extends OncePerRequestFilter {
private static final Logger LOG = LoggerFactory.getLogger(QuotaCheckServletFilter.class);
/**
* Default Filter Registration Bean Name Defined .
* Default Filter Registration Bean Name Defined.
*/
public static final String QUOTA_FILTER_BEAN_NAME = "quotaFilterRegistrationBean";
private static final Logger LOG = LoggerFactory.getLogger(QuotaCheckServletFilter.class);
private final LimitAPI limitAPI;
private final PolarisRateLimiterLabelServletResolver labelResolver;
@ -99,8 +97,8 @@ public class QuotaCheckServletFilter extends OncePerRequestFilter {
Map<String, String> labels = getRequestLabels(request, localNamespace, localService);
try {
QuotaResponse quotaResponse = QuotaCheckUtils.getQuota(limitAPI,
localNamespace, localService, 1, labels, request.getRequestURI());
QuotaResponse quotaResponse = QuotaCheckUtils.getQuota(
limitAPI, localNamespace, localService, 1, labels, request.getRequestURI());
if (quotaResponse.getCode() == QuotaResultCode.QuotaResultLimited) {
response.setStatus(polarisRateLimitProperties.getRejectHttpCode());

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

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

@ -55,5 +55,4 @@ public final class QuotaCheckUtils {
return new QuotaResponse(new QuotaResult(QuotaResult.Code.QuotaResultOk, 0, "get quota failed"));
}
}
}

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

@ -42,13 +42,11 @@ import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class RateLimitRuleLabelResolverTest {
private ServiceRuleManager serviceRuleManager;
private RateLimitRuleLabelResolver rateLimitRuleLabelResolver;
@Before
public void setUp() {
serviceRuleManager = mock(ServiceRuleManager.class);
ServiceRuleManager serviceRuleManager = mock(ServiceRuleManager.class);
when(serviceRuleManager.getServiceRateLimitRule(any(), anyString())).thenAnswer(invocationOnMock -> {
String serviceName = invocationOnMock.getArgument(1).toString();
if (serviceName.equals("TestApp1")) {

@ -66,7 +66,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 -> {
@ -83,7 +84,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 -> {

@ -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() {

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

@ -56,9 +56,9 @@ import static org.mockito.Mockito.when;
*/
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
classes = { CalleeControllerTests.Config.class, TestController.class },
properties = { "spring.application.name=java_provider_test", "spring.cloud.polaris.discovery.namespace=Test",
"spring.cloud.polaris.address=grpc://127.0.0.1:10081" })
classes = {CalleeControllerTests.Config.class, TestController.class},
properties = {"spring.application.name=java_provider_test", "spring.cloud.polaris.discovery.namespace=Test",
"spring.cloud.polaris.address=grpc://127.0.0.1:10081"})
public class CalleeControllerTests {
private static NamingServer namingServer;
@ -86,7 +86,7 @@ public class CalleeControllerTests {
}
@AfterClass
public static void afterClass() throws Exception {
public static void afterClass() {
if (null != namingServer) {
namingServer.terminate();
}
@ -142,5 +142,4 @@ public class CalleeControllerTests {
}
}
}

@ -34,5 +34,4 @@ public class TestController {
public String info() throws Exception {
return "hello service info";
}
}

@ -60,8 +60,7 @@ public class PolarisRateLimitRuleEndpointTests {
.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 ServiceRuleManager serviceRuleManager;

@ -69,22 +69,21 @@ import static org.mockito.Mockito.when;
* @author Haotian Zhang, kaiy
*/
@RunWith(MockitoJUnitRunner.class)
@SpringBootTest(classes = QuotaCheckReactiveFilterTest.TestApplication.class, properties = {
"spring.cloud.polaris.namespace=Test", "spring.cloud.polaris.service=TestApp"
})
@SpringBootTest(classes = QuotaCheckReactiveFilterTest.TestApplication.class,
properties = {"spring.cloud.polaris.namespace=Test", "spring.cloud.polaris.service=TestApp"})
public class QuotaCheckReactiveFilterTest {
private PolarisRateLimiterLabelReactiveResolver labelResolver = exchange -> Collections.singletonMap("ReactiveResolver", "ReactiveResolver");
private QuotaCheckReactiveFilter quotaCheckReactiveFilter;
private static MockedStatic<ApplicationContextAwareUtils> mockedApplicationContextAwareUtils;
private static MockedStatic<ExpressionLabelUtils> 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()))
@ -123,9 +122,11 @@ public class QuotaCheckReactiveFilterTest {
polarisRateLimitProperties.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.quotaCheckReactiveFilter = new QuotaCheckReactiveFilter(limitAPI, labelResolver, polarisRateLimitProperties, rateLimitRuleLabelResolver);
this.quotaCheckReactiveFilter = new QuotaCheckReactiveFilter(
limitAPI, labelResolver, polarisRateLimitProperties, rateLimitRuleLabelResolver);
}
@Test
@ -149,7 +150,8 @@ public class QuotaCheckReactiveFilterTest {
@Test
public void testGetRuleExpressionLabels() {
try {
Method getCustomResolvedLabels = QuotaCheckReactiveFilter.class.getDeclaredMethod("getCustomResolvedLabels", ServerWebExchange.class);
Method getCustomResolvedLabels =
QuotaCheckReactiveFilter.class.getDeclaredMethod("getCustomResolvedLabels", ServerWebExchange.class);
getCustomResolvedLabels.setAccessible(true);
// Mock request
@ -162,11 +164,8 @@ public class QuotaCheckReactiveFilterTest {
assertThat(result.get("ReactiveResolver")).isEqualTo("ReactiveResolver");
// throw exception
PolarisRateLimiterLabelReactiveResolver exceptionLabelResolver = new PolarisRateLimiterLabelReactiveResolver() {
@Override
public Map<String, String> resolve(ServerWebExchange exchange) {
throw new RuntimeException("Mock exception.");
}
PolarisRateLimiterLabelReactiveResolver exceptionLabelResolver = exchange1 -> {
throw new RuntimeException("Mock exception.");
};
quotaCheckReactiveFilter = new QuotaCheckReactiveFilter(null, exceptionLabelResolver, null, null);
result = (Map<String, String>) getCustomResolvedLabels.invoke(quotaCheckReactiveFilter, exchange);
@ -203,7 +202,9 @@ public class QuotaCheckReactiveFilterTest {
MetadataContext.LOCAL_SERVICE = "TestApp2";
long startTimestamp = System.currentTimeMillis();
CountDownLatch countDownLatch = new CountDownLatch(1);
quotaCheckReactiveFilter.filter(exchange, webFilterChain).subscribe(e -> { }, t -> { }, countDownLatch::countDown);
quotaCheckReactiveFilter.filter(exchange, webFilterChain).subscribe(e -> {
}, t -> {
}, countDownLatch::countDown);
try {
countDownLatch.await();
}

@ -73,18 +73,18 @@ import static org.mockito.Mockito.when;
})
public class QuotaCheckServletFilterTest {
private PolarisRateLimiterLabelServletResolver labelResolver = exchange -> Collections.singletonMap("ServletResolver", "ServletResolver");
private static MockedStatic<ApplicationContextAwareUtils> mockedApplicationContextAwareUtils;
private static MockedStatic<ExpressionLabelUtils> expressionLabelUtilsMockedStatic;
private final PolarisRateLimiterLabelServletResolver labelResolver =
exchange -> Collections.singletonMap("ServletResolver", "ServletResolver");
private QuotaCheckServletFilter quotaCheckServletFilter;
private QuotaCheckServletFilter quotaCheckWithHtmlRejectTipsServletFilter;
private static MockedStatic<ApplicationContextAwareUtils> mockedApplicationContextAwareUtils;
private static MockedStatic<ExpressionLabelUtils> 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()))
@ -127,10 +127,12 @@ 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.quotaCheckServletFilter = new QuotaCheckServletFilter(
limitAPI, labelResolver, polarisRateLimitProperties, rateLimitRuleLabelResolver);
this.quotaCheckWithHtmlRejectTipsServletFilter = new QuotaCheckServletFilter(
limitAPI, labelResolver, polarisRateLimitWithHtmlRejectTipsProperties, rateLimitRuleLabelResolver);
}
@Test

@ -21,12 +21,14 @@ 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() {
}
}

@ -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<String, String> resolve(RequestTemplate request, Set<String> labelKeys) {
if (CollectionUtils.isEmpty(labelKeys)) {

@ -68,7 +68,5 @@ public final class ContextConstant {
* Order of configuration modifier.
*/
public static Integer CONFIG_ORDER = 1;
}
}

@ -45,7 +45,6 @@ public final class MetadataConstant {
* Order of Metadata2HeaderInterceptor.
*/
public static int METADATA_2_HEADER_INTERCEPTOR_ORDER = Ordered.LOWEST_PRECEDENCE;
}
/**
@ -67,7 +66,5 @@ public final class MetadataConstant {
* Metadata context.
*/
public static final String METADATA_CONTEXT = "SCT-METADATA-CONTEXT";
}
}

@ -105,5 +105,4 @@ public final class MetadataContextHolder {
public static void remove() {
METADATA_CONTEXT.remove();
}
}

@ -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<String, String> envMetadata;
private Map<String, String> envTransitiveMetadata;
private Map<String, String> configMetadata;

@ -61,5 +61,4 @@ public class MetadataFirstScgFilter implements GlobalFilter, Ordered {
return chain.filter(exchange);
}
}

@ -93,5 +93,4 @@ public class PolarisServiceInstance implements ServiceInstance {
public String getScheme() {
return this.scheme;
}
}

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

@ -28,9 +28,13 @@ 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 <T> List<T> getBeans(BeanFactory beanFactory, Class<T> requiredType) {
if (!(beanFactory instanceof DefaultListableBeanFactory)) {

@ -40,9 +40,9 @@ import org.springframework.web.server.ServerWebExchange;
/**
* the utils for parse label expression.
*
*@author lepdou 2022-05-13
* @author lepdou 2022-05-13
*/
public class ExpressionLabelUtils {
public final class ExpressionLabelUtils {
/**
* the expression prefix of header label.
@ -84,6 +84,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)) {

@ -36,7 +36,7 @@ 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" })
properties = {"spring.config.location = classpath:application-test.yml"})
public class MetadataContextHolderTest {
@Test
@ -77,5 +77,4 @@ public class MetadataContextHolderTest {
protected static class TestApplication {
}
}

@ -38,8 +38,9 @@ import static org.mockito.Mockito.when;
/**
* test for {@link StaticMetadataManager}
*@author lepdou 2022-06-27
* test for {@link StaticMetadataManager}.
*
* @author lepdou 2022-06-27
*/
@RunWith(MockitoJUnitRunner.class)
public class StaticMetadataManagerTest {
@ -182,5 +183,4 @@ public class StaticMetadataManagerTest {
return null;
}
}
}

@ -84,5 +84,4 @@ public class MetadataAutoConfigurationTest {
Assertions.assertThat(context).hasSingleBean(MetadataFirstScgFilter.class);
});
}
}

@ -34,7 +34,7 @@ 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" })
properties = {"spring.config.location = classpath:application-test.yml"})
public class MetadataLocalPropertiesTest {
@Autowired
@ -42,22 +42,18 @@ public class MetadataLocalPropertiesTest {
@Test
public void test1() {
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();
}
@Test
public void test2() {
Assertions.assertThat(metadataLocalProperties.getTransitive().contains("b"))
.isTrue();
Assertions.assertThat(metadataLocalProperties.getTransitive().contains("b")).isTrue();
}
@SpringBootApplication
protected static class TestApplication {
}
}

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

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

Loading…
Cancel
Save