Merge remote-tracking branch upstream/2020.0 into 2020.0

pull/379/head
wulingxiao 3 years ago
commit 252cc803ea

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

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

@ -17,3 +17,12 @@
- [feat:Add GitHub action of codecov.yml.](https://github.com/Tencent/spring-cloud-tencent/pull/330)
- [Feature: add spring cloud tencent logo](https://github.com/Tencent/spring-cloud-tencent/pull/331)
- [UT: add metadata-transfer unit test](https://github.com/Tencent/spring-cloud-tencent/pull/334)
- [Optimize code style & unit test case](https://github.com/Tencent/spring-cloud-tencent/pull/337)
- [test:update junit of metadata.](https://github.com/Tencent/spring-cloud-tencent/pull/338)
- [Feature: Optimize static metadata manager](https://github.com/Tencent/spring-cloud-tencent/pull/341)
- [fix: shutdown thread pool before the container closes](https://github.com/Tencent/spring-cloud-tencent/pull/354)
- [rm code: Condition 'null != interceptors' is always 'true' ](https://github.com/Tencent/spring-cloud-tencent/pull/356)
- [docs:update logo in README.](https://github.com/Tencent/spring-cloud-tencent/pull/359)
- [Use jdk constants instead of magic variables](https://github.com/Tencent/spring-cloud-tencent/pull/362)
- [Refator JacksonUtils and JacksonUtilsTest](https://github.com/Tencent/spring-cloud-tencent/pull/366)
- [Feature: support actuator for sct core components](https://github.com/Tencent/spring-cloud-tencent/pull/370)

@ -1,4 +1,4 @@
<img src="https://user-images.githubusercontent.com/4991116/176166888-9c8a4074-ba42-41b8-93db-d6e95b16656b.png" width="60%" height="60%" alt="Spring-Cloud-Tencent-Logo"/>
<img src="https://github.com/Tencent/spring-cloud-tencent/raw/2020.0/doc/logo/rectangle-white.png" width="60%" height="60%" alt="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)

@ -1,4 +1,4 @@
<img src="https://user-images.githubusercontent.com/4991116/176166888-9c8a4074-ba42-41b8-93db-d6e95b16656b.png" width="60%" height="60%" alt="Spring-Cloud-Tencent-Logo"/>
<img src="https://github.com/Tencent/spring-cloud-tencent/raw/2020.0/doc/logo/rectangle-white.png" width="60%" height="60%" alt="Spring-Cloud-Tencent-Logo"/>
[![Wiki](https://badgen.net/badge/icon/wiki?icon=wiki&label)](https://github.com/Tencent/spring-cloud-tencent/wiki)

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg width="424px" height="82px" viewBox="0 0 424 82" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<title>长款的 svg格式透明</title>
<g id="长款的-svg格式透明" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<rect id="矩形" x="0" y="0" width="424" height="82"></rect>
<text id="Spring-Cloud-Tencent" font-family="TencentSansW7, TencentSans" font-size="34" font-weight="bold" letter-spacing="-0.50303" fill="#000000">
<tspan x="83.8428418" y="49.8255109">Spring Cloud Tencent</tspan>
</text>
<polygon id="路径-2备份-10" fill="#95D2F7" points="43.9206195 11.8255109 43.9206195 21.8255109 52.6095084 16.8255109"></polygon>
<polygon id="矩形备份-25" fill="#7F98FF" points="24.9833459 32.3489782 48.8428418 46.1744891 48.8428418 73.8255109 24.9833459 60"></polygon>
<polygon id="矩形备份-26" fill="#7F98FF" transform="translate(55.772590, 29.412755) scale(-1, 1) translate(-55.772590, -29.412755) " points="43.8428418 8 67.7023376 21.8255109 67.7023376 50.8255109 43.8428418 37"></polygon>
<polygon id="矩形备份-27" fill="#95D2F7" transform="translate(24.983346, 21.523467) scale(-1, 1) translate(-24.983346, -21.523467) " points="24.9833459 10.5234673 43.9666917 21.5234673 24.9833459 32.5234673 6 21.5234673"></polygon>
<polygon id="路径-3" fill="#4065FF" points="43.8428418 43.2977777 43.8428418 50.8255109 48.8428418 47.9799656 48.8428418 46.1744891"></polygon>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg width="424px" height="82px" viewBox="0 0 424 82" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<title>长款的 svg 格式的白底</title>
<g id="长款的-svg-格式的白底" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<rect id="矩形" fill="#FFFFFF" x="0" y="0" width="424" height="82"></rect>
<rect id="矩形" fill="#FFFFFF" x="6" y="8" width="412" height="66"></rect>
<text id="Spring-Cloud-Tencent" font-family="TencentSansW7, TencentSans" font-size="34" font-weight="bold" letter-spacing="-0.50303" fill="#000000">
<tspan x="83.8428418" y="49.8255109">Spring Cloud Tencent</tspan>
</text>
<polygon id="路径-2备份-10" fill="#95D2F7" points="43.9206195 11.8255109 43.9206195 21.8255109 52.6095084 16.8255109"></polygon>
<polygon id="矩形备份-25" fill="#7F98FF" points="24.9833459 32.3489782 48.8428418 46.1744891 48.8428418 73.8255109 24.9833459 60"></polygon>
<polygon id="矩形备份-26" fill="#7F98FF" transform="translate(55.772590, 29.412755) scale(-1, 1) translate(-55.772590, -29.412755) " points="43.8428418 8 67.7023376 21.8255109 67.7023376 50.8255109 43.8428418 37"></polygon>
<polygon id="矩形备份-27" fill="#95D2F7" transform="translate(24.983346, 21.523467) scale(-1, 1) translate(-24.983346, -21.523467) " points="24.9833459 10.5234673 43.9666917 21.5234673 24.9833459 32.5234673 6 21.5234673"></polygon>
<polygon id="路径-3" fill="#4065FF" points="43.8428418 43.2977777 43.8428418 50.8255109 48.8428418 47.9799656 48.8428418 46.1744891"></polygon>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.7 KiB

@ -68,8 +68,10 @@ public class MetadataTransferAutoConfiguration {
DecodeTransferMetadataServletFilter decodeTransferMetadataServletFilter) {
FilterRegistrationBean<DecodeTransferMetadataServletFilter> filterRegistrationBean = new FilterRegistrationBean<>(
decodeTransferMetadataServletFilter);
filterRegistrationBean.setDispatcherTypes(ASYNC, ERROR, FORWARD, INCLUDE, REQUEST);
filterRegistrationBean.setOrder(MetadataConstant.OrderConstant.WEB_FILTER_ORDER);
filterRegistrationBean.setDispatcherTypes(ASYNC, ERROR, FORWARD, INCLUDE,
REQUEST);
filterRegistrationBean
.setOrder(MetadataConstant.OrderConstant.WEB_FILTER_ORDER);
return filterRegistrationBean;
}
@ -140,29 +142,34 @@ public class MetadataTransferAutoConfiguration {
BeanPostProcessor encodeTransferMetadataRestTemplatePostProcessor(
EncodeTransferMedataRestTemplateInterceptor encodeTransferMedataRestTemplateInterceptor) {
// Coping with multiple bean injection scenarios
Map<String, RestTemplate> beans = this.context.getBeansOfType(RestTemplate.class);
Map<String, RestTemplate> beans = this.context
.getBeansOfType(RestTemplate.class);
// If the restTemplate has been created when the
// MetadataRestTemplatePostProcessor Bean
// is initialized, then manually set the interceptor.
if (!CollectionUtils.isEmpty(beans)) {
for (RestTemplate restTemplate : beans.values()) {
List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors();
List<ClientHttpRequestInterceptor> interceptors = restTemplate
.getInterceptors();
// Avoid setting interceptor repeatedly.
if (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;
}
public static class EncodeTransferMetadataRestTemplatePostProcessor implements BeanPostProcessor {
public static class EncodeTransferMetadataRestTemplatePostProcessor
implements BeanPostProcessor {
private EncodeTransferMedataRestTemplateInterceptor encodeTransferMedataRestTemplateInterceptor;
@ -180,9 +187,10 @@ public class MetadataTransferAutoConfiguration {
public Object postProcessAfterInitialization(Object bean, String beanName) {
if (bean instanceof RestTemplate) {
RestTemplate restTemplate = (RestTemplate) bean;
List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors();
List<ClientHttpRequestInterceptor> interceptors = restTemplate
.getInterceptors();
// Avoid setting interceptor repeatedly.
if (null != interceptors && !interceptors.contains(encodeTransferMedataRestTemplateInterceptor)) {
if (!interceptors.contains(encodeTransferMedataRestTemplateInterceptor)) {
interceptors.add(this.encodeTransferMedataRestTemplateInterceptor);
restTemplate.setInterceptors(interceptors);
}

@ -32,8 +32,8 @@ 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 {

@ -20,6 +20,7 @@ package com.tencent.cloud.metadata.core;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
@ -84,7 +85,7 @@ public class DecodeTransferMetadataReactiveFilter implements WebFilter, Ordered
.getFirst(MetadataConstant.HeaderName.CUSTOM_METADATA);
try {
if (StringUtils.hasText(customMetadataStr)) {
customMetadataStr = URLDecoder.decode(customMetadataStr, "UTF-8");
customMetadataStr = URLDecoder.decode(customMetadataStr, StandardCharsets.UTF_8.name());
}
}
catch (UnsupportedEncodingException e) {

@ -21,6 +21,7 @@ package com.tencent.cloud.metadata.core;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
@ -76,7 +77,7 @@ public class DecodeTransferMetadataServletFilter extends OncePerRequestFilter {
String customMetadataStr = httpServletRequest.getHeader(MetadataConstant.HeaderName.CUSTOM_METADATA);
try {
if (StringUtils.hasText(customMetadataStr)) {
customMetadataStr = URLDecoder.decode(customMetadataStr, "UTF-8");
customMetadataStr = URLDecoder.decode(customMetadataStr, StandardCharsets.UTF_8.name());
}
}
catch (UnsupportedEncodingException e) {

@ -20,6 +20,7 @@ package com.tencent.cloud.metadata.core;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import com.tencent.cloud.common.constant.MetadataConstant;
@ -61,7 +62,8 @@ 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, StandardCharsets.UTF_8.name()));
}
catch (UnsupportedEncodingException e) {
LOG.error("Set header failed.", e);

@ -21,6 +21,7 @@ package com.tencent.cloud.metadata.core;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import com.tencent.cloud.common.constant.MetadataConstant;
@ -59,7 +60,7 @@ public class EncodeTransferMedataRestTemplateInterceptor implements ClientHttpRe
String encodedTransitiveMetadata = JacksonUtils.serialize2Json(customMetadata);
try {
httpRequest.getHeaders().set(MetadataConstant.HeaderName.CUSTOM_METADATA,
URLEncoder.encode(encodedTransitiveMetadata, "UTF-8"));
URLEncoder.encode(encodedTransitiveMetadata, StandardCharsets.UTF_8.name()));
}
catch (UnsupportedEncodingException e) {
httpRequest.getHeaders().set(MetadataConstant.HeaderName.CUSTOM_METADATA, encodedTransitiveMetadata);

@ -20,6 +20,7 @@ package com.tencent.cloud.metadata.core;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import com.tencent.cloud.common.constant.MetadataConstant;
@ -67,7 +68,8 @@ 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, StandardCharsets.UTF_8.name()));
}
catch (UnsupportedEncodingException e) {
builder.header(MetadataConstant.HeaderName.CUSTOM_METADATA, metadataStr);

@ -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;
@ -30,6 +28,7 @@ import org.springframework.mock.web.server.MockServerWebExchange;
/**
* Test for {@link CustomTransitiveMetadataResolver}.
*
* @author quan
*/
public class CustomTransitiveMetadataResolverTest {

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

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

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

@ -13,17 +13,15 @@
* 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;

@ -13,20 +13,18 @@
* 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;
import java.nio.charset.StandardCharsets;
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 +42,13 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
/**
* 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 +60,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, "UTF-8");
// 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<String, String> transitiveMap = JacksonUtils.deserialize2Map(decode);
Assertions.assertThat(transitiveMap.size()).isEqualTo(1);
Assert.assertEquals(transitiveMap.get("b"), "2");
Assertions.assertThat(transitiveMap.get("b")).isEqualTo("2");
}
@SpringBootApplication

@ -90,6 +90,12 @@
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>

@ -18,7 +18,7 @@
package com.tencent.cloud.polaris.circuitbreaker.config;
import com.tencent.cloud.polaris.circuitbreaker.feign.PolarisFeignBeanPostProcessor;
import com.tencent.cloud.polaris.context.PolarisContextAutoConfiguration;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import com.tencent.polaris.api.core.ConsumerAPI;
import com.tencent.polaris.client.api.SDKContext;
import com.tencent.polaris.factory.api.DiscoveryAPIFactory;

@ -20,7 +20,7 @@ package com.tencent.cloud.polaris.circuitbreaker.config;
import com.tencent.cloud.polaris.circuitbreaker.resttemplate.PolarisResponseErrorHandler;
import com.tencent.cloud.polaris.circuitbreaker.resttemplate.PolarisRestTemplateModifier;
import com.tencent.cloud.polaris.circuitbreaker.resttemplate.PolarisRestTemplateResponseErrorHandler;
import com.tencent.cloud.polaris.context.PolarisContextAutoConfiguration;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import com.tencent.polaris.api.core.ConsumerAPI;
import org.springframework.beans.factory.annotation.Autowired;
@ -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,16 @@ 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);
}
}

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

@ -28,10 +28,10 @@ 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 {

@ -29,24 +29,25 @@ 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;
@ -59,12 +60,12 @@ public class PolarisRestTemplateResponseErrorHandler implements ResponseErrorHan
}
@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 +73,22 @@ 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 +97,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,13 +109,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;
}

@ -19,7 +19,7 @@ package com.tencent.cloud.polaris.circuitbreaker;
import com.tencent.cloud.polaris.circuitbreaker.config.PolarisFeignClientAutoConfiguration;
import com.tencent.cloud.polaris.circuitbreaker.feign.PolarisFeignBeanPostProcessor;
import com.tencent.cloud.polaris.context.PolarisContextAutoConfiguration;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import com.tencent.polaris.api.core.ConsumerAPI;
import org.junit.Test;

@ -0,0 +1,72 @@
/*
* 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 <a href="mailto:iskp.me@gmail.com">Palmer Xu</a> 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();
}
}
}

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

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

@ -71,6 +71,18 @@
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-actuator</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-actuator-autoconfigure</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-inline</artifactId>

@ -25,7 +25,7 @@ import com.tencent.cloud.common.constant.ContextConstant;
import com.tencent.cloud.common.util.AddressUtils;
import com.tencent.cloud.polaris.config.config.PolarisConfigProperties;
import com.tencent.cloud.polaris.context.PolarisConfigModifier;
import com.tencent.cloud.polaris.context.PolarisContextProperties;
import com.tencent.cloud.polaris.context.config.PolarisContextProperties;
import com.tencent.polaris.factory.config.ConfigurationImpl;
import org.apache.commons.lang.StringUtils;

@ -21,8 +21,8 @@ import com.tencent.cloud.polaris.config.adapter.PolarisConfigFileLocator;
import com.tencent.cloud.polaris.config.adapter.PolarisPropertySourceManager;
import com.tencent.cloud.polaris.config.config.PolarisConfigProperties;
import com.tencent.cloud.polaris.context.ConditionalOnPolarisEnabled;
import com.tencent.cloud.polaris.context.PolarisContextAutoConfiguration;
import com.tencent.cloud.polaris.context.PolarisContextProperties;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import com.tencent.cloud.polaris.context.config.PolarisContextProperties;
import com.tencent.polaris.client.api.SDKContext;
import com.tencent.polaris.configuration.api.core.ConfigFileService;
import com.tencent.polaris.configuration.factory.ConfigFileServiceFactory;

@ -25,7 +25,7 @@ import java.util.concurrent.ConcurrentHashMap;
import com.tencent.cloud.polaris.config.config.ConfigFileGroup;
import com.tencent.cloud.polaris.config.config.PolarisConfigProperties;
import com.tencent.cloud.polaris.config.enums.ConfigFileFormat;
import com.tencent.cloud.polaris.context.PolarisContextProperties;
import com.tencent.cloud.polaris.context.config.PolarisContextProperties;
import com.tencent.polaris.configuration.api.core.ConfigFileMetadata;
import com.tencent.polaris.configuration.api.core.ConfigFileService;
import com.tencent.polaris.configuration.api.core.ConfigKVFile;

@ -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<String, Object> polarisConfig() {
Map<String, Object> configInfo = new HashMap<>();
configInfo.put("PolarisConfigProperties", polarisConfigProperties);
List<PolarisPropertySource> propertySourceList = polarisPropertySourceManager.getAllPropertySources();
configInfo.put("PolarisPropertySource", propertySourceList);
return configInfo;
}
}

@ -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);
}
}

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

@ -26,7 +26,7 @@ import java.util.Map;
import com.google.common.collect.Lists;
import com.tencent.cloud.polaris.config.config.ConfigFileGroup;
import com.tencent.cloud.polaris.config.config.PolarisConfigProperties;
import com.tencent.cloud.polaris.context.PolarisContextProperties;
import com.tencent.cloud.polaris.context.config.PolarisContextProperties;
import com.tencent.polaris.configuration.api.core.ConfigFileService;
import com.tencent.polaris.configuration.api.core.ConfigKVFile;
import org.junit.Assert;

@ -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<String, Object> 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<String, Object> info = endpoint.polarisConfig();
assertThat(polarisConfigProperties).isEqualTo(info.get("PolarisConfigProperties"));
assertThat(Lists.newArrayList(polarisPropertySource)).isEqualTo(info.get("PolarisPropertySource"));
}
}

@ -94,6 +94,18 @@
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-actuator</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-actuator-autoconfigure</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>

@ -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,7 @@ import static com.tencent.cloud.polaris.discovery.refresh.PolarisServiceStatusCh
*
* @author Haotian Zhang
*/
public class PolarisRefreshApplicationReadyEventListener implements ApplicationListener<ApplicationReadyEvent>, ApplicationEventPublisherAware {
public class PolarisRefreshApplicationReadyEventListener implements ApplicationListener<ApplicationReadyEvent>, ApplicationEventPublisherAware, DisposableBean {
private static final Logger LOG = LoggerFactory.getLogger(PolarisRefreshApplicationReadyEventListener.class);
private static final int DELAY = 60;
@ -83,4 +84,9 @@ public class PolarisRefreshApplicationReadyEventListener implements ApplicationL
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.publisher = applicationEventPublisher;
}
@Override
public void destroy() throws Exception {
refreshExecutor.shutdown();
}
}

@ -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<String, Object> polarisDiscovery(@Selector String serviceId) {
Map<String, Object> polarisDisConveryInfo = new HashMap<>();
polarisDisConveryInfo.put("PolarisDiscoveryProperties", polarisDiscoveryProperties);
List<ServiceInstances> 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;
}
}

@ -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);
}
}

@ -26,7 +26,6 @@ import java.util.Map;
import com.tencent.cloud.common.metadata.StaticMetadataManager;
import com.tencent.cloud.polaris.DiscoveryPropertiesAutoConfiguration;
import com.tencent.cloud.polaris.PolarisDiscoveryProperties;
import com.tencent.cloud.polaris.context.spi.InstanceMetadataProvider;
import com.tencent.polaris.client.api.SDKContext;
import org.apache.commons.lang.StringUtils;
@ -53,8 +52,6 @@ public class PolarisRegistration implements Registration, ServiceInstance {
private final StaticMetadataManager staticMetadataManager;
private final InstanceMetadataProvider instanceMetadataProvider;
private Map<String, String> metadata;
private final String host;
@ -62,13 +59,11 @@ public class PolarisRegistration implements Registration, ServiceInstance {
public PolarisRegistration(
DiscoveryPropertiesAutoConfiguration discoveryPropertiesAutoConfiguration,
PolarisDiscoveryProperties polarisDiscoveryProperties, SDKContext context,
StaticMetadataManager staticMetadataManager,
InstanceMetadataProvider instanceMetadataProvider) {
StaticMetadataManager staticMetadataManager) {
this.discoveryPropertiesAutoConfiguration = discoveryPropertiesAutoConfiguration;
this.polarisDiscoveryProperties = polarisDiscoveryProperties;
this.polarisContext = context;
this.staticMetadataManager = staticMetadataManager;
this.instanceMetadataProvider = instanceMetadataProvider;
host = polarisContext.getConfig().getGlobal().getAPI().getBindIP();
}
@ -116,23 +111,6 @@ public class PolarisRegistration implements Registration, ServiceInstance {
// location info will be putted both in metadata and instance's field
instanceMetadata.putAll(staticMetadataManager.getLocationMetadata());
// custom metadata from spi
if (instanceMetadataProvider != null) {
if (StringUtils.isNotBlank(instanceMetadataProvider.getRegion())) {
instanceMetadata.put(StaticMetadataManager.LOCATION_KEY_ZONE, instanceMetadataProvider.getRegion());
}
if (StringUtils.isNotBlank(instanceMetadataProvider.getZone())) {
instanceMetadata.put(StaticMetadataManager.LOCATION_KEY_ZONE, instanceMetadataProvider.getZone());
}
if (StringUtils.isNotBlank(instanceMetadataProvider.getCampus())) {
instanceMetadata.put(StaticMetadataManager.LOCATION_KEY_ZONE, instanceMetadataProvider.getCampus());
}
if (!CollectionUtils.isEmpty(instanceMetadataProvider.getMetadata())) {
instanceMetadata.putAll(instanceMetadataProvider.getMetadata());
}
}
this.metadata = Collections.unmodifiableMap(instanceMetadata);
}
return metadata;

@ -21,7 +21,6 @@ package com.tencent.cloud.polaris.registry;
import com.tencent.cloud.common.metadata.StaticMetadataManager;
import com.tencent.cloud.polaris.DiscoveryPropertiesAutoConfiguration;
import com.tencent.cloud.polaris.PolarisDiscoveryProperties;
import com.tencent.cloud.polaris.context.spi.InstanceMetadataProvider;
import com.tencent.cloud.polaris.discovery.PolarisDiscoveryAutoConfiguration;
import com.tencent.cloud.polaris.discovery.PolarisDiscoveryHandler;
import com.tencent.polaris.client.api.SDKContext;
@ -35,7 +34,6 @@ import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationC
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.Nullable;
/**
* Autoconfiguration of service registry of Polaris.
@ -62,9 +60,9 @@ public class PolarisServiceRegistryAutoConfiguration {
public PolarisRegistration polarisRegistration(
DiscoveryPropertiesAutoConfiguration discoveryPropertiesAutoConfiguration,
PolarisDiscoveryProperties polarisDiscoveryProperties, SDKContext context,
StaticMetadataManager staticMetadataManager, @Nullable InstanceMetadataProvider instanceMetadataProvider) {
StaticMetadataManager staticMetadataManager) {
return new PolarisRegistration(discoveryPropertiesAutoConfiguration,
polarisDiscoveryProperties, context, staticMetadataManager, instanceMetadataProvider);
polarisDiscoveryProperties, context, staticMetadataManager);
}
@Bean

@ -1,6 +1,7 @@
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.tencent.cloud.polaris.DiscoveryPropertiesAutoConfiguration,\
com.tencent.cloud.polaris.discovery.PolarisDiscoveryAutoConfiguration,\
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

@ -17,7 +17,7 @@
package com.tencent.cloud.polaris;
import com.tencent.cloud.polaris.context.PolarisContextAutoConfiguration;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import com.tencent.cloud.polaris.discovery.PolarisDiscoveryHandler;
import com.tencent.cloud.polaris.extend.consul.ConsulContextProperties;
import com.tencent.polaris.api.core.ConsumerAPI;

@ -17,7 +17,7 @@
package com.tencent.cloud.polaris;
import com.tencent.cloud.polaris.context.PolarisContextAutoConfiguration;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import org.junit.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;

@ -19,7 +19,7 @@
package com.tencent.cloud.polaris.discovery;
import com.tencent.cloud.polaris.PolarisDiscoveryProperties;
import com.tencent.cloud.polaris.context.PolarisContextAutoConfiguration;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import com.tencent.polaris.api.core.ConsumerAPI;
import com.tencent.polaris.api.core.ProviderAPI;
import com.tencent.polaris.test.mock.discovery.NamingServer;

@ -17,7 +17,7 @@
package com.tencent.cloud.polaris.discovery;
import com.tencent.cloud.polaris.context.PolarisContextAutoConfiguration;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import com.tencent.polaris.test.mock.discovery.NamingServer;
import org.junit.AfterClass;
import org.junit.BeforeClass;

@ -19,7 +19,7 @@ package com.tencent.cloud.polaris.discovery;
import java.util.List;
import com.tencent.cloud.polaris.context.PolarisContextAutoConfiguration;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import com.tencent.polaris.api.exception.PolarisException;
import com.tencent.polaris.api.pojo.ServiceKey;
import com.tencent.polaris.test.mock.discovery.NamingServer;

@ -17,7 +17,7 @@
package com.tencent.cloud.polaris.discovery.reactive;
import com.tencent.cloud.polaris.context.PolarisContextAutoConfiguration;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import com.tencent.cloud.polaris.discovery.PolarisDiscoveryClientConfiguration;
import com.tencent.polaris.test.mock.discovery.NamingServer;
import org.junit.AfterClass;

@ -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<String, Object> mapInfo = polarisDiscoveryEndPoint.polarisDiscovery("java_provider_test");
assertThat(polarisDiscoveryProperties).isEqualTo(mapInfo.get("PolarisDiscoveryProperties"));
});
}
@Configuration
@EnableAutoConfiguration
@EnableDiscoveryClient
static class PolarisPropertiesConfiguration {
}
}

@ -78,7 +78,7 @@ public class PolarisRegistrationTest {
doReturn(Collections.singletonMap("key2", "value2")).when(staticMetadataManager).getLocationMetadata();
polarisRegistration = new PolarisRegistration(
discoveryPropertiesAutoConfiguration, polarisDiscoveryProperties, polarisContext, staticMetadataManager, null);
discoveryPropertiesAutoConfiguration, polarisDiscoveryProperties, polarisContext, staticMetadataManager);
}
@Test

@ -17,7 +17,7 @@
package com.tencent.cloud.polaris.registry;
import com.tencent.cloud.polaris.context.PolarisContextAutoConfiguration;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import com.tencent.cloud.polaris.discovery.PolarisDiscoveryAutoConfiguration;
import com.tencent.cloud.polaris.discovery.PolarisDiscoveryClientConfiguration;
import com.tencent.polaris.test.mock.discovery.NamingServer;

@ -17,7 +17,7 @@
package com.tencent.cloud.polaris.registry;
import com.tencent.cloud.polaris.context.PolarisContextAutoConfiguration;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import com.tencent.cloud.polaris.discovery.PolarisDiscoveryAutoConfiguration;
import com.tencent.cloud.polaris.discovery.PolarisDiscoveryClientConfiguration;
import com.tencent.polaris.api.pojo.ServiceKey;

@ -84,6 +84,18 @@
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-actuator</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-actuator-autoconfigure</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-inline</artifactId>

@ -19,8 +19,8 @@
package com.tencent.cloud.polaris.ratelimit.config;
import com.tencent.cloud.polaris.context.ConditionalOnPolarisEnabled;
import com.tencent.cloud.polaris.context.PolarisContextAutoConfiguration;
import com.tencent.cloud.polaris.context.ServiceRuleManager;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import com.tencent.cloud.polaris.ratelimit.RateLimitRuleLabelResolver;
import com.tencent.cloud.polaris.ratelimit.constant.RateLimitConstant;
import com.tencent.cloud.polaris.ratelimit.filter.QuotaCheckReactiveFilter;

@ -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<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);
result.put("namespace", namespace);
result.put("service", service);
result.put("rateLimits", parseRateLimitRule(rateLimit));
if (StringUtils.isEmpty(dstService)) {
return result;
}
List<RoutingProto.Route> routes = serviceRuleManager.getServiceRouterRule(namespace, service, dstService);
result.put("routes", routes);
return result;
}
private List<Object> parseRateLimitRule(RateLimitProto.RateLimit rateLimit) {
List<Object> rateLimitRule = new ArrayList<>();
if (rateLimit == null || CollectionUtils.isEmpty(rateLimit.getRulesList())) {
return rateLimitRule;
}
for (RateLimitProto.Rule rule : rateLimit.getRulesList()) {
Map<String, Object> 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;
}
}

@ -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);
}
}

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

@ -17,7 +17,7 @@
package com.tencent.cloud.polaris.ratelimit.config;
import com.tencent.cloud.polaris.context.PolarisContextAutoConfiguration;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import com.tencent.cloud.polaris.ratelimit.RateLimitRuleLabelResolver;
import com.tencent.cloud.polaris.ratelimit.filter.QuotaCheckReactiveFilter;
import com.tencent.cloud.polaris.ratelimit.filter.QuotaCheckServletFilter;

@ -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<String, Object> rateLimit = polarisRateLimitRuleEndpoint.rateLimit("namespaceTest", "TestApp2", "TestApp3");
assertThat(polarisRateLimitProperties).isEqualTo(rateLimit.get("properties"));
}
@Configuration
@EnableAutoConfiguration
static class PolarisRateLimitAutoConfiguration {
}
}

@ -18,6 +18,7 @@
package com.tencent.cloud.polaris.router.spi;
import java.util.Collections;
import java.util.Map;
import feign.RequestTemplate;
@ -37,7 +38,9 @@ public interface RouterLabelResolver extends Ordered {
* @param requestTemplate the feign request.
* @return resolved labels
*/
Map<String, String> resolve(RequestTemplate requestTemplate);
default Map<String, String> resolve(RequestTemplate requestTemplate) {
return Collections.emptyMap();
}
/**
* resolve labels from rest template request.
@ -45,5 +48,7 @@ public interface RouterLabelResolver extends Ordered {
* @param body the rest template request body.
* @return resolved labels
*/
Map<String, String> resolve(HttpRequest request, byte[] body);
default Map<String, String> resolve(HttpRequest request, byte[] body) {
return Collections.emptyMap();
}
}

@ -87,6 +87,18 @@
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-actuator</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-actuator-autoconfigure</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
</project>

@ -22,14 +22,18 @@ import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.tencent.cloud.common.metadata.config.MetadataLocalProperties;
import com.tencent.cloud.common.spi.InstanceMetadataProvider;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
/**
* manage metadata from env/config file.
* manage metadata from env/config file/custom spi.
*
*@author lepdou 2022-05-20
*/
@ -60,17 +64,26 @@ public class StaticMetadataManager {
private Map<String, String> envTransitiveMetadata;
private Map<String, String> configMetadata;
private Map<String, String> configTransitiveMetadata;
private Map<String, String> customSPIMetadata;
private Map<String, String> customSPITransitiveMetadata;
private Map<String, String> mergedStaticMetadata;
private Map<String, String> mergedStaticTransitiveMetadata;
private String zone;
private String region;
private String campus;
public StaticMetadataManager(MetadataLocalProperties metadataLocalProperties) {
public StaticMetadataManager(MetadataLocalProperties metadataLocalProperties,
InstanceMetadataProvider instanceMetadataProvider) {
parseConfigMetadata(metadataLocalProperties);
parseEnvMetadata();
parseCustomMetadata(instanceMetadataProvider);
parseLocationMetadata(metadataLocalProperties, instanceMetadataProvider);
merge();
parseLocationMetadata();
LOGGER.info("[SCT] Loaded static metadata info. {}", this);
}
@ -125,26 +138,89 @@ public class StaticMetadataManager {
configMetadata = Collections.unmodifiableMap(allMetadata);
}
private void parseCustomMetadata(InstanceMetadataProvider instanceMetadataProvider) {
if (instanceMetadataProvider == null) {
customSPIMetadata = Collections.emptyMap();
customSPITransitiveMetadata = Collections.emptyMap();
return;
}
// resolve all metadata
Map<String, String> allMetadata = instanceMetadataProvider.getMetadata();
if (allMetadata == null) {
customSPIMetadata = Collections.emptyMap();
}
else {
customSPIMetadata = Collections.unmodifiableMap(allMetadata);
}
// resolve transitive metadata
Set<String> transitiveKeys = instanceMetadataProvider.getTransitiveMetadataKeys();
Map<String, String> transitiveMetadata = new HashMap<>();
if (!CollectionUtils.isEmpty(transitiveKeys)) {
for (String key : transitiveKeys) {
if (customSPIMetadata.containsKey(key)) {
transitiveMetadata.put(key, customSPIMetadata.get(key));
}
}
}
customSPITransitiveMetadata = Collections.unmodifiableMap(transitiveMetadata);
}
private void merge() {
// env priority is bigger than config
// the priority is : custom > env > config
Map<String, String> mergedMetadataResult = new HashMap<>();
mergedMetadataResult.putAll(configMetadata);
mergedMetadataResult.putAll(envMetadata);
mergedMetadataResult.putAll(customSPIMetadata);
// set location info as metadata
mergedMetadataResult.putAll(getLocationMetadata());
this.mergedStaticMetadata = Collections.unmodifiableMap(mergedMetadataResult);
Map<String, String> mergedTransitiveMetadataResult = new HashMap<>();
mergedTransitiveMetadataResult.putAll(configTransitiveMetadata);
mergedTransitiveMetadataResult.putAll(envTransitiveMetadata);
mergedTransitiveMetadataResult.putAll(customSPITransitiveMetadata);
this.mergedStaticTransitiveMetadata = Collections.unmodifiableMap(mergedTransitiveMetadataResult);
}
private void parseLocationMetadata() {
zone = System.getenv(ENV_METADATA_ZONE);
region = System.getenv(ENV_METADATA_REGION);
campus = System.getenv(ENV_METADATA_CAMPUS);
private void parseLocationMetadata(MetadataLocalProperties metadataLocalProperties,
InstanceMetadataProvider instanceMetadataProvider) {
// resolve zone info
if (instanceMetadataProvider != null) {
zone = instanceMetadataProvider.getZone();
}
if (StringUtils.isBlank(zone)) {
zone = System.getenv(ENV_METADATA_ZONE);
}
if (StringUtils.isBlank(zone)) {
zone = metadataLocalProperties.getContent().get(LOCATION_KEY_ZONE);
}
// resolve region info
if (instanceMetadataProvider != null) {
region = instanceMetadataProvider.getRegion();
}
if (StringUtils.isBlank(region)) {
region = System.getenv(ENV_METADATA_REGION);
}
if (StringUtils.isBlank(region)) {
region = metadataLocalProperties.getContent().get(LOCATION_KEY_REGION);
}
// resolve campus info
if (instanceMetadataProvider != null) {
campus = instanceMetadataProvider.getCampus();
}
if (StringUtils.isBlank(campus)) {
campus = System.getenv(ENV_METADATA_CAMPUS);
}
if (StringUtils.isBlank(campus)) {
campus = metadataLocalProperties.getContent().get(LOCATION_KEY_CAMPUS);
}
}
public Map<String, String> getAllEnvMetadata() {
@ -163,6 +239,14 @@ public class StaticMetadataManager {
return configTransitiveMetadata;
}
public Map<String, String> getAllCustomMetadata() {
return customSPIMetadata;
}
public Map<String, String> getCustomSPITransitiveMetadata() {
return customSPITransitiveMetadata;
}
public Map<String, String> getMergedStaticMetadata() {
return mergedStaticMetadata;
}
@ -204,6 +288,8 @@ public class StaticMetadataManager {
", envTransitiveMetadata=" + envTransitiveMetadata +
", configMetadata=" + configMetadata +
", configTransitiveMetadata=" + configTransitiveMetadata +
", customSPIMetadata=" + customSPIMetadata +
", customSPITransitiveMetadata=" + customSPITransitiveMetadata +
", mergedStaticMetadata=" + mergedStaticMetadata +
", mergedStaticTransitiveMetadata=" + mergedStaticTransitiveMetadata +
", zone='" + zone + '\'' +

@ -20,11 +20,13 @@ package com.tencent.cloud.common.metadata.config;
import com.tencent.cloud.common.metadata.StaticMetadataManager;
import com.tencent.cloud.common.metadata.filter.gateway.MetadataFirstScgFilter;
import com.tencent.cloud.common.spi.InstanceMetadataProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.Nullable;
/**
* Metadata auto configuration.
@ -44,8 +46,9 @@ public class MetadataAutoConfiguration {
}
@Bean
public StaticMetadataManager metadataManager(MetadataLocalProperties metadataLocalProperties) {
return new StaticMetadataManager(metadataLocalProperties);
public StaticMetadataManager metadataManager(MetadataLocalProperties metadataLocalProperties,
@Nullable InstanceMetadataProvider instanceMetadataProvider) {
return new StaticMetadataManager(metadataLocalProperties, instanceMetadataProvider);
}
/**

@ -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<String, Object> metadata() {
Map<String, Object> 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;
}
}

@ -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);
}
}

@ -16,9 +16,11 @@
*
*/
package com.tencent.cloud.polaris.context.spi;
package com.tencent.cloud.common.spi;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
/**
*
@ -30,26 +32,41 @@ public interface InstanceMetadataProvider {
/**
* @return the metadata of instance.
*/
Map<String, String> getMetadata();
default Map<String, String> getMetadata() {
return Collections.emptyMap();
}
/**
* @return the keys of transitive metadata.
*/
default Set<String> getTransitiveMetadataKeys() {
return Collections.emptySet();
}
/**
* The region of current instance.
*
* @return the region info.
*/
String getRegion();
default String getRegion() {
return "";
}
/**
* The zone of current instance.
*
* @return the zone info.
*/
String getZone();
default String getZone() {
return "";
}
/**
* The campus/datacenter of current instance.
*
* @return the campus or datacenter info.
*/
String getCampus();
default String getCampus() {
return "";
}
}

@ -30,7 +30,7 @@ import org.springframework.util.StringUtils;
/**
* Utils for Jackson.
*
* @author Haotian Zhang
* @author Haotian Zhang, cheese8
*/
public final class JacksonUtils {
@ -80,8 +80,7 @@ public final class JacksonUtils {
}
catch (JsonProcessingException e) {
LOG.error(
"Json to map failed. check if the format of the json string[{}] is correct.",
jsonStr, e);
"Json to map failed. check if the format of the json string[{}] is correct.", jsonStr, e);
throw new RuntimeException("Json to map failed.", e);
}
}

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

@ -0,0 +1,186 @@
/*
* 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;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.tencent.cloud.common.metadata.config.MetadataLocalProperties;
import com.tencent.cloud.common.spi.InstanceMetadataProvider;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.util.CollectionUtils;
import static org.mockito.Mockito.when;
/**
* test for {@link StaticMetadataManager}
*@author lepdou 2022-06-27
*/
@RunWith(MockitoJUnitRunner.class)
public class StaticMetadataManagerTest {
@Mock
private MetadataLocalProperties metadataLocalProperties;
@Test
public void testParseConfigMetadata() {
Map<String, String> content = new HashMap<>();
content.put("k1", "v1");
content.put("k2", "v22");
content.put("zone", "zone1");
content.put("region", "region1");
when(metadataLocalProperties.getContent()).thenReturn(content);
when(metadataLocalProperties.getTransitive()).thenReturn(Collections.singletonList("k1"));
StaticMetadataManager metadataManager = new StaticMetadataManager(metadataLocalProperties, null);
Map<String, String> metadata = metadataManager.getAllConfigMetadata();
Assert.assertEquals(4, metadata.size());
Assert.assertEquals("v1", metadata.get("k1"));
Assert.assertEquals("v22", metadata.get("k2"));
Map<String, String> transitiveMetadata = metadataManager.getConfigTransitiveMetadata();
Assert.assertEquals(1, transitiveMetadata.size());
Assert.assertEquals("v1", transitiveMetadata.get("k1"));
Assert.assertEquals("zone1", metadataManager.getZone());
Assert.assertEquals("region1", metadataManager.getRegion());
Map<String, String> locationInfo = metadataManager.getLocationMetadata();
Assert.assertEquals("zone1", locationInfo.get("zone"));
Assert.assertEquals("region1", locationInfo.get("region"));
}
@Test
public void testCustomSPIMetadata() {
Map<String, String> content = new HashMap<>();
content.put("k1", "v1");
content.put("k2", "v2");
when(metadataLocalProperties.getContent()).thenReturn(content);
when(metadataLocalProperties.getTransitive()).thenReturn(Collections.singletonList("k1"));
StaticMetadataManager metadataManager = new StaticMetadataManager(metadataLocalProperties,
new MockedMetadataProvider());
Map<String, String> metadata = metadataManager.getAllCustomMetadata();
Assert.assertEquals(3, metadata.size());
Assert.assertEquals("v1", metadata.get("k1"));
Assert.assertEquals("v22", metadata.get("k2"));
Assert.assertEquals("v33", metadata.get("k3"));
Map<String, String> transitiveMetadata = metadataManager.getCustomSPITransitiveMetadata();
Assert.assertEquals(1, transitiveMetadata.size());
Assert.assertEquals("v22", metadata.get("k2"));
Assert.assertEquals("zone2", metadataManager.getZone());
Assert.assertEquals("region1", metadataManager.getRegion());
Map<String, String> locationInfo = metadataManager.getLocationMetadata();
Assert.assertEquals("zone2", locationInfo.get("zone"));
Assert.assertEquals("region1", locationInfo.get("region"));
}
@Test
public void testMergedMetadata() {
Map<String, String> content = new HashMap<>();
content.put("k1", "v1");
content.put("k2", "v2");
content.put("zone", "zone1");
content.put("region", "region1");
content.put("campus", "campus1");
when(metadataLocalProperties.getContent()).thenReturn(content);
when(metadataLocalProperties.getTransitive()).thenReturn(Collections.singletonList("k1"));
StaticMetadataManager metadataManager = new StaticMetadataManager(metadataLocalProperties,
new MockedMetadataProvider());
Map<String, String> metadata = metadataManager.getMergedStaticMetadata();
Assert.assertEquals(6, metadata.size());
Assert.assertEquals("v1", metadata.get("k1"));
Assert.assertEquals("v22", metadata.get("k2"));
Assert.assertEquals("v33", metadata.get("k3"));
Assert.assertEquals("zone2", metadata.get("zone"));
Assert.assertEquals("region1", metadata.get("region"));
Assert.assertEquals("campus1", metadata.get("campus"));
Map<String, String> transitiveMetadata = metadataManager.getMergedStaticTransitiveMetadata();
Assert.assertEquals(2, transitiveMetadata.size());
Assert.assertEquals("v1", metadata.get("k1"));
Assert.assertEquals("v22", metadata.get("k2"));
Assert.assertEquals("zone2", metadataManager.getZone());
Assert.assertEquals("region1", metadataManager.getRegion());
Assert.assertTrue(CollectionUtils.isEmpty(metadataManager.getAllEnvMetadata()));
Assert.assertTrue(CollectionUtils.isEmpty(metadataManager.getEnvTransitiveMetadata()));
Map<String, String> locationInfo = metadataManager.getLocationMetadata();
Assert.assertEquals("zone2", locationInfo.get("zone"));
Assert.assertEquals("region1", locationInfo.get("region"));
Assert.assertEquals("campus1", locationInfo.get("campus"));
}
static class MockedMetadataProvider implements InstanceMetadataProvider {
@Override
public Map<String, String> getMetadata() {
Map<String, String> metadata = new HashMap<>();
metadata.put("k1", "v1");
metadata.put("k2", "v22");
metadata.put("k3", "v33");
return metadata;
}
@Override
public Set<String> getTransitiveMetadataKeys() {
Set<String> transitiveKeys = new HashSet<>();
transitiveKeys.add("k2");
return transitiveKeys;
}
@Override
public String getRegion() {
return "region1";
}
@Override
public String getZone() {
return "zone2";
}
@Override
public String getCampus() {
return null;
}
}
}

@ -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<String, String> 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<String, Object> metaMap = polarisMetadataEndpoint.metadata();
assertThat(envMetadata).isEqualTo(metaMap.get("Env"));
}
}

@ -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<String, String> 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.");
}
}

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

@ -24,6 +24,41 @@
<groupId>com.tencent.cloud</groupId>
<artifactId>spring-cloud-starter-tencent-polaris-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

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

@ -21,7 +21,7 @@ package com.tencent.cloud.polaris.discovery.service.callee;
import java.util.HashMap;
import java.util.Map;
import com.tencent.cloud.polaris.context.spi.InstanceMetadataProvider;
import com.tencent.cloud.common.spi.InstanceMetadataProvider;
import org.springframework.stereotype.Component;
@ -39,18 +39,8 @@ public class CustomMetadata implements InstanceMetadataProvider {
return metadata;
}
@Override
public String getRegion() {
return "shanghai";
}
@Override
public String getZone() {
return null;
}
@Override
public String getCampus() {
return null;
return "shanghai-zone-1";
}
}

@ -11,6 +11,10 @@ spring:
discovery:
enabled: true
register: true
tencent:
metadata:
content:
region: shanghai
# consul:
# port: 8500
# host: 127.0.0.1

@ -5,6 +5,10 @@ spring:
application:
name: DiscoveryCallerService
cloud:
tencent:
metadata:
content:
region: shanghai
polaris:
address: grpc://183.47.111.80:8091
namespace: default
@ -32,3 +36,9 @@ spring:
# client:
# serviceUrl:
# defaultZone: http://127.0.0.1:7654/eureka/
management:
endpoints:
web:
exposure:
include:
- polaris-discovery

@ -19,6 +19,7 @@ package com.tencent.cloud.polaris.gateway.example.callee;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import com.tencent.cloud.common.constant.MetadataConstant;
import org.slf4j.Logger;
@ -63,8 +64,8 @@ public class GatewayCalleeController {
@RequestMapping("/echo")
public String echoHeader(@RequestHeader(MetadataConstant.HeaderName.CUSTOM_METADATA) String metadataStr)
throws UnsupportedEncodingException {
LOG.info(URLDecoder.decode(metadataStr, "UTF-8"));
return URLDecoder.decode(metadataStr, "UTF-8");
LOG.info(URLDecoder.decode(metadataStr, StandardCharsets.UTF_8.name()));
return URLDecoder.decode(metadataStr, StandardCharsets.UTF_8.name());
}
}

@ -28,6 +28,10 @@
<artifactId>spring-cloud-starter-tencent-polaris-ratelimit</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
<build>

@ -12,3 +12,10 @@ spring:
enabled: true
rejectRequestTipsFilePath: reject-tips.html
maxQueuingTime: 500
management:
endpoints:
web:
exposure:
include:
- polaris-ratelimit

@ -58,6 +58,7 @@ public class CustomRouterLabelResolver implements RouterLabelResolver {
return labels;
}
@Override
public int getOrder() {
return 0;

@ -22,6 +22,7 @@ import java.util.List;
import com.tencent.cloud.common.constant.ContextConstant;
import com.tencent.cloud.common.util.AddressUtils;
import com.tencent.cloud.polaris.context.config.PolarisContextProperties;
import com.tencent.polaris.factory.config.ConfigurationImpl;
import org.apache.commons.lang.StringUtils;

@ -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.context;
import com.tencent.cloud.common.metadata.StaticMetadataManager;
import com.tencent.polaris.api.plugin.common.ValueContext;
import com.tencent.polaris.api.plugin.route.LocationLevel;
import com.tencent.polaris.client.api.SDKContext;
import org.apache.commons.lang.StringUtils;
/**
* After all configurations are loaded, post-initialize SDKContext.
*@author lepdou 2022-06-28
*/
public class PostInitPolarisSDKContext {
public PostInitPolarisSDKContext(SDKContext sdkContext, StaticMetadataManager staticMetadataManager) {
// set instance's location info
String region = staticMetadataManager.getRegion();
String zone = staticMetadataManager.getZone();
String campus = staticMetadataManager.getCampus();
ValueContext valueContext = sdkContext.getValueContext();
if (StringUtils.isNotBlank(region)) {
valueContext.setValue(LocationLevel.region.name(), region);
}
if (StringUtils.isNotBlank(zone)) {
valueContext.setValue(LocationLevel.zone.name(), zone);
}
if (StringUtils.isNotBlank(campus)) {
valueContext.setValue(LocationLevel.campus.name(), campus);
}
}
}

@ -16,17 +16,14 @@
*
*/
package com.tencent.cloud.polaris.context;
package com.tencent.cloud.polaris.context.config;
import com.tencent.cloud.common.metadata.StaticMetadataManager;
import com.tencent.cloud.common.metadata.config.MetadataAutoConfiguration;
import com.tencent.cloud.polaris.context.ConditionalOnPolarisEnabled;
import com.tencent.cloud.polaris.context.ModifyAddress;
import com.tencent.cloud.polaris.context.ServiceRuleManager;
import com.tencent.polaris.api.exception.PolarisException;
import com.tencent.polaris.api.plugin.common.ValueContext;
import com.tencent.polaris.api.plugin.route.LocationLevel;
import com.tencent.polaris.client.api.SDKContext;
import org.apache.commons.lang.StringUtils;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
@ -38,32 +35,13 @@ import org.springframework.context.annotation.Bean;
*/
@ConditionalOnPolarisEnabled
@EnableConfigurationProperties({PolarisContextProperties.class})
@ImportAutoConfiguration(MetadataAutoConfiguration.class)
public class PolarisContextAutoConfiguration {
@Bean(name = "polarisContext", initMethod = "init", destroyMethod = "destroy")
@ConditionalOnMissingBean
public SDKContext polarisContext(PolarisContextProperties properties, StaticMetadataManager staticMetadataManager)
public SDKContext polarisContext(PolarisContextProperties properties)
throws PolarisException {
SDKContext sdkContext = SDKContext.initContextByConfig(properties.configuration());
// init current instance location info from environment
ValueContext valueContext = sdkContext.getValueContext();
String region = staticMetadataManager.getRegion();
String zone = staticMetadataManager.getZone();
String campus = staticMetadataManager.getCampus();
if (StringUtils.isNotBlank(region)) {
valueContext.setValue(LocationLevel.region.name(), region);
}
if (StringUtils.isNotBlank(zone)) {
valueContext.setValue(LocationLevel.zone.name(), zone);
}
if (StringUtils.isNotBlank(campus)) {
valueContext.setValue(LocationLevel.campus.name(), campus);
}
return sdkContext;
return SDKContext.initContextByConfig(properties.configuration());
}
@Bean
@ -73,6 +51,7 @@ public class PolarisContextAutoConfiguration {
}
@Bean
@ConditionalOnMissingBean
public ServiceRuleManager serviceRuleManager(SDKContext sdkContext) {
return new ServiceRuleManager(sdkContext);
}

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

Loading…
Cancel
Save