Merge branch '2020.0' into 0701

pull/366/head
cheese8 3 years ago committed by GitHub
commit f6530abbf2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -0,0 +1,37 @@
# This workflow will build a Java project with Maven
# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven
name: Codecov
on:
push:
branches:
- main
- 2021.0
- 2020.0
- greenwich
pull_request:
branches:
- main
- 2021.0
- 2020.0
- greenwich
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout codes
uses: actions/checkout@v3
- name: Set up JDK 8
uses: actions/setup-java@v3
with:
distribution: 'temurin'
java-version: 8
- name: Test with Maven
run: mvn -B test --file pom.xml
- name: Upload coverage to Codecov
uses: codecov/codecov-action@v3
with:
file: ${{ github.workspace }}/target/site/jacoco/jacoco.xml

@ -5,24 +5,41 @@ name: Test with Junit
on:
push:
branches: [ 2020.0 ]
branches:
- main
- 2021.0
- 2020.0
- greenwich
pull_request:
branches: [ 2020.0 ]
branches:
- main
- 2021.0
- 2020.0
- greenwich
jobs:
build:
strategy:
matrix:
java: [ 8, 11, 17 ]
os: [ 'windows-latest', 'ubuntu-latest' ]
runs-on: ubuntu-latest
runs-on: ${{ matrix.os }}
steps:
- name: Checkout codes
uses: actions/checkout@v2
- name: Set up JDK 8
uses: actions/setup-java@v2
uses: actions/checkout@v3
- name: Set up JDK ${{ matrix.java }}
uses: actions/setup-java@v3
with:
java-version: '8'
distribution: 'adopt'
# - name: Build with Maven
# run: mvn -B package --file pom.xml
distribution: 'temurin'
java-version: ${{ matrix.java }}
- name: Cache local Maven repository
uses: actions/cache@v3
with:
path: ~/.m2/repository
key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
restore-keys: |
${{ runner.os }}-maven-
- name: Test with Maven
run: mvn -B test --file pom.xml

@ -8,4 +8,20 @@
- [feat:support reading configuration from application.yml or application.properties.](https://github.com/Tencent/spring-cloud-tencent/pull/261)
- [change the way from escape to encode in 2020.0](https://github.com/Tencent/spring-cloud-tencent/pull/257)
- [fix:fix ClassNotFoundException while not importing openfeign when using circuit-breaker module.](https://github.com/Tencent/spring-cloud-tencent/pull/270)
- [fix:solve the chaos code problem on rejectTips](https://github.com/Tencent/spring-cloud-tencent/pull/283)
- [fix:solve ratelimit-callee-service UnknownHostException.](https://github.com/Tencent/spring-cloud-tencent/pull/291)
- [Update GitHub Actions workflow](https://github.com/Tencent/spring-cloud-tencent/pull/295)
- [Feature:add restTemplate Report Polaris](https://github.com/Tencent/spring-cloud-tencent/pull/300)
- [Fix the current limiting effect is that other requests cannot be processed when queuing at a constant speed](https://github.com/Tencent/spring-cloud-tencent/pull/317)
- [Fix config file format misspell](https://github.com/Tencent/spring-cloud-tencent/pull/320)
- [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/365)

@ -1,4 +1,4 @@
# Spring Cloud Tencent
<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,5 @@
# Spring Cloud Tencent
<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)

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.

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

@ -95,7 +95,7 @@
<spring.framework.version>5.3.21</spring.framework.version>
<!-- Maven Plugin Versions -->
<jacoco.version>0.8.3</jacoco.version>
<jacoco.version>0.8.8</jacoco.version>
<maven-source-plugin.version>3.2.0</maven-source-plugin.version>
<flatten-maven-plugin.version>1.2.7</flatten-maven-plugin.version>
<maven-gpg-plugin.version>3.0.1</maven-gpg-plugin.version>

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

@ -0,0 +1,54 @@
/*
* 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.metadata.core;
import java.util.Map;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.server.MockServerWebExchange;
/**
* Test for {@link CustomTransitiveMetadataResolver}.
*
* @author quan
*/
public class CustomTransitiveMetadataResolverTest {
@Test
public void test() {
MockServerHttpRequest.BaseBuilder<?> builder = MockServerHttpRequest.get("");
builder.header("X-SCT-Metadata-Transitive-a", "test");
MockServerWebExchange exchange = MockServerWebExchange.from(builder);
Map<String, String> resolve = CustomTransitiveMetadataResolver.resolve(exchange);
Assertions.assertThat(resolve.size()).isEqualTo(1);
Assertions.assertThat(resolve.get("a")).isEqualTo("test");
}
@Test
public void testServlet() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("X-SCT-Metadata-Transitive-a", "test");
Map<String, String> resolve = CustomTransitiveMetadataResolver.resolve(request);
Assertions.assertThat(resolve.size()).isEqualTo(1);
Assertions.assertThat(resolve.get("a")).isEqualTo("test");
}
}

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

@ -0,0 +1,83 @@
/*
* 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.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 org.assertj.core.api.Assertions;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.context.ApplicationContext;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.mock.web.server.MockServerWebExchange;
import org.springframework.test.context.junit4.SpringRunner;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
/**
* Test for {@link EncodeTransferMedataScgFilter}.
*
* @author quan
*/
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = RANDOM_PORT,
classes = EncodeTransferMedataScgFilterTest.TestApplication.class,
properties = {"spring.config.location = classpath:application-test.yml", "spring.main.web-application-type = reactive"})
public class EncodeTransferMedataScgFilterTest {
@Autowired
private ApplicationContext applicationContext;
@Mock
private GatewayFilterChain chain;
@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);
// 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);
Assertions.assertThat(transitiveMap.get("b")).isEqualTo("2");
}
@SpringBootApplication
protected static class TestApplication {
}
}

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

@ -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.config;
import com.tencent.cloud.common.constant.ContextConstant;
import com.tencent.cloud.polaris.context.ConditionalOnPolarisEnabled;

@ -15,10 +15,10 @@
* specific language governing permissions and limitations under the License.
*/
package com.tencent.cloud.polaris.circuitbreaker;
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;
@ -40,8 +40,7 @@ import static org.springframework.core.Ordered.HIGHEST_PRECEDENCE;
*
* @author Haotian Zhang
*/
@ConditionalOnProperty(value = "spring.cloud.polaris.circuitbreaker.enabled", havingValue = "true",
matchIfMissing = true)
@ConditionalOnProperty(value = "spring.cloud.polaris.circuitbreaker.enabled", havingValue = "true", matchIfMissing = true)
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(name = "org.springframework.cloud.openfeign.FeignAutoConfiguration")
@AutoConfigureAfter(PolarisContextAutoConfiguration.class)

@ -0,0 +1,59 @@
/*
* 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.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.config.PolarisContextAutoConfiguration;
import com.tencent.polaris.api.core.ConsumerAPI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
/**
* Auto configuration PolarisRestTemplateAutoConfiguration .
*
* @author wh 2022/6/21
*/
@ConditionalOnProperty(value = "spring.cloud.polaris.circuitbreaker.enabled",
havingValue = "true", matchIfMissing = true)
@Configuration(proxyBeanMethods = false)
@AutoConfigureAfter(PolarisContextAutoConfiguration.class)
public class PolarisRestTemplateAutoConfiguration {
@Bean
@ConditionalOnBean(RestTemplate.class)
public PolarisRestTemplateResponseErrorHandler polarisRestTemplateResponseErrorHandler(
ConsumerAPI consumerAPI, @Autowired(required = false) PolarisResponseErrorHandler polarisResponseErrorHandler) {
return new PolarisRestTemplateResponseErrorHandler(consumerAPI, polarisResponseErrorHandler);
}
@Bean
@ConditionalOnBean(RestTemplate.class)
public PolarisRestTemplateModifier polarisRestTemplateBeanPostProcessor(
PolarisRestTemplateResponseErrorHandler restTemplateResponseErrorHandler) {
return new PolarisRestTemplateModifier(restTemplateResponseErrorHandler);
}
}

@ -0,0 +1,29 @@
/*
* 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.resttemplate;
import org.springframework.web.client.ResponseErrorHandler;
/**
* Polaris Response Error Handler Definition Of {@link ResponseErrorHandler}.
*
* @author wh 2022/6/21
*/
public interface PolarisResponseErrorHandler extends ResponseErrorHandler {
}

@ -0,0 +1,65 @@
/*
* 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.resttemplate;
import java.util.Map;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;
/**
* Auto configuration RestTemplate, Find the RestTemplate bean annotated with {@link LoadBalanced},
* then replace {@link org.springframework.web.client.ResponseErrorHandler} with {@link PolarisRestTemplateResponseErrorHandler} .
*
* @author wh 2022/6/21
*/
public class PolarisRestTemplateModifier implements ApplicationContextAware, SmartInitializingSingleton {
private ApplicationContext applicationContext;
private final PolarisRestTemplateResponseErrorHandler polarisRestTemplateResponseErrorHandler;
public PolarisRestTemplateModifier(PolarisRestTemplateResponseErrorHandler polarisRestTemplateResponseErrorHandler) {
this.polarisRestTemplateResponseErrorHandler = polarisRestTemplateResponseErrorHandler;
}
@Override
public void afterSingletonsInstantiated() {
Map<String, Object> beans = this.applicationContext.getBeansWithAnnotation(LoadBalanced.class);
if (!ObjectUtils.isEmpty(beans)) {
beans.forEach(this::initRestTemplate);
}
}
private void initRestTemplate(String beanName, Object bean) {
if (bean instanceof RestTemplate) {
RestTemplate restTemplate = (RestTemplate) bean;
restTemplate.setErrorHandler(polarisRestTemplateResponseErrorHandler);
}
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}

@ -0,0 +1,115 @@
/*
* 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.resttemplate;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.util.Objects;
import com.tencent.cloud.common.metadata.MetadataContext;
import com.tencent.cloud.common.util.ReflectionUtils;
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 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;
/**
* 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 FIELD_NAME = "connection";
private final ConsumerAPI consumerAPI;
private final PolarisResponseErrorHandler polarisResponseErrorHandler;
public PolarisRestTemplateResponseErrorHandler(ConsumerAPI consumerAPI, PolarisResponseErrorHandler polarisResponseErrorHandler) {
this.consumerAPI = consumerAPI;
this.polarisResponseErrorHandler = polarisResponseErrorHandler;
}
@Override
public boolean hasError(@NonNull ClientHttpResponse response) {
return true;
}
@Override
public void handleError(@NonNull ClientHttpResponse response) throws IOException {
if (Objects.nonNull(polarisResponseErrorHandler)) {
if (polarisResponseErrorHandler.hasError(response)) {
polarisResponseErrorHandler.handleError(response);
}
}
}
@Override
public void handleError(@NonNull URI url, @NonNull HttpMethod method, @NonNull ClientHttpResponse response) throws IOException {
ServiceCallResult resultRequest = createServiceCallResult(url);
try {
HttpURLConnection connection = (HttpURLConnection) ReflectionUtils.getFieldValue(response, FIELD_NAME);
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 (Exception e) {
LOG.error("Will report response of {} url {}", response, url, e);
throw e;
}
finally {
consumerAPI.updateServiceCallResult(resultRequest);
}
}
private ServiceCallResult createServiceCallResult(URI uri) {
ServiceCallResult resultRequest = new ServiceCallResult();
String serviceName = uri.getHost();
resultRequest.setService(serviceName);
resultRequest.setNamespace(MetadataContext.LOCAL_NAMESPACE);
resultRequest.setMethod(uri.getPath());
resultRequest.setRetStatus(RetStatus.RetSuccess);
String sourceNamespace = MetadataContext.LOCAL_NAMESPACE;
String sourceService = MetadataContext.LOCAL_SERVICE;
if (StringUtils.isNotBlank(sourceNamespace) && StringUtils.isNotBlank(sourceService)) {
resultRequest.setCallerService(new ServiceKey(sourceNamespace, sourceService));
}
return resultRequest;
}
}

@ -1,4 +1,6 @@
org.springframework.cloud.bootstrap.BootstrapConfiguration=\
com.tencent.cloud.polaris.circuitbreaker.PolarisCircuitBreakerBootstrapConfiguration
com.tencent.cloud.polaris.circuitbreaker.config.PolarisCircuitBreakerBootstrapConfiguration
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.tencent.cloud.polaris.circuitbreaker.PolarisFeignClientAutoConfiguration
com.tencent.cloud.polaris.circuitbreaker.config.PolarisFeignClientAutoConfiguration,\
com.tencent.cloud.polaris.circuitbreaker.config.PolarisRestTemplateAutoConfiguration

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

@ -17,8 +17,9 @@
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();
}
}
}

@ -0,0 +1,69 @@
/*
* 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.resttemplate;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import com.tencent.polaris.api.core.ConsumerAPI;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpMethod;
import org.springframework.test.context.junit4.SpringRunner;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Test For {@link PolarisRestTemplateResponseErrorHandler}.
*
* @author wh 2022/6/22
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = PolarisRestTemplateResponseErrorHandlerTest.TestApplication.class,
properties = {"spring.cloud.polaris.namespace=Test", "spring.cloud.polaris.service=TestApp"})
public class PolarisRestTemplateResponseErrorHandlerTest {
@Test
public void handleError() throws Exception {
ConsumerAPI consumerAPI = mock(ConsumerAPI.class);
PolarisRestTemplateResponseErrorHandler polarisRestTemplateResponseErrorHandler = new PolarisRestTemplateResponseErrorHandler(consumerAPI, null);
URI uri = mock(URI.class);
when(uri.getPath()).thenReturn("/test");
when(uri.getHost()).thenReturn("host");
HttpURLConnection httpURLConnection = mock(HttpURLConnection.class);
URL url = mock(URL.class);
when(httpURLConnection.getURL()).thenReturn(url);
when(url.getHost()).thenReturn("127.0.0.1");
when(url.getPort()).thenReturn(8080);
when(httpURLConnection.getResponseCode()).thenReturn(200);
SimpleClientHttpResponseTest clientHttpResponse = new SimpleClientHttpResponseTest(httpURLConnection);
polarisRestTemplateResponseErrorHandler.handleError(uri, HttpMethod.GET, clientHttpResponse);
when(consumerAPI.unWatchService(null)).thenReturn(true);
}
@SpringBootApplication
protected static class TestApplication {
}
}

@ -0,0 +1,106 @@
/*
* 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.resttemplate;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import org.springframework.http.HttpHeaders;
import org.springframework.http.client.AbstractClientHttpResponse;
import org.springframework.lang.Nullable;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
/**
* Mock Test for {@link AbstractClientHttpResponse}.
*
* @author wh 2022/6/22
*/
public class SimpleClientHttpResponseTest extends AbstractClientHttpResponse {
private final HttpURLConnection connection;
@Nullable
private HttpHeaders headers;
@Nullable
private InputStream responseStream;
SimpleClientHttpResponseTest(HttpURLConnection connection) {
this.connection = connection;
}
@Override
public int getRawStatusCode() throws IOException {
return this.connection.getResponseCode();
}
@Override
public String getStatusText() throws IOException {
String result = this.connection.getResponseMessage();
return (result != null) ? result : "";
}
@Override
public HttpHeaders getHeaders() {
if (this.headers == null) {
this.headers = new HttpHeaders();
// Header field 0 is the status line for most HttpURLConnections, but not on GAE
String name = this.connection.getHeaderFieldKey(0);
if (StringUtils.hasLength(name)) {
this.headers.add(name, this.connection.getHeaderField(0));
}
int i = 1;
while (true) {
name = this.connection.getHeaderFieldKey(i);
if (!StringUtils.hasLength(name)) {
break;
}
this.headers.add(name, this.connection.getHeaderField(i));
i++;
}
}
return this.headers;
}
@Override
public InputStream getBody() throws IOException {
InputStream errorStream = this.connection.getErrorStream();
this.responseStream = (errorStream != null ? errorStream : this.connection.getInputStream());
return this.responseStream;
}
@Override
public void close() {
try {
if (this.responseStream == null) {
getBody();
}
StreamUtils.drain(this.responseStream);
this.responseStream.close();
}
catch (Exception ex) {
// ignore
}
}
}

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

@ -28,7 +28,7 @@ public enum ConfigFileFormat {
/**
* property format.
*/
PROPERTY(".property"),
PROPERTY(".properties"),
/**
* yaml format.
*/
@ -48,7 +48,7 @@ public enum ConfigFileFormat {
/**
* text format.
*/
TEXT(".text"),
TEXT(".txt"),
/**
* html format.
*/

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

@ -66,7 +66,7 @@ public class ConfigChangeListenerTest {
Sets.newHashSet("timeout"));
applicationEventPublisher.publishEvent(event);
Thread.sleep(200);
//after change
Assert.assertEquals(2, testConfig.getChangeCnt());
Assert.assertEquals(2000, testConfig.getTimeout());

@ -61,7 +61,7 @@ public class PolarisDiscoveryHandler {
GetHealthyInstancesRequest getHealthyInstancesRequest = new GetHealthyInstancesRequest();
getHealthyInstancesRequest.setNamespace(namespace);
getHealthyInstancesRequest.setService(service);
return polarisConsumer.getHealthyInstancesInstance(getHealthyInstancesRequest);
return polarisConsumer.getHealthyInstances(getHealthyInstancesRequest);
}
/**

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

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

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

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

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

@ -19,6 +19,7 @@
package com.tencent.cloud.polaris.ratelimit.filter;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
@ -55,7 +56,7 @@ import static com.tencent.cloud.polaris.ratelimit.constant.RateLimitConstant.LAB
/**
* Reactive filter to check quota.
*
* @author Haotian Zhang, lepdou
* @author Haotian Zhang, lepdou, cheese8, kaiy
*/
public class QuotaCheckReactiveFilter implements WebFilter, Ordered {
@ -106,14 +107,14 @@ public class QuotaCheckReactiveFilter implements WebFilter, Ordered {
if (quotaResponse.getCode() == QuotaResultCode.QuotaResultLimited) {
ServerHttpResponse response = exchange.getResponse();
response.setRawStatusCode(polarisRateLimitProperties.getRejectHttpCode());
response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
response.getHeaders().setContentType(MediaType.TEXT_HTML);
DataBuffer dataBuffer = response.bufferFactory().allocateBuffer()
.write(rejectTips.getBytes(StandardCharsets.UTF_8));
return response.writeWith(Mono.just(dataBuffer));
}
// Unirate
if (quotaResponse.getCode() == QuotaResultCode.QuotaResultOk && quotaResponse.getWaitMs() > 0) {
Thread.sleep(quotaResponse.getWaitMs());
return Mono.delay(Duration.ofMillis(quotaResponse.getWaitMs())).flatMap(e -> chain.filter(exchange));
}
}
catch (Throwable t) {

@ -53,7 +53,7 @@ import static com.tencent.cloud.polaris.ratelimit.constant.RateLimitConstant.LAB
/**
* Servlet filter to check quota.
*
* @author Haotian Zhang, lepdou
* @author Haotian Zhang, lepdou, cheese8
*/
@Order(RateLimitConstant.FILTER_ORDER)
public class QuotaCheckServletFilter extends OncePerRequestFilter {
@ -99,6 +99,7 @@ public class QuotaCheckServletFilter extends OncePerRequestFilter {
if (quotaResponse.getCode() == QuotaResultCode.QuotaResultLimited) {
response.setStatus(polarisRateLimitProperties.getRejectHttpCode());
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write(rejectTips);
return;
}

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

@ -22,6 +22,7 @@ import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import com.tencent.cloud.common.metadata.MetadataContext;
import com.tencent.cloud.common.util.ApplicationContextAwareUtils;
@ -65,7 +66,7 @@ import static org.mockito.Mockito.when;
/**
* Test for {@link QuotaCheckReactiveFilter}.
*
* @author Haotian Zhang
* @author Haotian Zhang, cheese8, kaiy
*/
@RunWith(MockitoJUnitRunner.class)
@SpringBootTest(classes = QuotaCheckReactiveFilterTest.TestApplication.class, properties = {
@ -118,7 +119,7 @@ public class QuotaCheckReactiveFilterTest {
});
PolarisRateLimitProperties polarisRateLimitProperties = new PolarisRateLimitProperties();
polarisRateLimitProperties.setRejectRequestTips("RejectRequestTips");
polarisRateLimitProperties.setRejectRequestTips("RejectRequestTips提示消息");
polarisRateLimitProperties.setRejectHttpCode(419);
RateLimitRuleLabelResolver rateLimitRuleLabelResolver = mock(RateLimitRuleLabelResolver.class);
@ -138,7 +139,7 @@ public class QuotaCheckReactiveFilterTest {
try {
Field rejectTips = QuotaCheckReactiveFilter.class.getDeclaredField("rejectTips");
rejectTips.setAccessible(true);
assertThat(rejectTips.get(quotaCheckReactiveFilter)).isEqualTo("RejectRequestTips");
assertThat(rejectTips.get(quotaCheckReactiveFilter)).isEqualTo("RejectRequestTips提示消息");
}
catch (NoSuchFieldException | IllegalAccessException e) {
fail("Exception encountered.", e);
@ -201,7 +202,14 @@ public class QuotaCheckReactiveFilterTest {
// Unirate waiting 1000ms
MetadataContext.LOCAL_SERVICE = "TestApp2";
long startTimestamp = System.currentTimeMillis();
quotaCheckReactiveFilter.filter(exchange, webFilterChain);
CountDownLatch countDownLatch = new CountDownLatch(1);
quotaCheckReactiveFilter.filter(exchange, webFilterChain).subscribe(e -> { }, t -> { }, countDownLatch::countDown);
try {
countDownLatch.await();
}
catch (InterruptedException e) {
fail("Exception encountered.", e);
}
assertThat(System.currentTimeMillis() - startTimestamp).isGreaterThanOrEqualTo(1000L);
// Rate limited

@ -65,7 +65,7 @@ import static org.mockito.Mockito.when;
/**
* Test for {@link QuotaCheckServletFilter}.
*
* @author Haotian Zhang
* @author Haotian Zhang, cheese8
*/
@RunWith(MockitoJUnitRunner.class)
@SpringBootTest(classes = QuotaCheckServletFilterTest.TestApplication.class, properties = {
@ -77,6 +77,8 @@ public class QuotaCheckServletFilterTest {
private QuotaCheckServletFilter quotaCheckServletFilter;
private QuotaCheckServletFilter quotaCheckWithHtmlRejectTipsServletFilter;
private static MockedStatic<ApplicationContextAwareUtils> mockedApplicationContextAwareUtils;
private static MockedStatic<ExpressionLabelUtils> expressionLabelUtilsMockedStatic;
@BeforeClass
@ -87,7 +89,6 @@ public class QuotaCheckServletFilterTest {
mockedApplicationContextAwareUtils = Mockito.mockStatic(ApplicationContextAwareUtils.class);
mockedApplicationContextAwareUtils.when(() -> ApplicationContextAwareUtils.getProperties(anyString()))
.thenReturn("unit-test");
}
@AfterClass
@ -118,13 +119,18 @@ public class QuotaCheckServletFilterTest {
});
PolarisRateLimitProperties polarisRateLimitProperties = new PolarisRateLimitProperties();
polarisRateLimitProperties.setRejectRequestTips("RejectRequestTips");
polarisRateLimitProperties.setRejectRequestTips("RejectRequestTips提示消息");
polarisRateLimitProperties.setRejectHttpCode(419);
PolarisRateLimitProperties polarisRateLimitWithHtmlRejectTipsProperties = new PolarisRateLimitProperties();
polarisRateLimitWithHtmlRejectTipsProperties.setRejectRequestTips("<h1>RejectRequestTips提示消息</h1>");
polarisRateLimitWithHtmlRejectTipsProperties.setRejectHttpCode(419);
RateLimitRuleLabelResolver rateLimitRuleLabelResolver = mock(RateLimitRuleLabelResolver.class);
when(rateLimitRuleLabelResolver.getExpressionLabelKeys(anyString(), anyString())).thenReturn(Collections.EMPTY_SET);
this.quotaCheckServletFilter = new QuotaCheckServletFilter(limitAPI, labelResolver, polarisRateLimitProperties, rateLimitRuleLabelResolver);
this.quotaCheckWithHtmlRejectTipsServletFilter = new QuotaCheckServletFilter(limitAPI, labelResolver, polarisRateLimitWithHtmlRejectTipsProperties, rateLimitRuleLabelResolver);
}
@Test
@ -133,7 +139,16 @@ public class QuotaCheckServletFilterTest {
try {
Field rejectTips = QuotaCheckServletFilter.class.getDeclaredField("rejectTips");
rejectTips.setAccessible(true);
assertThat(rejectTips.get(quotaCheckServletFilter)).isEqualTo("RejectRequestTips");
assertThat(rejectTips.get(quotaCheckServletFilter)).isEqualTo("RejectRequestTips提示消息");
}
catch (NoSuchFieldException | IllegalAccessException e) {
fail("Exception encountered.", e);
}
quotaCheckWithHtmlRejectTipsServletFilter.init();
try {
Field rejectTips = QuotaCheckServletFilter.class.getDeclaredField("rejectTips");
rejectTips.setAccessible(true);
assertThat(rejectTips.get(quotaCheckWithHtmlRejectTipsServletFilter)).isEqualTo("<h1>RejectRequestTips提示消息</h1>");
}
catch (NoSuchFieldException | IllegalAccessException e) {
fail("Exception encountered.", e);
@ -201,8 +216,11 @@ public class QuotaCheckServletFilterTest {
MetadataContext.LOCAL_SERVICE = "TestApp3";
quotaCheckServletFilter.doFilterInternal(request, response, filterChain);
assertThat(response.getStatus()).isEqualTo(419);
assertThat(response.getContentAsString()).isEqualTo("RejectRequestTips");
assertThat(response.getContentAsString()).isEqualTo("RejectRequestTips提示消息");
quotaCheckWithHtmlRejectTipsServletFilter.doFilterInternal(request, response, filterChain);
assertThat(response.getStatus()).isEqualTo(419);
assertThat(response.getContentAsString()).isEqualTo("RejectRequestTips提示消息");
// Exception
MetadataContext.LOCAL_SERVICE = "TestApp4";

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

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

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

@ -23,6 +23,7 @@ import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.StreamUtils;
/**
* Read file content from classpath resource.
@ -35,20 +36,15 @@ public final class ResourceFileUtils {
}
public static String readFile(String path) throws IOException {
StringBuilder sb = new StringBuilder();
ClassPathResource classPathResource = new ClassPathResource(path);
if (classPathResource.exists() && classPathResource.isReadable()) {
try (InputStream inputStream = classPathResource.getInputStream()) {
byte[] buffer = new byte[1024 * 10];
int len;
while ((len = inputStream.read(buffer)) != -1) {
sb.append(new String(buffer, 0, len, StandardCharsets.UTF_8));
}
return StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
}
}
return sb.toString();
return "";
}
}

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

@ -35,7 +35,7 @@ public class ResourceFileUtilsTest {
@Test
public void testReadExistedFile() throws IOException {
String content = ResourceFileUtils.readFile("test.txt");
Assert.assertEquals("just for test\n", content);
Assert.assertEquals("just for test", content);
}
@Test

@ -73,7 +73,7 @@
<revision>1.6.0-2020.0.5-SNAPSHOT</revision>
<!-- Dependencies -->
<polaris.version>1.6.1</polaris.version>
<polaris.version>1.7.0-SNAPSHOT</polaris.version>
<logback.version>1.2.11</logback.version>
<mocktio.version>4.5.1</mocktio.version>
<byte-buddy.version>1.12.10</byte-buddy.version>

@ -48,6 +48,11 @@ public class ServiceAController {
return polarisServiceB.info();
}
@GetMapping("/getBServiceInfoByRestTemplate")
public String getBServiceInfoByRestTemplate() {
return restTemplate.getForObject("http://polaris-circuitbreaker-example-b/example/service/b/info", String.class);
}
/**
* Get info of Service B by RestTemplate.
* @return info of Service B

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

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

@ -18,6 +18,11 @@
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.tencent.cloud</groupId>
<artifactId>spring-cloud-starter-tencent-polaris-discovery</artifactId>
</dependency>
<dependency>
<groupId>com.tencent.cloud</groupId>
<artifactId>spring-cloud-starter-tencent-polaris-ratelimit</artifactId>

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

@ -0,0 +1,39 @@
/*
* 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.config;
import com.tencent.cloud.common.metadata.StaticMetadataManager;
import com.tencent.cloud.polaris.context.PostInitPolarisSDKContext;
import com.tencent.polaris.client.api.SDKContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Post-initialization operations after the application initialization phase is completed.
*@author lepdou 2022-06-28
*/
@Configuration
public class PolarisContextPostConfiguration {
@Bean
public PostInitPolarisSDKContext postInitPolarisSDKContext(SDKContext sdkContext, StaticMetadataManager staticMetadataManager) {
return new PostInitPolarisSDKContext(sdkContext, staticMetadataManager);
}
}

@ -16,13 +16,14 @@
*
*/
package com.tencent.cloud.polaris.context;
package com.tencent.cloud.polaris.context.config;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import com.tencent.cloud.polaris.context.PolarisConfigModifier;
import com.tencent.polaris.api.config.ConfigProvider;
import com.tencent.polaris.api.config.Configuration;
import com.tencent.polaris.factory.ConfigAPIFactory;

@ -2,8 +2,8 @@
"groups": [
{
"name": "spring.cloud.polaris",
"type": "com.tencent.cloud.polaris.context.PolarisContextProperties",
"sourceType": "com.tencent.cloud.polaris.context.PolarisContextProperties"
"type": "com.tencent.cloud.polaris.context.config.PolarisContextProperties",
"sourceType": "com.tencent.cloud.polaris.context.config.PolarisContextProperties"
}
],
"properties": [
@ -11,28 +11,28 @@
"name": "spring.cloud.polaris.address",
"type": "java.lang.String",
"description": "polaris server address list that can be separated by \",\"",
"sourceType": "com.tencent.cloud.polaris.context.PolarisContextProperties"
"sourceType": "com.tencent.cloud.polaris.context.config.PolarisContextProperties"
},
{
"name": "spring.cloud.polaris.namespace",
"type": "java.lang.String",
"description": "polaris namespace",
"default": "default",
"sourceType": "com.tencent.cloud.polaris.context.PolarisContextProperties"
"sourceType": "com.tencent.cloud.polaris.context.config.PolarisContextProperties"
},
{
"name": "spring.cloud.polaris.service",
"type": "java.lang.String",
"description": "polaris service name",
"default": "${spring.application.name}",
"sourceType": "com.tencent.cloud.polaris.context.PolarisContextProperties"
"sourceType": "com.tencent.cloud.polaris.context.config.PolarisContextProperties"
},
{
"name": "spring.cloud.polaris.enabled",
"type": "java.lang.Boolean",
"description": "polaris enabled",
"default": "true",
"sourceType": "com.tencent.cloud.polaris.context.PolarisContextProperties"
"sourceType": "com.tencent.cloud.polaris.context.config.PolarisContextProperties"
},
{
"name": "spring.cloud.polaris.local-ip-address",

@ -1,4 +1,5 @@
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.tencent.cloud.polaris.context.PolarisContextAutoConfiguration
com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration,\
com.tencent.cloud.polaris.context.config.PolarisContextPostConfiguration
org.springframework.cloud.bootstrap.BootstrapConfiguration=\
com.tencent.cloud.polaris.context.PolarisContextBootstrapAutoConfiguration
com.tencent.cloud.polaris.context.config.PolarisContextBootstrapAutoConfiguration

@ -17,6 +17,7 @@
package com.tencent.cloud.polaris.context;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import com.tencent.polaris.client.api.SDKContext;
import org.junit.Assert;
import org.junit.Test;

@ -17,6 +17,8 @@
package com.tencent.cloud.polaris.context;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import com.tencent.cloud.polaris.context.config.PolarisContextProperties;
import com.tencent.polaris.client.api.SDKContext;
import org.junit.Assert;
import org.junit.Test;

@ -17,7 +17,7 @@
package com.tencent.cloud.polaris.loadbalancer.config;
import com.tencent.cloud.polaris.context.PolarisContextAutoConfiguration;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import com.tencent.polaris.router.api.core.RouterAPI;
import org.junit.Test;

@ -17,7 +17,7 @@
package com.tencent.cloud.polaris.loadbalancer.config;
import com.tencent.cloud.polaris.context.PolarisContextAutoConfiguration;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import com.tencent.cloud.polaris.loadbalancer.PolarisServiceInstanceListSupplier;
import com.tencent.polaris.router.api.core.RouterAPI;
import org.junit.Test;

Loading…
Cancel
Save