feat:add switch of polaris, discovery and register.

pull/129/head
SkyeBeFreeman 3 years ago
parent 8ee3c9f96b
commit aec7b599ae

@ -1,10 +1,11 @@
# Change Log # Change Log
--- ---
- [Bugfix: fix router bug and add router example](https://github.com/Tencent/spring-cloud-tencent/pull/89) - [Bugfix: fix router bug and add router example](https://github.com/Tencent/spring-cloud-tencent/pull/109)
- [feat:add custom label resolver spi for rate limit](https://github.com/Tencent/spring-cloud-tencent/pull/105) - [feat:add custom label resolver spi for rate limit](https://github.com/Tencent/spring-cloud-tencent/pull/107)
- [feat:fix discovery weight param not set to register request bug](https://github.com/Tencent/spring-cloud-tencent/pull/102) - [feat:fix discovery weight param not set to register request bug](https://github.com/Tencent/spring-cloud-tencent/pull/104)
- [Bugfix: fix causing cpu 100% when set ScheduledThreadPoolExecutor corePoolSize=0](https://github.com/Tencent/spring-cloud-tencent/pull/98) - [Bugfix: fix causing cpu 100% when set ScheduledThreadPoolExecutor corePoolSize=0](https://github.com/Tencent/spring-cloud-tencent/pull/101)
- [Refactor: refactor transfer metadata](https://github.com/Tencent/spring-cloud-tencent/pull/113) - [Refactor: refactor transfer metadata](https://github.com/Tencent/spring-cloud-tencent/pull/113)
- [Bugfix: fix circuitbreaker http code greater than 400 as fail response bug](https://github.com/Tencent/spring-cloud-tencent/pull/118) - [Bugfix: fix circuitbreaker http code greater than 400 as fail response bug](https://github.com/Tencent/spring-cloud-tencent/pull/118)
- [Feat: optimize router dependency](https://github.com/Tencent/spring-cloud-tencent/pull/115) - [Feat: optimize router dependency](https://github.com/Tencent/spring-cloud-tencent/pull/115)
- [feat:add switch of polaris, discovery and register.](https://github.com/Tencent/spring-cloud-tencent/pull/129)

@ -265,6 +265,7 @@
<version>${maven-gpg-plugin.version}</version> <version>${maven-gpg-plugin.version}</version>
<executions> <executions>
<execution> <execution>
<id>sign-artifacts</id>
<phase>verify</phase> <phase>verify</phase>
<goals> <goals>
<goal>sign</goal> <goal>sign</goal>

@ -47,6 +47,7 @@ import static javax.servlet.DispatcherType.ERROR;
import static javax.servlet.DispatcherType.FORWARD; import static javax.servlet.DispatcherType.FORWARD;
import static javax.servlet.DispatcherType.INCLUDE; import static javax.servlet.DispatcherType.INCLUDE;
import static javax.servlet.DispatcherType.REQUEST; import static javax.servlet.DispatcherType.REQUEST;
/** /**
* Metadata transfer auto configuration. * Metadata transfer auto configuration.
* *
@ -67,10 +68,8 @@ public class MetadataTransferAutoConfiguration {
DecodeTransferMetadataServletFilter decodeTransferMetadataServletFilter) { DecodeTransferMetadataServletFilter decodeTransferMetadataServletFilter) {
FilterRegistrationBean<DecodeTransferMetadataServletFilter> filterRegistrationBean = new FilterRegistrationBean<>( FilterRegistrationBean<DecodeTransferMetadataServletFilter> filterRegistrationBean = new FilterRegistrationBean<>(
decodeTransferMetadataServletFilter); decodeTransferMetadataServletFilter);
filterRegistrationBean.setDispatcherTypes(ASYNC, ERROR, FORWARD, INCLUDE, filterRegistrationBean.setDispatcherTypes(ASYNC, ERROR, FORWARD, INCLUDE, REQUEST);
REQUEST); filterRegistrationBean.setOrder(MetadataConstant.OrderConstant.WEB_FILTER_ORDER);
filterRegistrationBean
.setOrder(MetadataConstant.OrderConstant.WEB_FILTER_ORDER);
return filterRegistrationBean; return filterRegistrationBean;
} }
@ -149,15 +148,13 @@ public class MetadataTransferAutoConfiguration {
for (RestTemplate restTemplate : beans.values()) { for (RestTemplate restTemplate : beans.values()) {
List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors(); List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors();
// Avoid setting interceptor repeatedly. // Avoid setting interceptor repeatedly.
if (null != interceptors && !interceptors if (null != interceptors && !interceptors.contains(encodeTransferMedataRestTemplateInterceptor)) {
.contains(encodeTransferMedataRestTemplateInterceptor)) {
interceptors.add(encodeTransferMedataRestTemplateInterceptor); interceptors.add(encodeTransferMedataRestTemplateInterceptor);
restTemplate.setInterceptors(interceptors); restTemplate.setInterceptors(interceptors);
} }
} }
} }
return new EncodeTransferMetadataRestTemplatePostProcessor( return new EncodeTransferMetadataRestTemplatePostProcessor(encodeTransferMedataRestTemplateInterceptor);
encodeTransferMedataRestTemplateInterceptor);
} }
@Override @Override
@ -165,8 +162,7 @@ public class MetadataTransferAutoConfiguration {
this.context = applicationContext; this.context = applicationContext;
} }
public static class EncodeTransferMetadataRestTemplatePostProcessor public static class EncodeTransferMetadataRestTemplatePostProcessor implements BeanPostProcessor {
implements BeanPostProcessor {
private EncodeTransferMedataRestTemplateInterceptor encodeTransferMedataRestTemplateInterceptor; private EncodeTransferMedataRestTemplateInterceptor encodeTransferMedataRestTemplateInterceptor;
@ -186,8 +182,7 @@ public class MetadataTransferAutoConfiguration {
RestTemplate restTemplate = (RestTemplate) bean; RestTemplate restTemplate = (RestTemplate) bean;
List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors(); List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors();
// Avoid setting interceptor repeatedly. // Avoid setting interceptor repeatedly.
if (null != interceptors && !interceptors if (null != interceptors && !interceptors.contains(encodeTransferMedataRestTemplateInterceptor)) {
.contains(encodeTransferMedataRestTemplateInterceptor)) {
interceptors.add(this.encodeTransferMedataRestTemplateInterceptor); interceptors.add(this.encodeTransferMedataRestTemplateInterceptor);
restTemplate.setInterceptors(interceptors); restTemplate.setInterceptors(interceptors);
} }

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

@ -47,8 +47,7 @@ import org.springframework.web.filter.OncePerRequestFilter;
@Order(MetadataConstant.OrderConstant.WEB_FILTER_ORDER) @Order(MetadataConstant.OrderConstant.WEB_FILTER_ORDER)
public class DecodeTransferMetadataServletFilter extends OncePerRequestFilter { public class DecodeTransferMetadataServletFilter extends OncePerRequestFilter {
private static final Logger LOG = LoggerFactory private static final Logger LOG = LoggerFactory.getLogger(DecodeTransferMetadataServletFilter.class);
.getLogger(DecodeTransferMetadataServletFilter.class);
@Override @Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,

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

@ -42,8 +42,7 @@ import org.springframework.util.CollectionUtils;
* *
* @author Haotian Zhang * @author Haotian Zhang
*/ */
public class EncodeTransferMedataRestTemplateInterceptor public class EncodeTransferMedataRestTemplateInterceptor implements ClientHttpRequestInterceptor, Ordered {
implements ClientHttpRequestInterceptor, Ordered {
@Override @Override
public int getOrder() { public int getOrder() {

@ -38,12 +38,10 @@ import org.springframework.web.server.WebFilterChain;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.MOCK; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.MOCK;
/** /**
*
* @author Haotian Zhang * @author Haotian Zhang
*/ */
@RunWith(SpringRunner.class) @RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = MOCK, @SpringBootTest(webEnvironment = MOCK, classes = DecodeTransferMetadataServletFilterTest.TestApplication.class,
classes = DecodeTransferMetadataServletFilterTest.TestApplication.class,
properties = { "spring.config.location = classpath:application-test.yml" }) properties = { "spring.config.location = classpath:application-test.yml" })
public class DecodeTransferMetadataReactiveFilterTest { public class DecodeTransferMetadataReactiveFilterTest {

@ -40,12 +40,10 @@ import org.springframework.test.context.junit4.SpringRunner;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
/** /**
*
* @author Haotian Zhang * @author Haotian Zhang
*/ */
@RunWith(SpringRunner.class) @RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = RANDOM_PORT, @SpringBootTest(webEnvironment = RANDOM_PORT, classes = DecodeTransferMetadataServletFilterTest.TestApplication.class,
classes = DecodeTransferMetadataServletFilterTest.TestApplication.class,
properties = { "spring.config.location = classpath:application-test.yml" }) properties = { "spring.config.location = classpath:application-test.yml" })
public class DecodeTransferMetadataServletFilterTest { public class DecodeTransferMetadataServletFilterTest {

@ -45,16 +45,14 @@ public class MetadataTransferAutoConfigurationTest {
.run(context -> { .run(context -> {
Assertions.assertThat(context).hasSingleBean( Assertions.assertThat(context).hasSingleBean(
MetadataTransferAutoConfiguration.MetadataTransferFeignInterceptorConfig.class); MetadataTransferAutoConfiguration.MetadataTransferFeignInterceptorConfig.class);
Assertions.assertThat(context).hasSingleBean(EncodeTransferMedataFeignInterceptor.class);
Assertions.assertThat(context) Assertions.assertThat(context)
.hasSingleBean(EncodeTransferMedataFeignInterceptor.class); .hasSingleBean(MetadataTransferAutoConfiguration.MetadataTransferRestTemplateConfig.class);
Assertions.assertThat(context).hasSingleBean( Assertions.assertThat(context).hasSingleBean(EncodeTransferMedataRestTemplateInterceptor.class);
MetadataTransferAutoConfiguration.MetadataTransferRestTemplateConfig.class);
Assertions.assertThat(context)
.hasSingleBean(EncodeTransferMedataRestTemplateInterceptor.class);
Assertions.assertThat(context).hasSingleBean( Assertions.assertThat(context).hasSingleBean(
MetadataTransferAutoConfiguration.MetadataTransferRestTemplateConfig.EncodeTransferMetadataRestTemplatePostProcessor.class); MetadataTransferAutoConfiguration.MetadataTransferRestTemplateConfig.EncodeTransferMetadataRestTemplatePostProcessor.class);
Assertions.assertThat(context).hasSingleBean( Assertions.assertThat(context)
MetadataTransferAutoConfiguration.MetadataTransferScgFilterConfig.class); .hasSingleBean(MetadataTransferAutoConfiguration.MetadataTransferScgFilterConfig.class);
Assertions.assertThat(context).hasSingleBean(GlobalFilter.class); Assertions.assertThat(context).hasSingleBean(GlobalFilter.class);
}); });
} }

@ -57,10 +57,8 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
* @author Haotian Zhang * @author Haotian Zhang
*/ */
@RunWith(SpringRunner.class) @RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = DEFINED_PORT, @SpringBootTest(webEnvironment = DEFINED_PORT, classes = EncodeTransferMedataFeignInterceptorTest.TestApplication.class,
classes = EncodeTransferMedataFeignInterceptorTest.TestApplication.class, properties = { "server.port=8081", "spring.config.location = classpath:application-test.yml" })
properties = { "server.port=8081",
"spring.config.location = classpath:application-test.yml" })
public class EncodeTransferMedataFeignInterceptorTest { public class EncodeTransferMedataFeignInterceptorTest {
@Autowired @Autowired

@ -18,6 +18,7 @@
package com.tencent.cloud.polaris.circuitbreaker; package com.tencent.cloud.polaris.circuitbreaker;
import com.tencent.cloud.common.constant.ContextConstant; import com.tencent.cloud.common.constant.ContextConstant;
import com.tencent.cloud.polaris.context.ConditionalOnPolarisEnabled;
import com.tencent.cloud.polaris.context.PolarisConfigModifier; import com.tencent.cloud.polaris.context.PolarisConfigModifier;
import com.tencent.polaris.factory.config.ConfigurationImpl; import com.tencent.polaris.factory.config.ConfigurationImpl;
@ -30,6 +31,7 @@ import org.springframework.context.annotation.Configuration;
* *
* @author lepdou 2022-03-29 * @author lepdou 2022-03-29
*/ */
@ConditionalOnPolarisEnabled
@ConditionalOnProperty(value = "spring.cloud.polaris.circuitbreaker.enabled", havingValue = "true", @ConditionalOnProperty(value = "spring.cloud.polaris.circuitbreaker.enabled", havingValue = "true",
matchIfMissing = true) matchIfMissing = true)
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)

@ -18,7 +18,7 @@
package com.tencent.cloud.polaris.circuitbreaker; package com.tencent.cloud.polaris.circuitbreaker;
import com.tencent.cloud.polaris.circuitbreaker.feign.PolarisFeignBeanPostProcessor; import com.tencent.cloud.polaris.circuitbreaker.feign.PolarisFeignBeanPostProcessor;
import com.tencent.cloud.polaris.context.PolarisContextConfiguration; import com.tencent.cloud.polaris.context.PolarisContextAutoConfiguration;
import com.tencent.polaris.api.core.ConsumerAPI; import com.tencent.polaris.api.core.ConsumerAPI;
import com.tencent.polaris.client.api.SDKContext; import com.tencent.polaris.client.api.SDKContext;
import com.tencent.polaris.factory.api.DiscoveryAPIFactory; import com.tencent.polaris.factory.api.DiscoveryAPIFactory;
@ -42,7 +42,7 @@ import static org.springframework.core.Ordered.HIGHEST_PRECEDENCE;
@ConditionalOnProperty(value = "spring.cloud.polaris.circuitbreaker.enabled", havingValue = "true", @ConditionalOnProperty(value = "spring.cloud.polaris.circuitbreaker.enabled", havingValue = "true",
matchIfMissing = true) matchIfMissing = true)
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
@AutoConfigureAfter(PolarisContextConfiguration.class) @AutoConfigureAfter(PolarisContextAutoConfiguration.class)
@AutoConfigureBefore(FeignAutoConfiguration.class) @AutoConfigureBefore(FeignAutoConfiguration.class)
public class PolarisFeignClientAutoConfiguration { public class PolarisFeignClientAutoConfiguration {

@ -3,7 +3,7 @@
{ {
"name": "spring.cloud.polaris.circuitbreaker.enabled", "name": "spring.cloud.polaris.circuitbreaker.enabled",
"type": "java.lang.Boolean", "type": "java.lang.Boolean",
"sourceType": "com.tencent.cloud.polaris.circuitbreaker.PolarisFeignProperties" "defaultValue": "true"
} }
], ],
"hints": [] "hints": []

@ -18,7 +18,7 @@
package com.tencent.cloud.polaris.circuitbreaker.feign; package com.tencent.cloud.polaris.circuitbreaker.feign;
import com.tencent.cloud.polaris.circuitbreaker.PolarisFeignClientAutoConfiguration; import com.tencent.cloud.polaris.circuitbreaker.PolarisFeignClientAutoConfiguration;
import com.tencent.cloud.polaris.context.PolarisContextConfiguration; import com.tencent.cloud.polaris.context.PolarisContextAutoConfiguration;
import feign.Client; import feign.Client;
import org.junit.Test; import org.junit.Test;
import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Assertions;
@ -37,7 +37,7 @@ import org.springframework.test.context.junit4.SpringRunner;
*/ */
@RunWith(SpringRunner.class) @RunWith(SpringRunner.class)
@SpringBootTest(classes = TestPolarisFeignApp.class) @SpringBootTest(classes = TestPolarisFeignApp.class)
@ContextConfiguration(classes = { PolarisFeignClientAutoConfiguration.class, PolarisContextConfiguration.class }) @ContextConfiguration(classes = { PolarisFeignClientAutoConfiguration.class, PolarisContextAutoConfiguration.class })
public class PolarisFeignClientTest { public class PolarisFeignClientTest {
@Autowired @Autowired

@ -21,6 +21,7 @@ package com.tencent.cloud.polaris.config;
import com.tencent.cloud.polaris.config.adapter.PolarisPropertySourceAutoRefresher; import com.tencent.cloud.polaris.config.adapter.PolarisPropertySourceAutoRefresher;
import com.tencent.cloud.polaris.config.adapter.PolarisPropertySourceManager; import com.tencent.cloud.polaris.config.adapter.PolarisPropertySourceManager;
import com.tencent.cloud.polaris.config.config.PolarisConfigProperties; import com.tencent.cloud.polaris.config.config.PolarisConfigProperties;
import com.tencent.cloud.polaris.context.ConditionalOnPolarisEnabled;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.context.refresh.ContextRefresher; import org.springframework.cloud.context.refresh.ContextRefresher;
@ -33,6 +34,7 @@ import org.springframework.context.annotation.Configuration;
* @author lepdou 2022-03-28 * @author lepdou 2022-03-28
*/ */
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
@ConditionalOnPolarisEnabled
@ConditionalOnProperty(value = "spring.cloud.polaris.config.enabled", matchIfMissing = true) @ConditionalOnProperty(value = "spring.cloud.polaris.config.enabled", matchIfMissing = true)
public class PolarisConfigAutoConfiguration { public class PolarisConfigAutoConfiguration {

@ -20,7 +20,8 @@ package com.tencent.cloud.polaris.config;
import com.tencent.cloud.polaris.config.adapter.PolarisConfigFileLocator; import com.tencent.cloud.polaris.config.adapter.PolarisConfigFileLocator;
import com.tencent.cloud.polaris.config.adapter.PolarisPropertySourceManager; import com.tencent.cloud.polaris.config.adapter.PolarisPropertySourceManager;
import com.tencent.cloud.polaris.config.config.PolarisConfigProperties; import com.tencent.cloud.polaris.config.config.PolarisConfigProperties;
import com.tencent.cloud.polaris.context.PolarisContextConfiguration; 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.PolarisContextProperties;
import com.tencent.polaris.client.api.SDKContext; import com.tencent.polaris.client.api.SDKContext;
import com.tencent.polaris.configuration.api.core.ConfigFileService; import com.tencent.polaris.configuration.api.core.ConfigFileService;
@ -37,8 +38,9 @@ import org.springframework.context.annotation.Import;
* @author lepdou 2022-03-10 * @author lepdou 2022-03-10
*/ */
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
@ConditionalOnPolarisEnabled
@ConditionalOnProperty(value = "spring.cloud.polaris.config.enabled", matchIfMissing = true) @ConditionalOnProperty(value = "spring.cloud.polaris.config.enabled", matchIfMissing = true)
@Import(PolarisContextConfiguration.class) @Import(PolarisContextAutoConfiguration.class)
public class PolarisConfigBootstrapAutoConfiguration { public class PolarisConfigBootstrapAutoConfiguration {
@Bean @Bean

@ -0,0 +1,95 @@
/*
* 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;
import javax.annotation.PostConstruct;
import com.tencent.cloud.polaris.context.ConditionalOnPolarisEnabled;
import com.tencent.cloud.polaris.discovery.PolarisDiscoveryHandler;
import com.tencent.cloud.polaris.extend.consul.ConsulContextProperties;
import com.tencent.polaris.api.core.ConsumerAPI;
import com.tencent.polaris.api.core.ProviderAPI;
import com.tencent.polaris.api.exception.PolarisException;
import com.tencent.polaris.client.api.SDKContext;
import com.tencent.polaris.factory.api.DiscoveryAPIFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
/**
* Common configuration of discovery.
*
* @author Haotian Zhang
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnPolarisEnabled
@Import({ PolarisDiscoveryProperties.class, ConsulContextProperties.class })
public class DiscoveryPropertiesAutoConfiguration {
@Autowired(required = false)
private PolarisDiscoveryProperties polarisDiscoveryProperties;
@Autowired(required = false)
private ConsulContextProperties consulContextProperties;
private boolean registerEnabled = false;
private boolean discoveryEnabled = false;
@Bean(name = "polarisProvider")
@ConditionalOnMissingBean
public ProviderAPI polarisProvider(SDKContext polarisContext) throws PolarisException {
return DiscoveryAPIFactory.createProviderAPIByContext(polarisContext);
}
@Bean(name = "polarisConsumer")
@ConditionalOnMissingBean
public ConsumerAPI polarisConsumer(SDKContext polarisContext) throws PolarisException {
return DiscoveryAPIFactory.createConsumerAPIByContext(polarisContext);
}
@Bean
@ConditionalOnMissingBean
public PolarisDiscoveryHandler polarisDiscoveryHandler() {
return new PolarisDiscoveryHandler();
}
@PostConstruct
public void init() {
if (null != polarisDiscoveryProperties) {
registerEnabled |= polarisDiscoveryProperties.isRegisterEnabled();
discoveryEnabled |= polarisDiscoveryProperties.isEnabled();
}
if (null != consulContextProperties && consulContextProperties.isEnabled()) {
registerEnabled |= consulContextProperties.isRegister();
discoveryEnabled |= consulContextProperties.isDiscoveryEnabled();
}
}
public boolean isRegisterEnabled() {
return registerEnabled;
}
public boolean isDiscoveryEnabled() {
return discoveryEnabled;
}
}

@ -0,0 +1,34 @@
/*
* 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;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
/**
* Common configuration of discovery.
*
* @author Haotian Zhang
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnProperty("spring.cloud.polaris.enabled")
@Import(DiscoveryPropertiesAutoConfiguration.class)
public class DiscoveryPropertiesBootstrapAutoConfiguration {
}

@ -20,11 +20,18 @@ package com.tencent.cloud.polaris;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
import com.tencent.cloud.common.constant.ContextConstant;
import com.tencent.cloud.polaris.context.PolarisConfigModifier;
import com.tencent.polaris.factory.config.ConfigurationImpl;
import com.tencent.polaris.factory.config.consumer.DiscoveryConfigImpl;
import com.tencent.polaris.factory.config.provider.RegisterConfigImpl;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment; import org.springframework.core.env.Environment;
/** /**
@ -75,10 +82,15 @@ public class PolarisDiscoveryProperties {
@Value("${server.port:}") @Value("${server.port:}")
private int port; private int port;
/**
* Enable polaris discovery or not.
*/
private Boolean enabled = true;
/** /**
* If instance registered. * If instance registered.
*/ */
@Value("${spring.cloud.polaris.discovery.register.enabled:#{true}}") @Value("${spring.cloud.polaris.discovery.register:#{true}}")
private Boolean registerEnabled; private Boolean registerEnabled;
/** /**
@ -147,6 +159,14 @@ public class PolarisDiscoveryProperties {
this.service = service; this.service = service;
} }
public Boolean isEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public boolean isRegisterEnabled() { public boolean isRegisterEnabled() {
return registerEnabled; return registerEnabled;
} }
@ -203,4 +223,39 @@ public class PolarisDiscoveryProperties {
+ heartbeatEnabled + ", healthCheckUrl=" + healthCheckUrl + ", environment=" + environment + '}'; + heartbeatEnabled + ", healthCheckUrl=" + healthCheckUrl + ", environment=" + environment + '}';
} }
@Bean
@ConditionalOnMissingBean
public PolarisDiscoveryConfigModifier polarisDiscoveryConfigModifier() {
return new PolarisDiscoveryConfigModifier();
}
private static class PolarisDiscoveryConfigModifier implements PolarisConfigModifier {
private final String ID = "polaris";
@Autowired(required = false)
private PolarisDiscoveryProperties polarisDiscoveryProperties;
@Override
public void modify(ConfigurationImpl configuration) {
if (polarisDiscoveryProperties != null) {
DiscoveryConfigImpl discoveryConfig = new DiscoveryConfigImpl();
discoveryConfig.setServerConnectorId(ID);
discoveryConfig.setEnable(polarisDiscoveryProperties.enabled);
configuration.getConsumer().getDiscoveries().add(discoveryConfig);
RegisterConfigImpl registerConfig = new RegisterConfigImpl();
registerConfig.setServerConnectorId(ID);
registerConfig.setEnable(polarisDiscoveryProperties.registerEnabled);
configuration.getProvider().getRegisters().add(registerConfig);
}
}
@Override
public int getOrder() {
return ContextConstant.ModifierOrder.LAST;
}
}
} }

@ -22,8 +22,10 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy; import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; import java.lang.annotation.Target;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import com.tencent.cloud.polaris.context.ConditionalOnPolarisEnabled;
import org.springframework.cloud.client.ConditionalOnDiscoveryEnabled; import org.springframework.cloud.client.ConditionalOnDiscoveryEnabled;
import org.springframework.context.annotation.Conditional;
/** /**
* @author Haotian Zhang, Andrew Shan, Jie Cheng * @author Haotian Zhang, Andrew Shan, Jie Cheng
@ -31,7 +33,8 @@ import org.springframework.cloud.client.ConditionalOnDiscoveryEnabled;
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD }) @Target({ ElementType.TYPE, ElementType.METHOD })
@ConditionalOnDiscoveryEnabled @ConditionalOnDiscoveryEnabled
@ConditionalOnProperty(value = "spring.cloud.polaris.discovery.enabled", matchIfMissing = true) @ConditionalOnPolarisEnabled
@Conditional(DiscoveryEnabledCondition.class)
public @interface ConditionalOnPolarisDiscoveryEnabled { public @interface ConditionalOnPolarisDiscoveryEnabled {
} }

@ -0,0 +1,46 @@
/*
* 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.discovery;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
/**
* Condition for checking if discovery enabled.
*
* @author Haotian Zhang
*/
public class DiscoveryEnabledCondition implements Condition {
@Override
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
boolean isDiscoveryEnabled = Boolean.parseBoolean(
conditionContext.getEnvironment().getProperty("spring.cloud.polaris.discovery.enabled", "true"));
boolean isConsulDiscoveryEnabled = Boolean
.parseBoolean(conditionContext.getEnvironment().getProperty("spring.cloud.consul.enabled", "false"))
&& Boolean.parseBoolean(
conditionContext.getEnvironment().getProperty("spring.cloud.consul.discovery.enabled", "true"));
isDiscoveryEnabled |= isConsulDiscoveryEnabled;
return isDiscoveryEnabled;
}
}

@ -18,14 +18,7 @@
package com.tencent.cloud.polaris.discovery; package com.tencent.cloud.polaris.discovery;
import com.tencent.cloud.polaris.PolarisDiscoveryProperties;
import com.tencent.cloud.polaris.discovery.reactive.PolarisReactiveDiscoveryClientConfiguration; import com.tencent.cloud.polaris.discovery.reactive.PolarisReactiveDiscoveryClientConfiguration;
import com.tencent.cloud.polaris.extend.consul.ConsulContextProperties;
import com.tencent.polaris.api.core.ConsumerAPI;
import com.tencent.polaris.api.core.ProviderAPI;
import com.tencent.polaris.api.exception.PolarisException;
import com.tencent.polaris.client.api.SDKContext;
import com.tencent.polaris.factory.api.DiscoveryAPIFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
@ -39,34 +32,9 @@ import org.springframework.context.annotation.Import;
*/ */
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
@ConditionalOnPolarisDiscoveryEnabled @ConditionalOnPolarisDiscoveryEnabled
@Import({ PolarisDiscoveryClientConfiguration.class, PolarisReactiveDiscoveryClientConfiguration.class, @Import({ PolarisDiscoveryClientConfiguration.class, PolarisReactiveDiscoveryClientConfiguration.class })
ConsulContextProperties.class })
public class PolarisDiscoveryAutoConfiguration { public class PolarisDiscoveryAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public PolarisDiscoveryProperties polarisDiscoveryProperties() {
return new PolarisDiscoveryProperties();
}
@Bean(name = "polarisProvider")
@ConditionalOnMissingBean
public ProviderAPI polarisProvider(SDKContext polarisContext) throws PolarisException {
return DiscoveryAPIFactory.createProviderAPIByContext(polarisContext);
}
@Bean(name = "polarisConsumer")
@ConditionalOnMissingBean
public ConsumerAPI polarisConsumer(SDKContext polarisContext) throws PolarisException {
return DiscoveryAPIFactory.createConsumerAPIByContext(polarisContext);
}
@Bean
@ConditionalOnMissingBean
public PolarisDiscoveryHandler polarisDiscoveryHandler() {
return new PolarisDiscoveryHandler();
}
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public PolarisServiceDiscovery polarisServiceDiscovery(PolarisDiscoveryHandler polarisDiscoveryHandler) { public PolarisServiceDiscovery polarisServiceDiscovery(PolarisDiscoveryHandler polarisDiscoveryHandler) {

@ -49,7 +49,7 @@ public class PolarisServiceDiscovery {
*/ */
public List<ServiceInstance> getInstances(String serviceId) throws PolarisException { public List<ServiceInstance> getInstances(String serviceId) throws PolarisException {
List<ServiceInstance> instances = new ArrayList<>(); List<ServiceInstance> instances = new ArrayList<>();
InstancesResponse filteredInstances = polarisDiscoveryHandler.getInstances(serviceId); InstancesResponse filteredInstances = polarisDiscoveryHandler.getFilteredInstances(serviceId);
ServiceInstances serviceInstances = filteredInstances.toServiceInstances(); ServiceInstances serviceInstances = filteredInstances.toServiceInstances();
for (Instance instance : serviceInstances.getInstances()) { for (Instance instance : serviceInstances.getInstances()) {
instances.add(new PolarisServiceInstance(instance)); instances.add(new PolarisServiceInstance(instance));

@ -25,13 +25,14 @@ import com.tencent.cloud.common.constant.ContextConstant.ModifierOrder;
import com.tencent.cloud.polaris.context.PolarisConfigModifier; import com.tencent.cloud.polaris.context.PolarisConfigModifier;
import com.tencent.polaris.api.config.plugin.DefaultPlugins; import com.tencent.polaris.api.config.plugin.DefaultPlugins;
import com.tencent.polaris.factory.config.ConfigurationImpl; import com.tencent.polaris.factory.config.ConfigurationImpl;
import com.tencent.polaris.factory.config.consumer.DiscoveryConfigImpl;
import com.tencent.polaris.factory.config.global.ServerConnectorConfigImpl; import com.tencent.polaris.factory.config.global.ServerConnectorConfigImpl;
import com.tencent.polaris.factory.config.provider.RegisterConfigImpl;
import com.tencent.polaris.plugins.connector.common.constant.ConsulConstant.MetadataMapKey; import com.tencent.polaris.plugins.connector.common.constant.ConsulConstant.MetadataMapKey;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
@ -42,8 +43,6 @@ import org.springframework.util.CollectionUtils;
* *
* @author Haotian Zhang * @author Haotian Zhang
*/ */
@ConditionalOnExpression("'true'.equals('${spring.cloud.consul.enabled:true}')"
+ " && 'true'.equals('${spring.cloud.consul.discovery.enabled:true}')")
@ConfigurationProperties("spring.cloud.consul") @ConfigurationProperties("spring.cloud.consul")
public class ConsulContextProperties { public class ConsulContextProperties {
@ -54,7 +53,7 @@ public class ConsulContextProperties {
private int port; private int port;
private boolean enabled; private boolean enabled = false;
@Value("${spring.cloud.consul.discovery.register:#{'true'}}") @Value("${spring.cloud.consul.discovery.register:#{'true'}}")
private boolean register; private boolean register;
@ -82,10 +81,22 @@ public class ConsulContextProperties {
this.port = port; this.port = port;
} }
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) { public void setEnabled(boolean enabled) {
this.enabled = enabled; this.enabled = enabled;
} }
public boolean isRegister() {
return register;
}
public boolean isDiscoveryEnabled() {
return discoveryEnabled;
}
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public ConsulConfigModifier consulConfigModifier() { public ConsulConfigModifier consulConfigModifier() {
@ -94,18 +105,23 @@ public class ConsulContextProperties {
private static class ConsulConfigModifier implements PolarisConfigModifier { private static class ConsulConfigModifier implements PolarisConfigModifier {
private final String ID = "consul";
@Autowired(required = false) @Autowired(required = false)
private ConsulContextProperties consulContextProperties; private ConsulContextProperties consulContextProperties;
@Override @Override
public void modify(ConfigurationImpl configuration) { public void modify(ConfigurationImpl configuration) {
if (consulContextProperties != null && consulContextProperties.enabled if (consulContextProperties != null && consulContextProperties.enabled) {
&& consulContextProperties.discoveryEnabled && consulContextProperties.register) {
if (CollectionUtils.isEmpty(configuration.getGlobal().getServerConnectors())) { if (CollectionUtils.isEmpty(configuration.getGlobal().getServerConnectors())) {
configuration.getGlobal().setServerConnectors(new ArrayList<>()); configuration.getGlobal().setServerConnectors(new ArrayList<>());
} }
if (CollectionUtils.isEmpty(configuration.getGlobal().getServerConnectors())
&& null != configuration.getGlobal().getServerConnector()) {
configuration.getGlobal().getServerConnectors().add(configuration.getGlobal().getServerConnector()); configuration.getGlobal().getServerConnectors().add(configuration.getGlobal().getServerConnector());
}
ServerConnectorConfigImpl serverConnectorConfig = new ServerConnectorConfigImpl(); ServerConnectorConfigImpl serverConnectorConfig = new ServerConnectorConfigImpl();
serverConnectorConfig.setId(ID);
serverConnectorConfig.setAddresses( serverConnectorConfig.setAddresses(
Collections.singletonList(consulContextProperties.host + ":" + consulContextProperties.port)); Collections.singletonList(consulContextProperties.host + ":" + consulContextProperties.port));
serverConnectorConfig.setProtocol(DefaultPlugins.SERVER_CONNECTOR_CONSUL); serverConnectorConfig.setProtocol(DefaultPlugins.SERVER_CONNECTOR_CONSUL);
@ -123,6 +139,16 @@ public class ConsulContextProperties {
metadata.put(MetadataMapKey.IP_ADDRESS_KEY, consulContextProperties.ipAddress); metadata.put(MetadataMapKey.IP_ADDRESS_KEY, consulContextProperties.ipAddress);
} }
configuration.getGlobal().getServerConnectors().add(serverConnectorConfig); configuration.getGlobal().getServerConnectors().add(serverConnectorConfig);
DiscoveryConfigImpl discoveryConfig = new DiscoveryConfigImpl();
discoveryConfig.setServerConnectorId(ID);
discoveryConfig.setEnable(consulContextProperties.discoveryEnabled);
configuration.getConsumer().getDiscoveries().add(discoveryConfig);
RegisterConfigImpl registerConfig = new RegisterConfigImpl();
registerConfig.setServerConnectorId(ID);
registerConfig.setEnable(consulContextProperties.register);
configuration.getProvider().getRegisters().add(registerConfig);
} }
} }

@ -0,0 +1,38 @@
/*
* 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.registry;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.tencent.cloud.polaris.context.ConditionalOnPolarisEnabled;
import org.springframework.context.annotation.Conditional;
/**
* @author Haotian Zhang
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
@ConditionalOnPolarisEnabled
@Conditional(RegisterEnabledCondition.class)
public @interface ConditionalOnPolarisRegisterEnabled {
}

@ -58,7 +58,7 @@ public class PolarisAutoServiceRegistration extends AbstractAutoServiceRegistrat
@Override @Override
protected void register() { protected void register() {
if (!this.registration.getPolarisProperties().isRegisterEnabled()) { if (!this.registration.isRegisterEnabled()) {
log.debug("Registration disabled."); log.debug("Registration disabled.");
return; return;
} }
@ -70,7 +70,7 @@ public class PolarisAutoServiceRegistration extends AbstractAutoServiceRegistrat
@Override @Override
protected void registerManagement() { protected void registerManagement() {
if (!this.registration.getPolarisProperties().isRegisterEnabled()) { if (!this.registration.isRegisterEnabled()) {
return; return;
} }
super.registerManagement(); super.registerManagement();
@ -84,7 +84,7 @@ public class PolarisAutoServiceRegistration extends AbstractAutoServiceRegistrat
@Override @Override
protected boolean isEnabled() { protected boolean isEnabled() {
return this.registration.getPolarisProperties().isRegisterEnabled(); return this.registration.isRegisterEnabled();
} }
@Override @Override

@ -22,6 +22,7 @@ import java.net.URI;
import java.util.Map; import java.util.Map;
import com.tencent.cloud.common.metadata.MetadataContextHolder; import com.tencent.cloud.common.metadata.MetadataContextHolder;
import com.tencent.cloud.polaris.DiscoveryPropertiesAutoConfiguration;
import com.tencent.cloud.polaris.PolarisDiscoveryProperties; import com.tencent.cloud.polaris.PolarisDiscoveryProperties;
import com.tencent.polaris.client.api.SDKContext; import com.tencent.polaris.client.api.SDKContext;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
@ -37,11 +38,15 @@ import org.springframework.cloud.client.serviceregistry.Registration;
*/ */
public class PolarisRegistration implements Registration, ServiceInstance { public class PolarisRegistration implements Registration, ServiceInstance {
private final DiscoveryPropertiesAutoConfiguration discoveryPropertiesAutoConfiguration;
private final PolarisDiscoveryProperties polarisDiscoveryProperties; private final PolarisDiscoveryProperties polarisDiscoveryProperties;
private final SDKContext polarisContext; private final SDKContext polarisContext;
public PolarisRegistration(PolarisDiscoveryProperties polarisDiscoveryProperties, SDKContext context) { public PolarisRegistration(DiscoveryPropertiesAutoConfiguration discoveryPropertiesAutoConfiguration,
PolarisDiscoveryProperties polarisDiscoveryProperties, SDKContext context) {
this.discoveryPropertiesAutoConfiguration = discoveryPropertiesAutoConfiguration;
this.polarisDiscoveryProperties = polarisDiscoveryProperties; this.polarisDiscoveryProperties = polarisDiscoveryProperties;
this.polarisContext = context; this.polarisContext = context;
} }
@ -84,6 +89,10 @@ public class PolarisRegistration implements Registration, ServiceInstance {
return polarisDiscoveryProperties; return polarisDiscoveryProperties;
} }
public boolean isRegisterEnabled() {
return discoveryPropertiesAutoConfiguration.isRegisterEnabled();
}
@Override @Override
public String toString() { public String toString() {
return "PolarisRegistration{" + "polarisDiscoveryProperties=" + polarisDiscoveryProperties + ", polarisContext=" return "PolarisRegistration{" + "polarisDiscoveryProperties=" + polarisDiscoveryProperties + ", polarisContext="

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

@ -19,8 +19,8 @@
package com.tencent.cloud.polaris.registry; package com.tencent.cloud.polaris.registry;
import com.tencent.cloud.common.metadata.config.MetadataLocalProperties; import com.tencent.cloud.common.metadata.config.MetadataLocalProperties;
import com.tencent.cloud.polaris.DiscoveryPropertiesAutoConfiguration;
import com.tencent.cloud.polaris.PolarisDiscoveryProperties; import com.tencent.cloud.polaris.PolarisDiscoveryProperties;
import com.tencent.cloud.polaris.discovery.ConditionalOnPolarisDiscoveryEnabled;
import com.tencent.cloud.polaris.discovery.PolarisDiscoveryAutoConfiguration; import com.tencent.cloud.polaris.discovery.PolarisDiscoveryAutoConfiguration;
import com.tencent.cloud.polaris.discovery.PolarisDiscoveryHandler; import com.tencent.cloud.polaris.discovery.PolarisDiscoveryHandler;
import com.tencent.polaris.client.api.SDKContext; import com.tencent.polaris.client.api.SDKContext;
@ -42,7 +42,7 @@ import org.springframework.context.annotation.Configuration;
*/ */
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties @EnableConfigurationProperties
@ConditionalOnPolarisDiscoveryEnabled @ConditionalOnPolarisRegisterEnabled
@ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true) @ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true)
@AutoConfigureAfter({ AutoServiceRegistrationConfiguration.class, AutoServiceRegistrationAutoConfiguration.class, @AutoConfigureAfter({ AutoServiceRegistrationConfiguration.class, AutoServiceRegistrationAutoConfiguration.class,
PolarisDiscoveryAutoConfiguration.class }) PolarisDiscoveryAutoConfiguration.class })
@ -56,9 +56,10 @@ public class PolarisServiceRegistryAutoConfiguration {
@Bean @Bean
@ConditionalOnBean(AutoServiceRegistrationProperties.class) @ConditionalOnBean(AutoServiceRegistrationProperties.class)
public PolarisRegistration polarisRegistration(PolarisDiscoveryProperties polarisDiscoveryProperties, public PolarisRegistration polarisRegistration(
SDKContext context) { DiscoveryPropertiesAutoConfiguration discoveryPropertiesAutoConfiguration,
return new PolarisRegistration(polarisDiscoveryProperties, context); PolarisDiscoveryProperties polarisDiscoveryProperties, SDKContext context) {
return new PolarisRegistration(discoveryPropertiesAutoConfiguration, polarisDiscoveryProperties, context);
} }
@Bean @Bean

@ -0,0 +1,45 @@
/*
* 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.registry;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
/**
* Condition for checking if register enabled.
*
* @author Haotian Zhang
*/
public class RegisterEnabledCondition implements Condition {
@Override
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
boolean isRegisterEnabled = Boolean.parseBoolean(
conditionContext.getEnvironment().getProperty("spring.cloud.polaris.discovery.register", "true"));
boolean isConsulRegisterEnabled = Boolean
.parseBoolean(conditionContext.getEnvironment().getProperty("spring.cloud.consul.enabled", "false"))
&& Boolean.parseBoolean(conditionContext.getEnvironment()
.getProperty("spring.cloud.consul.discovery.register", "true"));
isRegisterEnabled |= isConsulRegisterEnabled;
return isRegisterEnabled;
}
}

@ -18,6 +18,12 @@
"defaultValue": true, "defaultValue": true,
"description": "enable polaris discovery or not." "description": "enable polaris discovery or not."
}, },
{
"name": "spring.cloud.polaris.discovery.register",
"type": "java.lang.Boolean",
"defaultValue": true,
"description": "enable polaris registration or not."
},
{ {
"name": "spring.cloud.polaris.discovery.health-check-url", "name": "spring.cloud.polaris.discovery.health-check-url",
"type": "java.lang.String", "type": "java.lang.String",

@ -1,3 +1,6 @@
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.tencent.cloud.polaris.DiscoveryPropertiesAutoConfiguration,\
com.tencent.cloud.polaris.discovery.PolarisDiscoveryAutoConfiguration,\ com.tencent.cloud.polaris.discovery.PolarisDiscoveryAutoConfiguration,\
com.tencent.cloud.polaris.registry.PolarisServiceRegistryAutoConfiguration com.tencent.cloud.polaris.registry.PolarisServiceRegistryAutoConfiguration
org.springframework.cloud.bootstrap.BootstrapConfiguration=\
com.tencent.cloud.polaris.DiscoveryPropertiesBootstrapAutoConfiguration

@ -19,7 +19,7 @@
package com.tencent.cloud.polaris.discovery; package com.tencent.cloud.polaris.discovery;
import com.tencent.cloud.polaris.PolarisDiscoveryProperties; import com.tencent.cloud.polaris.PolarisDiscoveryProperties;
import com.tencent.cloud.polaris.context.PolarisContextConfiguration; import com.tencent.cloud.polaris.context.PolarisContextAutoConfiguration;
import com.tencent.polaris.api.core.ConsumerAPI; import com.tencent.polaris.api.core.ConsumerAPI;
import com.tencent.polaris.api.core.ProviderAPI; import com.tencent.polaris.api.core.ProviderAPI;
import com.tencent.polaris.test.mock.discovery.NamingServer; import com.tencent.polaris.test.mock.discovery.NamingServer;
@ -47,9 +47,9 @@ public class PolarisDiscoveryAutoConfigurationTest {
private static NamingServer namingServer; private static NamingServer namingServer;
private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.withConfiguration( .withConfiguration(AutoConfigurations.of(PolarisContextAutoConfiguration.class,
AutoConfigurations.of(PolarisContextConfiguration.class, PolarisDiscoveryAutoConfiguration.class, PolarisDiscoveryAutoConfiguration.class, PolarisDiscoveryClientConfiguration.class,
PolarisDiscoveryClientConfiguration.class, PolarisContextConfiguration.class)) PolarisContextAutoConfiguration.class))
.withPropertyValues("spring.application.name=" + SERVICE_PROVIDER).withPropertyValues("server.port=" + PORT) .withPropertyValues("spring.application.name=" + SERVICE_PROVIDER).withPropertyValues("server.port=" + PORT)
.withPropertyValues("spring.cloud.polaris.address=grpc://127.0.0.1:10081"); .withPropertyValues("spring.cloud.polaris.address=grpc://127.0.0.1:10081");

@ -17,7 +17,7 @@
package com.tencent.cloud.polaris.discovery; package com.tencent.cloud.polaris.discovery;
import com.tencent.cloud.polaris.context.PolarisContextConfiguration; import com.tencent.cloud.polaris.context.PolarisContextAutoConfiguration;
import com.tencent.polaris.test.mock.discovery.NamingServer; import com.tencent.polaris.test.mock.discovery.NamingServer;
import org.junit.AfterClass; import org.junit.AfterClass;
import org.junit.BeforeClass; import org.junit.BeforeClass;
@ -43,8 +43,8 @@ public class PolarisDiscoveryClientConfigurationTest {
private static NamingServer namingServer; private static NamingServer namingServer;
private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(PolarisContextConfiguration.class, .withConfiguration(AutoConfigurations.of(PolarisContextAutoConfiguration.class,
PolarisDiscoveryClientConfiguration.class, PolarisContextConfiguration.class)) PolarisDiscoveryClientConfiguration.class, PolarisContextAutoConfiguration.class))
.withPropertyValues("spring.application.name=" + SERVICE_PROVIDER).withPropertyValues("server.port=" + PORT) .withPropertyValues("spring.application.name=" + SERVICE_PROVIDER).withPropertyValues("server.port=" + PORT)
.withPropertyValues("spring.cloud.polaris.address=grpc://127.0.0.1:10081"); .withPropertyValues("spring.cloud.polaris.address=grpc://127.0.0.1:10081");

@ -19,7 +19,7 @@ package com.tencent.cloud.polaris.discovery;
import java.util.List; import java.util.List;
import com.tencent.cloud.polaris.context.PolarisContextConfiguration; import com.tencent.cloud.polaris.context.PolarisContextAutoConfiguration;
import com.tencent.polaris.api.exception.PolarisException; import com.tencent.polaris.api.exception.PolarisException;
import com.tencent.polaris.api.pojo.ServiceKey; import com.tencent.polaris.api.pojo.ServiceKey;
import com.tencent.polaris.test.mock.discovery.NamingServer; import com.tencent.polaris.test.mock.discovery.NamingServer;
@ -50,10 +50,10 @@ public class PolarisServiceDiscoveryTest {
private static NamingServer namingServer; private static NamingServer namingServer;
private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(PolarisContextConfiguration.class, .withConfiguration(AutoConfigurations.of(PolarisContextAutoConfiguration.class,
PolarisServiceDiscoveryTest.PolarisPropertiesConfiguration.class, PolarisServiceDiscoveryTest.PolarisPropertiesConfiguration.class,
PolarisDiscoveryClientConfiguration.class, PolarisDiscoveryAutoConfiguration.class, PolarisDiscoveryClientConfiguration.class, PolarisDiscoveryAutoConfiguration.class,
PolarisContextConfiguration.class)) PolarisContextAutoConfiguration.class))
.withPropertyValues("spring.application.name=" + SERVICE_PROVIDER).withPropertyValues("server.port=" + PORT) .withPropertyValues("spring.application.name=" + SERVICE_PROVIDER).withPropertyValues("server.port=" + PORT)
.withPropertyValues("spring.cloud.polaris.address=grpc://127.0.0.1:10081") .withPropertyValues("spring.cloud.polaris.address=grpc://127.0.0.1:10081")
.withPropertyValues("spring.cloud.polaris.discovery.namespace=" + NAMESPACE_TEST) .withPropertyValues("spring.cloud.polaris.discovery.namespace=" + NAMESPACE_TEST)

@ -17,7 +17,7 @@
package com.tencent.cloud.polaris.discovery.reactive; package com.tencent.cloud.polaris.discovery.reactive;
import com.tencent.cloud.polaris.context.PolarisContextConfiguration; import com.tencent.cloud.polaris.context.PolarisContextAutoConfiguration;
import com.tencent.cloud.polaris.discovery.PolarisDiscoveryClientConfiguration; import com.tencent.cloud.polaris.discovery.PolarisDiscoveryClientConfiguration;
import com.tencent.polaris.test.mock.discovery.NamingServer; import com.tencent.polaris.test.mock.discovery.NamingServer;
import org.junit.AfterClass; import org.junit.AfterClass;
@ -44,9 +44,9 @@ public class PolarisReactiveDiscoveryClientConfigurationTest {
private static NamingServer namingServer; private static NamingServer namingServer;
private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(PolarisContextConfiguration.class, .withConfiguration(AutoConfigurations.of(PolarisContextAutoConfiguration.class,
PolarisReactiveDiscoveryClientConfiguration.class, PolarisDiscoveryClientConfiguration.class, PolarisReactiveDiscoveryClientConfiguration.class, PolarisDiscoveryClientConfiguration.class,
PolarisContextConfiguration.class)) PolarisContextAutoConfiguration.class))
.withPropertyValues("spring.application.name=" + SERVICE_PROVIDER).withPropertyValues("server.port=" + PORT) .withPropertyValues("spring.application.name=" + SERVICE_PROVIDER).withPropertyValues("server.port=" + PORT)
.withPropertyValues("spring.cloud.polaris.address=grpc://127.0.0.1:10081"); .withPropertyValues("spring.cloud.polaris.address=grpc://127.0.0.1:10081");

@ -17,7 +17,7 @@
package com.tencent.cloud.polaris.registry; package com.tencent.cloud.polaris.registry;
import com.tencent.cloud.polaris.context.PolarisContextConfiguration; import com.tencent.cloud.polaris.context.PolarisContextAutoConfiguration;
import com.tencent.cloud.polaris.discovery.PolarisDiscoveryAutoConfiguration; import com.tencent.cloud.polaris.discovery.PolarisDiscoveryAutoConfiguration;
import com.tencent.cloud.polaris.discovery.PolarisDiscoveryClientConfiguration; import com.tencent.cloud.polaris.discovery.PolarisDiscoveryClientConfiguration;
import com.tencent.polaris.test.mock.discovery.NamingServer; import com.tencent.polaris.test.mock.discovery.NamingServer;
@ -46,7 +46,7 @@ public class PolarisServiceRegistryAutoConfigurationTest {
private static NamingServer namingServer; private static NamingServer namingServer;
private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(PolarisContextConfiguration.class, .withConfiguration(AutoConfigurations.of(PolarisContextAutoConfiguration.class,
PolarisServiceRegistryAutoConfiguration.class, PolarisDiscoveryClientConfiguration.class)) PolarisServiceRegistryAutoConfiguration.class, PolarisDiscoveryClientConfiguration.class))
.withPropertyValues("spring.application.name=" + SERVICE_PROVIDER).withPropertyValues("server.port=" + PORT) .withPropertyValues("spring.application.name=" + SERVICE_PROVIDER).withPropertyValues("server.port=" + PORT)
.withPropertyValues("spring.cloud.polaris.address=grpc://127.0.0.1:10081"); .withPropertyValues("spring.cloud.polaris.address=grpc://127.0.0.1:10081");

@ -17,7 +17,7 @@
package com.tencent.cloud.polaris.registry; package com.tencent.cloud.polaris.registry;
import com.tencent.cloud.polaris.context.PolarisContextConfiguration; import com.tencent.cloud.polaris.context.PolarisContextAutoConfiguration;
import com.tencent.cloud.polaris.discovery.PolarisDiscoveryAutoConfiguration; import com.tencent.cloud.polaris.discovery.PolarisDiscoveryAutoConfiguration;
import com.tencent.cloud.polaris.discovery.PolarisDiscoveryClientConfiguration; import com.tencent.cloud.polaris.discovery.PolarisDiscoveryClientConfiguration;
import com.tencent.polaris.api.pojo.ServiceKey; import com.tencent.polaris.api.pojo.ServiceKey;
@ -51,7 +51,7 @@ public class PolarisServiceRegistryTest {
private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.withConfiguration( .withConfiguration(
AutoConfigurations.of(PolarisContextConfiguration.class, PolarisPropertiesConfiguration.class, AutoConfigurations.of(PolarisContextAutoConfiguration.class, PolarisPropertiesConfiguration.class,
PolarisDiscoveryClientConfiguration.class, PolarisDiscoveryAutoConfiguration.class)) PolarisDiscoveryClientConfiguration.class, PolarisDiscoveryAutoConfiguration.class))
.withPropertyValues("spring.application.name=" + SERVICE_PROVIDER).withPropertyValues("server.port=" + PORT) .withPropertyValues("spring.application.name=" + SERVICE_PROVIDER).withPropertyValues("server.port=" + PORT)
.withPropertyValues("spring.cloud.polaris.address=grpc://127.0.0.1:10081") .withPropertyValues("spring.cloud.polaris.address=grpc://127.0.0.1:10081")

@ -13,11 +13,11 @@
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * 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 * CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License. * specific language governing permissions and limitations under the License.
*
*/ */
package com.tencent.cloud.polaris.ratelimit.config; package com.tencent.cloud.polaris.ratelimit.config;
import com.tencent.cloud.polaris.context.ConditionalOnPolarisEnabled;
import com.tencent.cloud.polaris.ratelimit.constant.RateLimitConstant; import com.tencent.cloud.polaris.ratelimit.constant.RateLimitConstant;
import com.tencent.cloud.polaris.ratelimit.filter.QuotaCheckReactiveFilter; import com.tencent.cloud.polaris.ratelimit.filter.QuotaCheckReactiveFilter;
import com.tencent.cloud.polaris.ratelimit.filter.QuotaCheckServletFilter; import com.tencent.cloud.polaris.ratelimit.filter.QuotaCheckServletFilter;
@ -45,6 +45,7 @@ import static javax.servlet.DispatcherType.REQUEST;
* @author Haotian Zhang * @author Haotian Zhang
*/ */
@Configuration @Configuration
@ConditionalOnPolarisEnabled
@ConditionalOnProperty(name = "spring.cloud.polaris.ratelimit.enabled", matchIfMissing = true) @ConditionalOnProperty(name = "spring.cloud.polaris.ratelimit.enabled", matchIfMissing = true)
public class RateLimitConfiguration { public class RateLimitConfiguration {

@ -59,8 +59,7 @@ public class QuotaCheckReactiveFilter implements WebFilter, Ordered {
private final PolarisRateLimiterLabelReactiveResolver labelResolver; private final PolarisRateLimiterLabelReactiveResolver labelResolver;
public QuotaCheckReactiveFilter(LimitAPI limitAPI, public QuotaCheckReactiveFilter(LimitAPI limitAPI, PolarisRateLimiterLabelReactiveResolver labelResolver) {
PolarisRateLimiterLabelReactiveResolver labelResolver) {
this.limitAPI = limitAPI; this.limitAPI = limitAPI;
this.labelResolver = labelResolver; this.labelResolver = labelResolver;
} }
@ -90,21 +89,22 @@ public class QuotaCheckReactiveFilter implements WebFilter, Ordered {
if (!CollectionUtils.isEmpty(customLabels)) { if (!CollectionUtils.isEmpty(customLabels)) {
labels.putAll(customLabels); labels.putAll(customLabels);
} }
} catch (Throwable e) { }
catch (Throwable e) {
LOG.error("resolve custom label failed. resolver = {}", labelResolver.getClass().getName(), e); LOG.error("resolve custom label failed. resolver = {}", labelResolver.getClass().getName(), e);
} }
} }
try { try {
QuotaResponse quotaResponse = QuotaCheckUtils.getQuota(limitAPI, QuotaResponse quotaResponse = QuotaCheckUtils.getQuota(limitAPI, localNamespace, localService, 1, labels,
localNamespace, localService, 1, labels, null); null);
if (quotaResponse.getCode() == QuotaResultCode.QuotaResultLimited) { if (quotaResponse.getCode() == QuotaResultCode.QuotaResultLimited) {
ServerHttpResponse response = exchange.getResponse(); ServerHttpResponse response = exchange.getResponse();
response.setStatusCode(HttpStatus.TOO_MANY_REQUESTS); response.setStatusCode(HttpStatus.TOO_MANY_REQUESTS);
response.getHeaders().setContentType(MediaType.APPLICATION_JSON); response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
DataBuffer dataBuffer = response.bufferFactory().allocateBuffer().write( DataBuffer dataBuffer = response.bufferFactory().allocateBuffer()
RateLimitConstant.QUOTA_LIMITED_INFO.getBytes(StandardCharsets.UTF_8)); .write(RateLimitConstant.QUOTA_LIMITED_INFO.getBytes(StandardCharsets.UTF_8));
return response.writeWith(Mono.just(dataBuffer)); return response.writeWith(Mono.just(dataBuffer));
} }
} }

@ -56,6 +56,7 @@ public class QuotaCheckServletFilter extends OncePerRequestFilter {
private static final Logger LOG = LoggerFactory.getLogger(QuotaCheckServletFilter.class); private static final Logger LOG = LoggerFactory.getLogger(QuotaCheckServletFilter.class);
private final LimitAPI limitAPI; private final LimitAPI limitAPI;
private final PolarisRateLimiterLabelServletResolver labelResolver; private final PolarisRateLimiterLabelServletResolver labelResolver;
public QuotaCheckServletFilter(LimitAPI limitAPI, PolarisRateLimiterLabelServletResolver labelResolver) { public QuotaCheckServletFilter(LimitAPI limitAPI, PolarisRateLimiterLabelServletResolver labelResolver) {
@ -85,7 +86,8 @@ public class QuotaCheckServletFilter extends OncePerRequestFilter {
if (!CollectionUtils.isEmpty(customLabels)) { if (!CollectionUtils.isEmpty(customLabels)) {
labels.putAll(customLabels); labels.putAll(customLabels);
} }
} catch (Throwable e) { }
catch (Throwable e) {
LOG.error("resolve custom label failed. resolver = {}", labelResolver.getClass().getName(), e); LOG.error("resolve custom label failed. resolver = {}", labelResolver.getClass().getName(), e);
} }
} }

@ -31,7 +31,6 @@ public interface PolarisRateLimiterLabelReactiveResolver {
/** /**
* Resolve custom label from request. * Resolve custom label from request.
*
* @param exchange the http request * @param exchange the http request
* @return resolved labels * @return resolved labels
*/ */

@ -31,7 +31,6 @@ public interface PolarisRateLimiterLabelServletResolver {
/** /**
* Resolve custom label from request. * Resolve custom label from request.
*
* @param request the http request * @param request the http request
* @return resolved labels * @return resolved labels
*/ */

@ -17,6 +17,7 @@
package com.tencent.cloud.polaris.router.config; package com.tencent.cloud.polaris.router.config;
import com.tencent.cloud.polaris.context.ConditionalOnPolarisEnabled;
import com.tencent.polaris.api.exception.PolarisException; import com.tencent.polaris.api.exception.PolarisException;
import com.tencent.polaris.client.api.SDKContext; import com.tencent.polaris.client.api.SDKContext;
import com.tencent.polaris.factory.api.RouterAPIFactory; import com.tencent.polaris.factory.api.RouterAPIFactory;
@ -32,12 +33,13 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
/** /**
* Autoconfiguration of loadbalancer of Polaris. * Auto-configuration of loadbalancer for Polaris.
* *
* @author Haotian Zhang, Andrew Shan, Jie Cheng * @author Haotian Zhang
*/ */
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties @EnableConfigurationProperties
@ConditionalOnPolarisEnabled
@ConditionalOnProperty(value = "spring.cloud.polaris.loadbalancer.enabled", matchIfMissing = true) @ConditionalOnProperty(value = "spring.cloud.polaris.loadbalancer.enabled", matchIfMissing = true)
@AutoConfigureAfter(LoadBalancerAutoConfiguration.class) @AutoConfigureAfter(LoadBalancerAutoConfiguration.class)
@LoadBalancerClients(defaultConfiguration = PolarisLoadBalancerClientConfiguration.class) @LoadBalancerClients(defaultConfiguration = PolarisLoadBalancerClientConfiguration.class)

@ -0,0 +1,60 @@
/*
* 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.router.config;
import com.tencent.cloud.polaris.context.PolarisContextAutoConfiguration;
import com.tencent.polaris.router.api.core.RouterAPI;
import org.junit.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Configuration;
import static com.tencent.polaris.test.common.Consts.PORT;
import static com.tencent.polaris.test.common.Consts.SERVICE_PROVIDER;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Test for {@link PolarisLoadBalancerAutoConfiguration}
*
* @author Haotian Zhang
*/
public class PolarisLoadBalancerAutoConfigurationTest {
private ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(PolarisRibbonTest.class,
PolarisLoadBalancerAutoConfiguration.class, PolarisContextAutoConfiguration.class))
.withPropertyValues("spring.application.name=" + SERVICE_PROVIDER).withPropertyValues("server.port=" + PORT)
.withPropertyValues("spring.cloud.polaris.address=grpc://127.0.0.1:10081");
@Test
public void testDefaultInitialization() {
this.contextRunner.run(context -> {
assertThat(context).hasSingleBean(RouterAPI.class);
assertThat(context).hasSingleBean(PolarisLoadBalancerProperties.class);
});
}
@Configuration
@EnableAutoConfiguration
static class PolarisRibbonTest {
}
}

@ -17,7 +17,7 @@
package com.tencent.cloud.polaris.router.config; package com.tencent.cloud.polaris.router.config;
import com.tencent.cloud.polaris.context.PolarisContextConfiguration; import com.tencent.cloud.polaris.context.PolarisContextAutoConfiguration;
import com.tencent.cloud.polaris.router.PolarisRouterServiceInstanceListSupplier; import com.tencent.cloud.polaris.router.PolarisRouterServiceInstanceListSupplier;
import com.tencent.polaris.router.api.core.RouterAPI; import com.tencent.polaris.router.api.core.RouterAPI;
import org.junit.Test; import org.junit.Test;
@ -37,14 +37,14 @@ import static org.assertj.core.api.Assertions.assertThat;
public class PolarisRouterAutoConfigurationTest { public class PolarisRouterAutoConfigurationTest {
private final ApplicationContextRunner blockingContextRunner = new ApplicationContextRunner() private final ApplicationContextRunner blockingContextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(PolarisLoadBalancerTest.class, PolarisContextConfiguration.class, .withConfiguration(AutoConfigurations.of(PolarisLoadBalancerTest.class,
PolarisLoadBalancerAutoConfiguration.class, PolarisContextAutoConfiguration.class, PolarisLoadBalancerAutoConfiguration.class,
PolarisLoadBalancerClientConfiguration.PolarisBlockingSupportConfiguration.class)) PolarisLoadBalancerClientConfiguration.PolarisBlockingSupportConfiguration.class))
.withPropertyValues("spring.cloud.loadbalancer.configurations=polaris"); .withPropertyValues("spring.cloud.loadbalancer.configurations=polaris");
private final ApplicationContextRunner noPolarisContextRunner = new ApplicationContextRunner() private final ApplicationContextRunner noPolarisContextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(PolarisLoadBalancerTest.class, PolarisContextConfiguration.class, .withConfiguration(AutoConfigurations.of(PolarisLoadBalancerTest.class,
PolarisLoadBalancerAutoConfiguration.class, PolarisContextAutoConfiguration.class, PolarisLoadBalancerAutoConfiguration.class,
PolarisLoadBalancerClientConfiguration.PolarisBlockingSupportConfiguration.class)); PolarisLoadBalancerClientConfiguration.PolarisBlockingSupportConfiguration.class));
/** /**

@ -24,8 +24,7 @@ import java.util.concurrent.ConcurrentHashMap;
import com.tencent.cloud.common.util.ApplicationContextAwareUtils; import com.tencent.cloud.common.util.ApplicationContextAwareUtils;
import com.tencent.cloud.common.util.JacksonUtils; import com.tencent.cloud.common.util.JacksonUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.StringUtils;
/** /**
* Metadata Context. * Metadata Context.
@ -44,32 +43,32 @@ public class MetadataContext {
*/ */
public static String LOCAL_SERVICE; public static String LOCAL_SERVICE;
/**
* Transitive custom metadata content.
*/
private final Map<String, String> transitiveCustomMetadata;
/**
* System metadata content.
*/
private final Map<String, String> systemMetadata;
static { static {
String namespace = ApplicationContextAwareUtils.getProperties("spring.cloud.polaris.namespace"); String namespace = ApplicationContextAwareUtils.getProperties("spring.cloud.polaris.namespace");
if (StringUtils.isEmpty(namespace)) { if (StringUtils.isBlank(namespace)) {
namespace = ApplicationContextAwareUtils.getProperties("spring.cloud.polaris.discovery.namespace", "default"); namespace = ApplicationContextAwareUtils.getProperties("spring.cloud.polaris.discovery.namespace",
"default");
} }
LOCAL_NAMESPACE = namespace; LOCAL_NAMESPACE = namespace;
String serviceName = ApplicationContextAwareUtils.getProperties("spring.cloud.polaris.service"); String serviceName = ApplicationContextAwareUtils.getProperties("spring.cloud.polaris.service");
if (StringUtils.isEmpty(serviceName)) { if (StringUtils.isBlank(serviceName)) {
serviceName = ApplicationContextAwareUtils.getProperties( serviceName = ApplicationContextAwareUtils.getProperties("spring.cloud.polaris.discovery.service",
"spring.cloud.polaris.discovery.service",
ApplicationContextAwareUtils.getProperties("spring.application.name", null)); ApplicationContextAwareUtils.getProperties("spring.application.name", null));
} }
LOCAL_SERVICE = serviceName; LOCAL_SERVICE = serviceName;
} }
/**
* Transitive custom metadata content.
*/
private final Map<String, String> transitiveCustomMetadata;
/**
* System metadata content.
*/
private final Map<String, String> systemMetadata;
public MetadataContext() { public MetadataContext() {
this.transitiveCustomMetadata = new ConcurrentHashMap<>(); this.transitiveCustomMetadata = new ConcurrentHashMap<>();
this.systemMetadata = new ConcurrentHashMap<>(); this.systemMetadata = new ConcurrentHashMap<>();

@ -48,10 +48,9 @@ public class MetadataAutoConfigurationTest {
public void test1() { public void test1() {
this.applicationContextRunner.withConfiguration(AutoConfigurations.of(MetadataAutoConfiguration.class)) this.applicationContextRunner.withConfiguration(AutoConfigurations.of(MetadataAutoConfiguration.class))
.run(context -> { .run(context -> {
Assertions.assertThat(context).hasSingleBean(MetadataLocalProperties.class);
Assertions.assertThat(context) Assertions.assertThat(context)
.hasSingleBean(MetadataLocalProperties.class); .hasSingleBean(MetadataAutoConfiguration.MetadataFeignInterceptorConfig.class);
Assertions.assertThat(context).hasSingleBean(
MetadataAutoConfiguration.MetadataFeignInterceptorConfig.class);
Assertions.assertThat(context) Assertions.assertThat(context)
.hasSingleBean(MetadataAutoConfiguration.MetadataFeignInterceptorConfig.class); .hasSingleBean(MetadataAutoConfiguration.MetadataFeignInterceptorConfig.class);
Assertions.assertThat(context).hasSingleBean(MetadataFirstFeignInterceptor.class); Assertions.assertThat(context).hasSingleBean(MetadataFirstFeignInterceptor.class);
@ -68,10 +67,9 @@ public class MetadataAutoConfigurationTest {
public void test2() { public void test2() {
this.webApplicationContextRunner.withConfiguration(AutoConfigurations.of(MetadataAutoConfiguration.class)) this.webApplicationContextRunner.withConfiguration(AutoConfigurations.of(MetadataAutoConfiguration.class))
.run(context -> { .run(context -> {
Assertions.assertThat(context).hasSingleBean(MetadataLocalProperties.class);
Assertions.assertThat(context) Assertions.assertThat(context)
.hasSingleBean(MetadataLocalProperties.class); .hasSingleBean(MetadataAutoConfiguration.MetadataFeignInterceptorConfig.class);
Assertions.assertThat(context).hasSingleBean(
MetadataAutoConfiguration.MetadataFeignInterceptorConfig.class);
Assertions.assertThat(context) Assertions.assertThat(context)
.hasSingleBean(MetadataAutoConfiguration.MetadataFeignInterceptorConfig.class); .hasSingleBean(MetadataAutoConfiguration.MetadataFeignInterceptorConfig.class);
Assertions.assertThat(context).hasSingleBean(MetadataFirstFeignInterceptor.class); Assertions.assertThat(context).hasSingleBean(MetadataFirstFeignInterceptor.class);
@ -88,11 +86,10 @@ public class MetadataAutoConfigurationTest {
public void test3() { public void test3() {
this.reactiveWebApplicationContextRunner this.reactiveWebApplicationContextRunner
.withConfiguration(AutoConfigurations.of(MetadataAutoConfiguration.class)).run(context -> { .withConfiguration(AutoConfigurations.of(MetadataAutoConfiguration.class)).run(context -> {
Assertions.assertThat(context).hasSingleBean(MetadataLocalProperties.class);
Assertions.assertThat(context).hasSingleBean(MetadataLocalProperties.class); Assertions.assertThat(context).hasSingleBean(MetadataLocalProperties.class);
Assertions.assertThat(context) Assertions.assertThat(context)
.hasSingleBean(MetadataLocalProperties.class); .hasSingleBean(MetadataAutoConfiguration.MetadataFeignInterceptorConfig.class);
Assertions.assertThat(context).hasSingleBean(
MetadataAutoConfiguration.MetadataFeignInterceptorConfig.class);
Assertions.assertThat(context) Assertions.assertThat(context)
.hasSingleBean(MetadataAutoConfiguration.MetadataScgFilterConfig.class); .hasSingleBean(MetadataAutoConfiguration.MetadataScgFilterConfig.class);
Assertions.assertThat(context).hasSingleBean(MetadataFirstScgFilter.class); Assertions.assertThat(context).hasSingleBean(MetadataFirstScgFilter.class);

@ -46,6 +46,14 @@
<url>https://github.com/SkyeBeFreeman/</url> <url>https://github.com/SkyeBeFreeman/</url>
</developer> </developer>
<developer>
<id>lepdou</id>
<name>lepdou</name>
<email>lepdou@126.com</email>
<organization>Tencent</organization>
<url>https://github.com/lepdou</url>
</developer>
<developer> <developer>
<name>Andrew Shan</name> <name>Andrew Shan</name>
<email>samshan08@126.com</email> <email>samshan08@126.com</email>
@ -63,7 +71,7 @@
<properties> <properties>
<revision>1.3.0-2020.0.5-SNAPSHOT</revision> <revision>1.3.0-2020.0.5-SNAPSHOT</revision>
<polaris.version>1.3.1</polaris.version> <polaris.version>1.4.0-SNAPSHOT</polaris.version>
<powermock.version>2.0.0</powermock.version> <powermock.version>2.0.0</powermock.version>
<!-- Maven Plugin Versions --> <!-- Maven Plugin Versions -->

@ -7,6 +7,9 @@ spring:
polaris: polaris:
address: grpc://127.0.0.1:8091 address: grpc://127.0.0.1:8091
namespace: default namespace: default
enabled: true
circuitbreaker:
enabled: true
feign: feign:
circuitbreaker: circuitbreaker:
enabled: true enabled: true

@ -7,4 +7,5 @@ spring:
polaris: polaris:
address: grpc://127.0.0.1:8091 address: grpc://127.0.0.1:8091
namespace: default namespace: default
enabled: true
is-throw-runtime-exception: false is-throw-runtime-exception: false

@ -7,4 +7,5 @@ spring:
polaris: polaris:
address: grpc://127.0.0.1:8091 address: grpc://127.0.0.1:8091
namespace: default namespace: default
enabled: true
is-throw-runtime-exception: true is-throw-runtime-exception: true

@ -7,14 +7,18 @@ spring:
polaris: polaris:
address: grpc://127.0.0.1:8091 address: grpc://127.0.0.1:8091
namespace: default namespace: default
enabled: true
discovery:
enabled: true
register: true
# consul: # consul:
# port: 8500 # port: 8500
# host: 127.0.0.1 # host: 127.0.0.1
# enabled: true # enabled: true
# discovery: # discovery:
# enabled: true
# register: true # register: true
# instance-id: ${spring.application.name}:${spring.cloud.client.ip-address}:${server.port} # instance-id: ${spring.application.name}:${spring.cloud.client.ip-address}:${server.port}
# enabled: true
# service-name: ${spring.application.name} # service-name: ${spring.application.name}
# ip-address: localhost # ip-address: localhost
# prefer-ip-address: true # prefer-ip-address: true

@ -5,12 +5,13 @@ spring:
application: application:
name: DiscoveryCallerService name: DiscoveryCallerService
cloud: cloud:
loadbalancer:
configurations: polaris
polaris: polaris:
address: grpc://127.0.0.1:8091 address: grpc://127.0.0.1:8091
namespace: default namespace: default
enabled: true
discovery: discovery:
enabled: true
register: true
heartbeat: heartbeat:
enabled: true enabled: true
health-check-url: /discovery/service/caller/healthCheck health-check-url: /discovery/service/caller/healthCheck
@ -19,11 +20,11 @@ spring:
# host: 127.0.0.1 # host: 127.0.0.1
# enabled: true # enabled: true
# discovery: # discovery:
# enabled: true
# register: true # register: true
# health-check-path: /actuator/health # health-check-path: /actuator/health
# health-check-interval: 10s # health-check-interval: 10s
# instance-id: ${spring.application.name}:${server.port} # instance-id: ${spring.application.name}:${server.port}
# enabled: true
# service-name: ${spring.application.name} # service-name: ${spring.application.name}
# ip-address: localhost # ip-address: localhost
# prefer-ip-address: true # prefer-ip-address: true

@ -14,6 +14,7 @@ spring:
polaris: polaris:
address: grpc://127.0.0.1:8091 address: grpc://127.0.0.1:8091
namespace: default namespace: default
enabled: true
gateway: gateway:
discovery: discovery:
locator: locator:

@ -44,4 +44,5 @@ public class CustomLabelResolver implements PolarisRateLimiterLabelServletResolv
return labels; return labels;
} }
} }

@ -7,3 +7,6 @@ spring:
polaris: polaris:
address: grpc://127.0.0.1:8091 address: grpc://127.0.0.1:8091
namespace: default namespace: default
enabled: true
ratelimit:
enabled: true

@ -23,6 +23,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
/** /**
* Router callee application. * Router callee application.
*
* @author lepdou 2022-04-06 * @author lepdou 2022-04-06
*/ */
@SpringBootApplication @SpringBootApplication
@ -31,4 +32,5 @@ public class RouterCalleeApplication1 {
public static void main(String[] args) { public static void main(String[] args) {
SpringApplication.run(RouterCalleeApplication1.class, args); SpringApplication.run(RouterCalleeApplication1.class, args);
} }
} }

@ -49,4 +49,5 @@ public class RouterCalleeController {
LOG.info("Discovery Service Callee [{}] is called.", port); LOG.info("Discovery Service Callee [{}] is called.", port);
return String.format("Discovery Service Callee [%s] is called.", port); return String.format("Discovery Service Callee [%s] is called.", port);
} }
} }

@ -11,3 +11,4 @@ spring:
polaris: polaris:
address: grpc://127.0.0.1:8091 address: grpc://127.0.0.1:8091
namespace: default namespace: default
enabled: true

@ -23,6 +23,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
/** /**
* Router callee application. * Router callee application.
*
* @author lepdou 2022-04-06 * @author lepdou 2022-04-06
*/ */
@SpringBootApplication @SpringBootApplication
@ -31,4 +32,5 @@ public class RouterCalleeApplication2 {
public static void main(String[] args) { public static void main(String[] args) {
SpringApplication.run(RouterCalleeApplication2.class, args); SpringApplication.run(RouterCalleeApplication2.class, args);
} }
} }

@ -11,3 +11,4 @@ spring:
polaris: polaris:
address: grpc://127.0.0.1:8091 address: grpc://127.0.0.1:8091
namespace: default namespace: default
enabled: true

@ -45,4 +45,5 @@ public class RouterCallerApplication {
public RestTemplate restTemplate() { public RestTemplate restTemplate() {
return new RestTemplate(); return new RestTemplate();
} }
} }

@ -54,9 +54,7 @@ public class RouterCallerController {
*/ */
@GetMapping("/rest") @GetMapping("/rest")
public String rest() { public String rest() {
return restTemplate.getForObject( return restTemplate.getForObject("http://DiscoveryCalleeService/discovery/service/callee/info", String.class);
"http://DiscoveryCalleeService/discovery/service/callee/info",
String.class);
} }
/** /**

@ -9,3 +9,6 @@ spring:
polaris: polaris:
address: grpc://127.0.0.1:8091 address: grpc://127.0.0.1:8091
namespace: default namespace: default
enabled: true
loadbalancer:
enabled: true

@ -0,0 +1,37 @@
/*
* 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 java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
/**
* Condition that if Polaris enabled.
*
* @author Haotian Zhang
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
@ConditionalOnProperty(value = "spring.cloud.polaris.enabled", matchIfMissing = true)
public @interface ConditionalOnPolarisEnabled {
}

@ -26,12 +26,13 @@ import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
/** /**
* Configuration for Polaris {@link SDKContext}. * Autoconfiguration for Polaris {@link SDKContext}.
* *
* @author Haotian Zhang * @author Haotian Zhang
*/ */
@ConditionalOnPolarisEnabled
@EnableConfigurationProperties({ PolarisContextProperties.class }) @EnableConfigurationProperties({ PolarisContextProperties.class })
public class PolarisContextConfiguration { public class PolarisContextAutoConfiguration {
@Bean(name = "polarisContext", initMethod = "init", destroyMethod = "destroy") @Bean(name = "polarisContext", initMethod = "init", destroyMethod = "destroy")
@ConditionalOnMissingBean @ConditionalOnMissingBean

@ -0,0 +1,35 @@
/*
* 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.polaris.client.api.SDKContext;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Import;
/**
* Bootstrap autoconfiguration for Polaris {@link SDKContext}.
*
* @author Haotian Zhang
*/
@ConditionalOnProperty("spring.cloud.polaris.enabled")
@Import(PolarisContextAutoConfiguration.class)
public class PolarisContextBootstrapAutoConfiguration {
}

@ -52,6 +52,11 @@ public class PolarisContextProperties {
*/ */
private String localIpAddress; private String localIpAddress;
/**
* If polaris enabled.
*/
private Boolean enabled;
/** /**
* polaris namespace. * polaris namespace.
*/ */
@ -108,6 +113,14 @@ public class PolarisContextProperties {
this.localIpAddress = localIpAddress; this.localIpAddress = localIpAddress;
} }
public Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public String getNamespace() { public String getNamespace() {
return namespace; return namespace;
} }
@ -123,4 +136,5 @@ public class PolarisContextProperties {
void setService(String service) { void setService(String service) {
this.service = service; this.service = service;
} }
} }

@ -27,6 +27,13 @@
"default": "${spring.application.name}", "default": "${spring.application.name}",
"sourceType": "com.tencent.cloud.polaris.context.PolarisContextProperties" "sourceType": "com.tencent.cloud.polaris.context.PolarisContextProperties"
}, },
{
"name": "spring.cloud.polaris.enabled",
"type": "java.lang.Boolean",
"description": "polaris enabled",
"default": "true",
"sourceType": "com.tencent.cloud.polaris.context.PolarisContextProperties"
},
{ {
"name": "spring.cloud.polaris.local-ip-address", "name": "spring.cloud.polaris.local-ip-address",
"type": "java.lang.String", "type": "java.lang.String",

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

@ -28,11 +28,11 @@ import org.springframework.cloud.commons.util.UtilAutoConfiguration;
/** /**
* @author <a href="mailto:liaochuntao@live.com">liaochuntao</a> * @author <a href="mailto:liaochuntao@live.com">liaochuntao</a>
*/ */
public class PolarisContextConfigurationTest { public class PolarisContextAutoConfigurationTest {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(UtilAutoConfiguration.class)) .withConfiguration(AutoConfigurations.of(UtilAutoConfiguration.class))
.withConfiguration(AutoConfigurations.of(PolarisContextConfiguration.class)) .withConfiguration(AutoConfigurations.of(PolarisContextAutoConfiguration.class))
.withPropertyValues("spring.cloud.polaris.address=grpc://127.0.0.1:8083"); .withPropertyValues("spring.cloud.polaris.address=grpc://127.0.0.1:8083");
@Test @Test

@ -31,7 +31,7 @@ import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class) @RunWith(SpringRunner.class)
@SpringBootTest(classes = PolarisContextApplication.class, @SpringBootTest(classes = PolarisContextApplication.class,
properties = { "spring.config.location = classpath:bootstrap.yml" }) properties = { "spring.config.location = classpath:bootstrap.yml" })
@ImportAutoConfiguration({ PolarisContextConfiguration.class }) @ImportAutoConfiguration({ PolarisContextAutoConfiguration.class })
public class PolarisContextGetHostTest { public class PolarisContextGetHostTest {
@Autowired @Autowired

Loading…
Cancel
Save