feat:refactor SDKContext as static. (#995)

pull/1000/head
Haotian Zhang 2 years ago committed by GitHub
parent 841a39ac33
commit 0ab19edb7a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -5,4 +5,5 @@
- [feature: Enhance default configuration to support `application*.yaml` and `bootstrap*.yaml`.](https://github.com/Tencent/spring-cloud-tencent/pull/988) - [feature: Enhance default configuration to support `application*.yaml` and `bootstrap*.yaml`.](https://github.com/Tencent/spring-cloud-tencent/pull/988)
- [feat:Remove error log from `DecodeTransferMetadataReactiveFilter`.](https://github.com/Tencent/spring-cloud-tencent/pull/991) - [feat:Remove error log from `DecodeTransferMetadataReactiveFilter`.](https://github.com/Tencent/spring-cloud-tencent/pull/991)
- [Feature: add AssemblyFlow to support tsf.](https://github.com/Tencent/spring-cloud-tencent/pull/992) - [Feature: add AssemblyFlow to support tsf.](https://github.com/Tencent/spring-cloud-tencent/pull/992)
- [feat:refactor SDKContext as static.](https://github.com/Tencent/spring-cloud-tencent/pull/995)
- [Refactoring: Refactor Circuitbreaker ut.](https://github.com/Tencent/spring-cloud-tencent/pull/996) - [Refactoring: Refactor Circuitbreaker ut.](https://github.com/Tencent/spring-cloud-tencent/pull/996)

@ -78,7 +78,7 @@ Spring Cloud Tencent 所有组件都已上传到 Maven 中央仓库,只需要
<groupId>com.tencent.cloud</groupId> <groupId>com.tencent.cloud</groupId>
<artifactId>spring-cloud-tencent-dependencies</artifactId> <artifactId>spring-cloud-tencent-dependencies</artifactId>
<!--version number--> <!--version number-->
<version>1.11.1-2022.0.1</version> <version>1.11.2-2022.0.1</version>
<type>pom</type> <type>pom</type>
<scope>import</scope> <scope>import</scope>
</dependency> </dependency>

@ -80,7 +80,7 @@ For example:
<groupId>com.tencent.cloud</groupId> <groupId>com.tencent.cloud</groupId>
<artifactId>spring-cloud-tencent-dependencies</artifactId> <artifactId>spring-cloud-tencent-dependencies</artifactId>
<!--version number--> <!--version number-->
<version>1.11.1-2022.0.1</version> <version>1.11.2-2022.0.1</version>
<type>pom</type> <type>pom</type>
<scope>import</scope> <scope>import</scope>
</dependency> </dependency>

@ -5,7 +5,7 @@
<parent> <parent>
<groupId>org.springframework.cloud</groupId> <groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-build</artifactId> <artifactId>spring-cloud-build</artifactId>
<version>4.0.1</version> <version>4.0.2</version>
<relativePath/> <relativePath/>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
@ -88,16 +88,16 @@
<properties> <properties>
<!-- Project revision --> <!-- Project revision -->
<revision>1.12.0-2022.0.1-SNAPSHOT</revision> <revision>1.12.0-2022.0.2-SNAPSHOT</revision>
<!-- Spring Framework --> <!-- Spring Framework -->
<spring.framework.version>6.0.7</spring.framework.version> <spring.framework.version>6.0.8</spring.framework.version>
<!-- Spring Boot --> <!-- Spring Boot -->
<spring.boot.version>3.0.4</spring.boot.version> <spring.boot.version>3.0.6</spring.boot.version>
<!-- Spring Cloud --> <!-- Spring Cloud -->
<spring.cloud.version>2022.0.1</spring.cloud.version> <spring.cloud.version>2022.0.2</spring.cloud.version>
<!-- Maven Plugin Versions --> <!-- Maven Plugin Versions -->
<jacoco.version>0.8.8</jacoco.version> <jacoco.version>0.8.8</jacoco.version>

@ -25,12 +25,9 @@ import com.tencent.cloud.polaris.circuitbreaker.common.CircuitBreakerConfigModif
import com.tencent.cloud.polaris.circuitbreaker.reporter.ExceptionCircuitBreakerReporter; import com.tencent.cloud.polaris.circuitbreaker.reporter.ExceptionCircuitBreakerReporter;
import com.tencent.cloud.polaris.circuitbreaker.reporter.SuccessCircuitBreakerReporter; import com.tencent.cloud.polaris.circuitbreaker.reporter.SuccessCircuitBreakerReporter;
import com.tencent.cloud.polaris.circuitbreaker.resttemplate.PolarisCircuitBreakerRestTemplateBeanPostProcessor; import com.tencent.cloud.polaris.circuitbreaker.resttemplate.PolarisCircuitBreakerRestTemplateBeanPostProcessor;
import com.tencent.cloud.polaris.context.PolarisSDKContextManager;
import com.tencent.cloud.rpc.enhancement.config.RpcEnhancementAutoConfiguration; import com.tencent.cloud.rpc.enhancement.config.RpcEnhancementAutoConfiguration;
import com.tencent.cloud.rpc.enhancement.config.RpcEnhancementReporterProperties; import com.tencent.cloud.rpc.enhancement.config.RpcEnhancementReporterProperties;
import com.tencent.polaris.api.core.ConsumerAPI;
import com.tencent.polaris.circuitbreak.api.CircuitBreakAPI;
import com.tencent.polaris.circuitbreak.factory.CircuitBreakAPIFactory;
import com.tencent.polaris.client.api.SDKContext;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.AutoConfigureAfter;
@ -58,29 +55,31 @@ public class PolarisCircuitBreakerAutoConfiguration {
private List<Customizer<PolarisCircuitBreakerFactory>> customizers = new ArrayList<>(); private List<Customizer<PolarisCircuitBreakerFactory>> customizers = new ArrayList<>();
@Bean @Bean
@ConditionalOnMissingBean(CircuitBreakAPI.class) @ConditionalOnClass(name = "org.springframework.web.client.RestTemplate")
public CircuitBreakAPI circuitBreakAPI(SDKContext polarisContext) { public static PolarisCircuitBreakerRestTemplateBeanPostProcessor polarisCircuitBreakerRestTemplateBeanPostProcessor(
return CircuitBreakAPIFactory.createCircuitBreakAPIByContext(polarisContext); ApplicationContext applicationContext) {
return new PolarisCircuitBreakerRestTemplateBeanPostProcessor(applicationContext);
} }
@Bean @Bean
@ConditionalOnMissingBean(SuccessCircuitBreakerReporter.class) @ConditionalOnMissingBean(SuccessCircuitBreakerReporter.class)
public SuccessCircuitBreakerReporter successCircuitBreakerReporter(RpcEnhancementReporterProperties properties, public SuccessCircuitBreakerReporter successCircuitBreakerReporter(RpcEnhancementReporterProperties properties,
CircuitBreakAPI circuitBreakAPI) { PolarisSDKContextManager polarisSDKContextManager) {
return new SuccessCircuitBreakerReporter(properties, circuitBreakAPI); return new SuccessCircuitBreakerReporter(properties, polarisSDKContextManager.getCircuitBreakAPI());
} }
@Bean @Bean
@ConditionalOnMissingBean(ExceptionCircuitBreakerReporter.class) @ConditionalOnMissingBean(ExceptionCircuitBreakerReporter.class)
public ExceptionCircuitBreakerReporter exceptionCircuitBreakerReporter(RpcEnhancementReporterProperties properties, public ExceptionCircuitBreakerReporter exceptionCircuitBreakerReporter(RpcEnhancementReporterProperties properties,
CircuitBreakAPI circuitBreakAPI) { PolarisSDKContextManager polarisSDKContextManager) {
return new ExceptionCircuitBreakerReporter(properties, circuitBreakAPI); return new ExceptionCircuitBreakerReporter(properties, polarisSDKContextManager.getCircuitBreakAPI());
} }
@Bean @Bean
@ConditionalOnMissingBean(CircuitBreakerFactory.class) @ConditionalOnMissingBean(CircuitBreakerFactory.class)
public CircuitBreakerFactory polarisCircuitBreakerFactory(CircuitBreakAPI circuitBreakAPI, ConsumerAPI consumerAPI) { public CircuitBreakerFactory polarisCircuitBreakerFactory(PolarisSDKContextManager polarisSDKContextManager) {
PolarisCircuitBreakerFactory factory = new PolarisCircuitBreakerFactory(circuitBreakAPI, consumerAPI); PolarisCircuitBreakerFactory factory = new PolarisCircuitBreakerFactory(
polarisSDKContextManager.getCircuitBreakAPI(), polarisSDKContextManager.getConsumerAPI());
customizers.forEach(customizer -> customizer.customize(factory)); customizers.forEach(customizer -> customizer.customize(factory));
return factory; return factory;
} }
@ -92,11 +91,4 @@ public class PolarisCircuitBreakerAutoConfiguration {
return new CircuitBreakerConfigModifier(properties); return new CircuitBreakerConfigModifier(properties);
} }
@Bean
@ConditionalOnClass(name = "org.springframework.web.client.RestTemplate")
public static PolarisCircuitBreakerRestTemplateBeanPostProcessor polarisCircuitBreakerRestTemplateBeanPostProcessor(
ApplicationContext applicationContext) {
return new PolarisCircuitBreakerRestTemplateBeanPostProcessor(applicationContext);
}
} }

@ -24,12 +24,9 @@ import com.tencent.cloud.polaris.circuitbreaker.ReactivePolarisCircuitBreakerFac
import com.tencent.cloud.polaris.circuitbreaker.common.CircuitBreakerConfigModifier; import com.tencent.cloud.polaris.circuitbreaker.common.CircuitBreakerConfigModifier;
import com.tencent.cloud.polaris.circuitbreaker.reporter.ExceptionCircuitBreakerReporter; import com.tencent.cloud.polaris.circuitbreaker.reporter.ExceptionCircuitBreakerReporter;
import com.tencent.cloud.polaris.circuitbreaker.reporter.SuccessCircuitBreakerReporter; import com.tencent.cloud.polaris.circuitbreaker.reporter.SuccessCircuitBreakerReporter;
import com.tencent.cloud.polaris.context.PolarisSDKContextManager;
import com.tencent.cloud.rpc.enhancement.config.RpcEnhancementAutoConfiguration; import com.tencent.cloud.rpc.enhancement.config.RpcEnhancementAutoConfiguration;
import com.tencent.cloud.rpc.enhancement.config.RpcEnhancementReporterProperties; import com.tencent.cloud.rpc.enhancement.config.RpcEnhancementReporterProperties;
import com.tencent.polaris.api.core.ConsumerAPI;
import com.tencent.polaris.circuitbreak.api.CircuitBreakAPI;
import com.tencent.polaris.circuitbreak.factory.CircuitBreakAPIFactory;
import com.tencent.polaris.client.api.SDKContext;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.AutoConfigureAfter;
@ -47,7 +44,7 @@ import org.springframework.context.annotation.Configuration;
* @author seanyu 2023-02-27 * @author seanyu 2023-02-27
*/ */
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
@ConditionalOnClass(name = { "reactor.core.publisher.Mono", "reactor.core.publisher.Flux" }) @ConditionalOnClass(name = {"reactor.core.publisher.Mono", "reactor.core.publisher.Flux"})
@ConditionalOnPolarisCircuitBreakerEnabled @ConditionalOnPolarisCircuitBreakerEnabled
@AutoConfigureAfter(RpcEnhancementAutoConfiguration.class) @AutoConfigureAfter(RpcEnhancementAutoConfiguration.class)
public class ReactivePolarisCircuitBreakerAutoConfiguration { public class ReactivePolarisCircuitBreakerAutoConfiguration {
@ -55,30 +52,25 @@ public class ReactivePolarisCircuitBreakerAutoConfiguration {
@Autowired(required = false) @Autowired(required = false)
private List<Customizer<ReactivePolarisCircuitBreakerFactory>> customizers = new ArrayList<>(); private List<Customizer<ReactivePolarisCircuitBreakerFactory>> customizers = new ArrayList<>();
@Bean
@ConditionalOnMissingBean(CircuitBreakAPI.class)
public CircuitBreakAPI circuitBreakAPI(SDKContext polarisContext) {
return CircuitBreakAPIFactory.createCircuitBreakAPIByContext(polarisContext);
}
@Bean @Bean
@ConditionalOnMissingBean(SuccessCircuitBreakerReporter.class) @ConditionalOnMissingBean(SuccessCircuitBreakerReporter.class)
public SuccessCircuitBreakerReporter successCircuitBreakerReporter(RpcEnhancementReporterProperties properties, public SuccessCircuitBreakerReporter successCircuitBreakerReporter(RpcEnhancementReporterProperties properties,
CircuitBreakAPI circuitBreakAPI) { PolarisSDKContextManager polarisSDKContextManager) {
return new SuccessCircuitBreakerReporter(properties, circuitBreakAPI); return new SuccessCircuitBreakerReporter(properties, polarisSDKContextManager.getCircuitBreakAPI());
} }
@Bean @Bean
@ConditionalOnMissingBean(ExceptionCircuitBreakerReporter.class) @ConditionalOnMissingBean(ExceptionCircuitBreakerReporter.class)
public ExceptionCircuitBreakerReporter exceptionCircuitBreakerReporter(RpcEnhancementReporterProperties properties, public ExceptionCircuitBreakerReporter exceptionCircuitBreakerReporter(RpcEnhancementReporterProperties properties,
CircuitBreakAPI circuitBreakAPI) { PolarisSDKContextManager polarisSDKContextManager) {
return new ExceptionCircuitBreakerReporter(properties, circuitBreakAPI); return new ExceptionCircuitBreakerReporter(properties, polarisSDKContextManager.getCircuitBreakAPI());
} }
@Bean @Bean
@ConditionalOnMissingBean(ReactiveCircuitBreakerFactory.class) @ConditionalOnMissingBean(ReactiveCircuitBreakerFactory.class)
public ReactiveCircuitBreakerFactory polarisReactiveCircuitBreakerFactory(CircuitBreakAPI circuitBreakAPI, ConsumerAPI consumerAPI) { public ReactiveCircuitBreakerFactory polarisReactiveCircuitBreakerFactory(PolarisSDKContextManager polarisSDKContextManager) {
ReactivePolarisCircuitBreakerFactory factory = new ReactivePolarisCircuitBreakerFactory(circuitBreakAPI, consumerAPI); ReactivePolarisCircuitBreakerFactory factory = new ReactivePolarisCircuitBreakerFactory(
polarisSDKContextManager.getCircuitBreakAPI(), polarisSDKContextManager.getConsumerAPI());
customizers.forEach(customizer -> customizer.customize(factory)); customizers.forEach(customizer -> customizer.customize(factory));
return factory; return factory;
} }

@ -30,6 +30,7 @@ import java.util.stream.Collectors;
import com.google.protobuf.util.JsonFormat; import com.google.protobuf.util.JsonFormat;
import com.tencent.cloud.common.util.ApplicationContextAwareUtils; import com.tencent.cloud.common.util.ApplicationContextAwareUtils;
import com.tencent.cloud.polaris.context.PolarisSDKContextManager;
import com.tencent.polaris.api.config.Configuration; import com.tencent.polaris.api.config.Configuration;
import com.tencent.polaris.api.core.ConsumerAPI; import com.tencent.polaris.api.core.ConsumerAPI;
import com.tencent.polaris.api.pojo.ServiceKey; import com.tencent.polaris.api.pojo.ServiceKey;
@ -76,7 +77,7 @@ public class PolarisCircuitBreakerMockServerTest {
.thenReturn(NAMESPACE_TEST); .thenReturn(NAMESPACE_TEST);
mockedApplicationContextAwareUtils.when(() -> ApplicationContextAwareUtils.getProperties("spring.cloud.polaris.service")) mockedApplicationContextAwareUtils.when(() -> ApplicationContextAwareUtils.getProperties("spring.cloud.polaris.service"))
.thenReturn(SERVICE_CIRCUIT_BREAKER); .thenReturn(SERVICE_CIRCUIT_BREAKER);
PolarisSDKContextManager.innerDestroy();
namingServer = NamingServer.startNamingServer(-1); namingServer = NamingServer.startNamingServer(-1);
System.setProperty(SERVER_ADDRESS_ENV, String.format("127.0.0.1:%d", namingServer.getPort())); System.setProperty(SERVER_ADDRESS_ENV, String.format("127.0.0.1:%d", namingServer.getPort()));
@ -96,7 +97,9 @@ public class PolarisCircuitBreakerMockServerTest {
if (null != namingServer) { if (null != namingServer) {
namingServer.terminate(); namingServer.terminate();
} }
mockedApplicationContextAwareUtils.close(); if (null != mockedApplicationContextAwareUtils) {
mockedApplicationContextAwareUtils.close();
}
} }
@Test @Test
@ -143,7 +146,6 @@ public class PolarisCircuitBreakerMockServerTest {
.collectList().block()) .collectList().block())
.isEqualTo(Collections.singletonList("fallback")); .isEqualTo(Collections.singletonList("fallback"));
} }
} }

@ -20,7 +20,6 @@ package com.tencent.cloud.polaris.circuitbreaker.config;
import com.tencent.cloud.polaris.circuitbreaker.common.CircuitBreakerConfigModifier; import com.tencent.cloud.polaris.circuitbreaker.common.CircuitBreakerConfigModifier;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration; import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import com.tencent.cloud.rpc.enhancement.config.RpcEnhancementAutoConfiguration; import com.tencent.cloud.rpc.enhancement.config.RpcEnhancementAutoConfiguration;
import com.tencent.polaris.circuitbreak.api.CircuitBreakAPI;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.AutoConfigurations;
@ -61,7 +60,6 @@ public class PolarisCircuitBreakerAutoConfigurationTest {
assertThat(context).hasSingleBean(PolarisCircuitBreakerAutoConfiguration.class); assertThat(context).hasSingleBean(PolarisCircuitBreakerAutoConfiguration.class);
assertThat(context).hasSingleBean(CircuitBreakerFactory.class); assertThat(context).hasSingleBean(CircuitBreakerFactory.class);
assertThat(context).hasSingleBean(CircuitBreakerConfigModifier.class); assertThat(context).hasSingleBean(CircuitBreakerConfigModifier.class);
assertThat(context).hasSingleBean(CircuitBreakAPI.class);
assertThat(context).hasSingleBean(CircuitBreakerNameResolver.class); assertThat(context).hasSingleBean(CircuitBreakerNameResolver.class);
}); });
} }
@ -72,10 +70,7 @@ public class PolarisCircuitBreakerAutoConfigurationTest {
assertThat(context).hasSingleBean(ReactivePolarisCircuitBreakerAutoConfiguration.class); assertThat(context).hasSingleBean(ReactivePolarisCircuitBreakerAutoConfiguration.class);
assertThat(context).hasSingleBean(ReactiveCircuitBreakerFactory.class); assertThat(context).hasSingleBean(ReactiveCircuitBreakerFactory.class);
assertThat(context).hasSingleBean(CircuitBreakerConfigModifier.class); assertThat(context).hasSingleBean(CircuitBreakerConfigModifier.class);
assertThat(context).hasSingleBean(CircuitBreakAPI.class);
}); });
} }
} }

@ -24,14 +24,22 @@ import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import com.google.protobuf.util.JsonFormat; import com.google.protobuf.util.JsonFormat;
import com.tencent.cloud.polaris.circuitbreaker.PolarisCircuitBreakerFactory;
import com.tencent.cloud.polaris.circuitbreaker.config.PolarisCircuitBreakerFeignClientAutoConfiguration; import com.tencent.cloud.polaris.circuitbreaker.config.PolarisCircuitBreakerFeignClientAutoConfiguration;
import com.tencent.cloud.polaris.circuitbreaker.reporter.ExceptionCircuitBreakerReporter;
import com.tencent.cloud.polaris.circuitbreaker.reporter.SuccessCircuitBreakerReporter;
import com.tencent.cloud.rpc.enhancement.config.RpcEnhancementReporterProperties;
import com.tencent.polaris.api.core.ConsumerAPI;
import com.tencent.polaris.api.pojo.ServiceKey; import com.tencent.polaris.api.pojo.ServiceKey;
import com.tencent.polaris.circuitbreak.api.CircuitBreakAPI; import com.tencent.polaris.circuitbreak.api.CircuitBreakAPI;
import com.tencent.polaris.circuitbreak.factory.CircuitBreakAPIFactory; import com.tencent.polaris.circuitbreak.factory.CircuitBreakAPIFactory;
import com.tencent.polaris.client.util.Utils; import com.tencent.polaris.client.util.Utils;
import com.tencent.polaris.factory.api.DiscoveryAPIFactory;
import com.tencent.polaris.specification.api.v1.fault.tolerance.CircuitBreakerProto; import com.tencent.polaris.specification.api.v1.fault.tolerance.CircuitBreakerProto;
import com.tencent.polaris.test.common.TestUtils; import com.tencent.polaris.test.common.TestUtils;
import com.tencent.polaris.test.mock.discovery.NamingServer; import com.tencent.polaris.test.mock.discovery.NamingServer;
@ -42,7 +50,10 @@ import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration; import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory;
import org.springframework.cloud.client.circuitbreaker.Customizer;
import org.springframework.cloud.client.circuitbreaker.NoFallbackAvailableException; import org.springframework.cloud.client.circuitbreaker.NoFallbackAvailableException;
import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.cloud.openfeign.FallbackFactory; import org.springframework.cloud.openfeign.FallbackFactory;
@ -71,7 +82,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
"spring.cloud.openfeign.circuitbreaker.enabled=true", "spring.cloud.openfeign.circuitbreaker.enabled=true",
"spring.cloud.polaris.namespace=" + NAMESPACE_TEST, "spring.cloud.polaris.namespace=" + NAMESPACE_TEST,
"spring.cloud.polaris.service=test" "spring.cloud.polaris.service=test"
}) })
public class PolarisCircuitBreakerFeignIntegrationTest { public class PolarisCircuitBreakerFeignIntegrationTest {
private static final String TEST_SERVICE_NAME = "test-service-callee"; private static final String TEST_SERVICE_NAME = "test-service-callee";
@ -89,7 +100,7 @@ public class PolarisCircuitBreakerFeignIntegrationTest {
private BazService bazService; private BazService bazService;
@Test @Test
public void contextLoads() throws Exception { public void contextLoads() {
assertThat(echoService).isNotNull(); assertThat(echoService).isNotNull();
assertThat(fooService).isNotNull(); assertThat(fooService).isNotNull();
} }
@ -113,12 +124,52 @@ public class PolarisCircuitBreakerFeignIntegrationTest {
assertThat(echoService.equals(fooService)).isEqualTo(Boolean.FALSE); assertThat(echoService.equals(fooService)).isEqualTo(Boolean.FALSE);
} }
@FeignClient(value = TEST_SERVICE_NAME, contextId = "1", fallback = EchoServiceFallback.class)
@Primary
public interface EchoService {
@RequestMapping(path = "echo/{str}")
String echo(@RequestParam("str") String param) throws InvocationTargetException;
}
@FeignClient(value = TEST_SERVICE_NAME, contextId = "2", fallbackFactory = CustomFallbackFactory.class)
public interface FooService {
@RequestMapping("echo/{str}")
String echo(@RequestParam("str") String param);
}
@FeignClient(value = TEST_SERVICE_NAME, contextId = "3")
public interface BarService {
@RequestMapping(path = "bar")
String bar();
}
public interface BazService {
@RequestMapping(path = "baz")
String baz();
}
@FeignClient(value = TEST_SERVICE_NAME, contextId = "4")
public interface BazClient extends BazService {
}
@Configuration @Configuration
@EnableAutoConfiguration @EnableAutoConfiguration
@ImportAutoConfiguration({ PolarisCircuitBreakerFeignClientAutoConfiguration.class }) @ImportAutoConfiguration({PolarisCircuitBreakerFeignClientAutoConfiguration.class})
@EnableFeignClients @EnableFeignClients
public static class TestConfig { public static class TestConfig {
@Autowired(required = false)
private List<Customizer<PolarisCircuitBreakerFactory>> customizers = new ArrayList<>();
@Bean @Bean
public EchoServiceFallback echoServiceFallback() { public EchoServiceFallback echoServiceFallback() {
return new EchoServiceFallback(); return new EchoServiceFallback();
@ -140,12 +191,15 @@ public class PolarisCircuitBreakerFeignIntegrationTest {
System.setProperty(SERVER_ADDRESS_ENV, String.format("127.0.0.1:%d", namingServer.getPort())); System.setProperty(SERVER_ADDRESS_ENV, String.format("127.0.0.1:%d", namingServer.getPort()));
ServiceKey serviceKey = new ServiceKey(NAMESPACE_TEST, TEST_SERVICE_NAME); ServiceKey serviceKey = new ServiceKey(NAMESPACE_TEST, TEST_SERVICE_NAME);
CircuitBreakerProto.CircuitBreakerRule.Builder circuitBreakerRuleBuilder = CircuitBreakerProto.CircuitBreakerRule.newBuilder(); CircuitBreakerProto.CircuitBreakerRule.Builder circuitBreakerRuleBuilder = CircuitBreakerProto.CircuitBreakerRule.newBuilder();
InputStream inputStream = PolarisCircuitBreakerFeignIntegrationTest.class.getClassLoader().getResourceAsStream("circuitBreakerRule.json"); InputStream inputStream = PolarisCircuitBreakerFeignIntegrationTest.class.getClassLoader()
String json = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)).lines().collect(Collectors.joining("")); .getResourceAsStream("circuitBreakerRule.json");
String json = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)).lines()
.collect(Collectors.joining(""));
JsonFormat.parser().ignoringUnknownFields().merge(json, circuitBreakerRuleBuilder); JsonFormat.parser().ignoringUnknownFields().merge(json, circuitBreakerRuleBuilder);
CircuitBreakerProto.CircuitBreakerRule circuitBreakerRule = circuitBreakerRuleBuilder.build(); CircuitBreakerProto.CircuitBreakerRule circuitBreakerRule = circuitBreakerRuleBuilder.build();
CircuitBreakerProto.CircuitBreaker circuitBreaker = CircuitBreakerProto.CircuitBreaker.newBuilder().addRules(circuitBreakerRule).build(); CircuitBreakerProto.CircuitBreaker circuitBreaker = CircuitBreakerProto.CircuitBreaker.newBuilder()
.addRules(circuitBreakerRule).build();
namingServer.getNamingService().setCircuitBreaker(serviceKey, circuitBreaker); namingServer.getNamingService().setCircuitBreaker(serviceKey, circuitBreaker);
return namingServer; return namingServer;
} }
@ -156,43 +210,33 @@ public class PolarisCircuitBreakerFeignIntegrationTest {
return CircuitBreakAPIFactory.createCircuitBreakAPIByConfig(configuration); return CircuitBreakAPIFactory.createCircuitBreakAPIByConfig(configuration);
} }
} @Bean
public ConsumerAPI consumerAPI(NamingServer namingServer) {
@FeignClient(value = TEST_SERVICE_NAME, contextId = "1", fallback = EchoServiceFallback.class) com.tencent.polaris.api.config.Configuration configuration = TestUtils.configWithEnvAddress();
@Primary return DiscoveryAPIFactory.createConsumerAPIByConfig(configuration);
public interface EchoService { }
@RequestMapping(path = "echo/{str}")
String echo(@RequestParam("str") String param) throws InvocationTargetException;
}
@FeignClient(value = TEST_SERVICE_NAME, contextId = "2", fallbackFactory = CustomFallbackFactory.class)
public interface FooService {
@RequestMapping("echo/{str}")
String echo(@RequestParam("str") String param);
}
@FeignClient(value = TEST_SERVICE_NAME, contextId = "3")
public interface BarService {
@RequestMapping(path = "bar")
String bar();
}
public interface BazService {
@RequestMapping(path = "baz")
String baz();
} @Bean
@ConditionalOnMissingBean(SuccessCircuitBreakerReporter.class)
public SuccessCircuitBreakerReporter successCircuitBreakerReporter(RpcEnhancementReporterProperties properties,
CircuitBreakAPI circuitBreakAPI) {
return new SuccessCircuitBreakerReporter(properties, circuitBreakAPI);
}
@FeignClient(value = TEST_SERVICE_NAME, contextId = "4") @Bean
public interface BazClient extends BazService { @ConditionalOnMissingBean(ExceptionCircuitBreakerReporter.class)
public ExceptionCircuitBreakerReporter exceptionCircuitBreakerReporter(RpcEnhancementReporterProperties properties,
CircuitBreakAPI circuitBreakAPI) {
return new ExceptionCircuitBreakerReporter(properties, circuitBreakAPI);
}
@Bean
@ConditionalOnMissingBean(CircuitBreakerFactory.class)
public CircuitBreakerFactory polarisCircuitBreakerFactory(CircuitBreakAPI circuitBreakAPI, ConsumerAPI consumerAPI) {
PolarisCircuitBreakerFactory factory = new PolarisCircuitBreakerFactory(circuitBreakAPI, consumerAPI);
customizers.forEach(customizer -> customizer.customize(factory));
return factory;
}
} }
public static class EchoServiceFallback implements EchoService { public static class EchoServiceFallback implements EchoService {
@ -219,7 +263,7 @@ public class PolarisCircuitBreakerFeignIntegrationTest {
public static class CustomFallbackFactory public static class CustomFallbackFactory
implements FallbackFactory<FooService> { implements FallbackFactory<FooService> {
private FooService fooService = new FooServiceFallback(); private final FooService fooService = new FooServiceFallback();
@Override @Override
public FooService create(Throwable throwable) { public FooService create(Throwable throwable) {
@ -231,9 +275,11 @@ public class PolarisCircuitBreakerFeignIntegrationTest {
public static class PreDestroy implements DisposableBean { public static class PreDestroy implements DisposableBean {
private final NamingServer namingServer; private final NamingServer namingServer;
public PreDestroy(NamingServer namingServer) { public PreDestroy(NamingServer namingServer) {
this.namingServer = namingServer; this.namingServer = namingServer;
} }
@Override @Override
public void destroy() throws Exception { public void destroy() throws Exception {
namingServer.terminate(); namingServer.terminate();

@ -23,16 +23,24 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.HashSet; import java.util.HashSet;
import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import com.google.protobuf.util.JsonFormat; import com.google.protobuf.util.JsonFormat;
import com.tencent.cloud.polaris.circuitbreaker.PolarisCircuitBreakerFactory;
import com.tencent.cloud.polaris.circuitbreaker.reporter.ExceptionCircuitBreakerReporter;
import com.tencent.cloud.polaris.circuitbreaker.reporter.SuccessCircuitBreakerReporter;
import com.tencent.cloud.rpc.enhancement.config.RpcEnhancementReporterProperties;
import com.tencent.polaris.api.core.ConsumerAPI;
import com.tencent.polaris.api.pojo.ServiceKey; import com.tencent.polaris.api.pojo.ServiceKey;
import com.tencent.polaris.circuitbreak.api.CircuitBreakAPI; import com.tencent.polaris.circuitbreak.api.CircuitBreakAPI;
import com.tencent.polaris.circuitbreak.factory.CircuitBreakAPIFactory; import com.tencent.polaris.circuitbreak.factory.CircuitBreakAPIFactory;
import com.tencent.polaris.client.util.Utils; import com.tencent.polaris.client.util.Utils;
import com.tencent.polaris.factory.api.DiscoveryAPIFactory;
import com.tencent.polaris.specification.api.v1.fault.tolerance.CircuitBreakerProto; import com.tencent.polaris.specification.api.v1.fault.tolerance.CircuitBreakerProto;
import com.tencent.polaris.test.common.TestUtils; import com.tencent.polaris.test.common.TestUtils;
import com.tencent.polaris.test.mock.discovery.NamingServer; import com.tencent.polaris.test.mock.discovery.NamingServer;
@ -43,8 +51,11 @@ import reactor.core.publisher.Mono;
import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient; import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory;
import org.springframework.cloud.client.circuitbreaker.Customizer;
import org.springframework.cloud.contract.wiremock.AutoConfigureWireMock; import org.springframework.cloud.contract.wiremock.AutoConfigureWireMock;
import org.springframework.cloud.gateway.filter.factory.SpringCloudCircuitBreakerFilterFactory; import org.springframework.cloud.gateway.filter.factory.SpringCloudCircuitBreakerFilterFactory;
import org.springframework.cloud.gateway.route.RouteLocator; import org.springframework.cloud.gateway.route.RouteLocator;
@ -152,6 +163,9 @@ public class PolarisCircuitBreakerGatewayIntegrationTest {
@EnableAutoConfiguration @EnableAutoConfiguration
public static class TestApplication { public static class TestApplication {
@Autowired(required = false)
private List<Customizer<PolarisCircuitBreakerFactory>> customizers = new ArrayList<>();
@Bean @Bean
public PreDestroy preDestroy(NamingServer namingServer) { public PreDestroy preDestroy(NamingServer namingServer) {
return new PreDestroy(namingServer); return new PreDestroy(namingServer);
@ -163,12 +177,15 @@ public class PolarisCircuitBreakerGatewayIntegrationTest {
System.setProperty(SERVER_ADDRESS_ENV, String.format("127.0.0.1:%d", namingServer.getPort())); System.setProperty(SERVER_ADDRESS_ENV, String.format("127.0.0.1:%d", namingServer.getPort()));
ServiceKey serviceKey = new ServiceKey(NAMESPACE_TEST, TEST_SERVICE_NAME); ServiceKey serviceKey = new ServiceKey(NAMESPACE_TEST, TEST_SERVICE_NAME);
CircuitBreakerProto.CircuitBreakerRule.Builder circuitBreakerRuleBuilder = CircuitBreakerProto.CircuitBreakerRule.newBuilder(); CircuitBreakerProto.CircuitBreakerRule.Builder circuitBreakerRuleBuilder = CircuitBreakerProto.CircuitBreakerRule.newBuilder();
InputStream inputStream = PolarisCircuitBreakerGatewayIntegrationTest.class.getClassLoader().getResourceAsStream("circuitBreakerRule.json"); InputStream inputStream = PolarisCircuitBreakerGatewayIntegrationTest.class.getClassLoader()
String json = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)).lines().collect(Collectors.joining("")); .getResourceAsStream("circuitBreakerRule.json");
String json = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)).lines()
.collect(Collectors.joining(""));
JsonFormat.parser().ignoringUnknownFields().merge(json, circuitBreakerRuleBuilder); JsonFormat.parser().ignoringUnknownFields().merge(json, circuitBreakerRuleBuilder);
CircuitBreakerProto.CircuitBreakerRule circuitBreakerRule = circuitBreakerRuleBuilder.build(); CircuitBreakerProto.CircuitBreakerRule circuitBreakerRule = circuitBreakerRuleBuilder.build();
CircuitBreakerProto.CircuitBreaker circuitBreaker = CircuitBreakerProto.CircuitBreaker.newBuilder().addRules(circuitBreakerRule).build(); CircuitBreakerProto.CircuitBreaker circuitBreaker = CircuitBreakerProto.CircuitBreaker.newBuilder()
.addRules(circuitBreakerRule).build();
namingServer.getNamingService().setCircuitBreaker(serviceKey, circuitBreaker); namingServer.getNamingService().setCircuitBreaker(serviceKey, circuitBreaker);
return namingServer; return namingServer;
} }
@ -179,6 +196,34 @@ public class PolarisCircuitBreakerGatewayIntegrationTest {
return CircuitBreakAPIFactory.createCircuitBreakAPIByConfig(configuration); return CircuitBreakAPIFactory.createCircuitBreakAPIByConfig(configuration);
} }
@Bean
public ConsumerAPI consumerAPI(NamingServer namingServer) {
com.tencent.polaris.api.config.Configuration configuration = TestUtils.configWithEnvAddress();
return DiscoveryAPIFactory.createConsumerAPIByConfig(configuration);
}
@Bean
@ConditionalOnMissingBean(SuccessCircuitBreakerReporter.class)
public SuccessCircuitBreakerReporter successCircuitBreakerReporter(RpcEnhancementReporterProperties properties,
CircuitBreakAPI circuitBreakAPI) {
return new SuccessCircuitBreakerReporter(properties, circuitBreakAPI);
}
@Bean
@ConditionalOnMissingBean(ExceptionCircuitBreakerReporter.class)
public ExceptionCircuitBreakerReporter exceptionCircuitBreakerReporter(RpcEnhancementReporterProperties properties,
CircuitBreakAPI circuitBreakAPI) {
return new ExceptionCircuitBreakerReporter(properties, circuitBreakAPI);
}
@Bean
@ConditionalOnMissingBean(CircuitBreakerFactory.class)
public CircuitBreakerFactory polarisCircuitBreakerFactory(CircuitBreakAPI circuitBreakAPI, ConsumerAPI consumerAPI) {
PolarisCircuitBreakerFactory factory = new PolarisCircuitBreakerFactory(circuitBreakAPI, consumerAPI);
customizers.forEach(customizer -> customizer.customize(factory));
return factory;
}
@Bean @Bean
public RouteLocator myRoutes(RouteLocatorBuilder builder) { public RouteLocator myRoutes(RouteLocatorBuilder builder) {
Set<String> codeSets = new HashSet<>(); Set<String> codeSets = new HashSet<>();
@ -225,9 +270,11 @@ public class PolarisCircuitBreakerGatewayIntegrationTest {
public static class PreDestroy implements DisposableBean { public static class PreDestroy implements DisposableBean {
private final NamingServer namingServer; private final NamingServer namingServer;
public PreDestroy(NamingServer namingServer) { public PreDestroy(NamingServer namingServer) {
this.namingServer = namingServer; this.namingServer = namingServer;
} }
@Override @Override
public void destroy() throws Exception { public void destroy() throws Exception {
namingServer.terminate(); namingServer.terminate();

@ -24,11 +24,18 @@ import java.io.InputStreamReader;
import java.net.URI; import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import com.google.protobuf.util.JsonFormat; import com.google.protobuf.util.JsonFormat;
import com.tencent.cloud.polaris.circuitbreaker.PolarisCircuitBreakerFactory;
import com.tencent.cloud.polaris.circuitbreaker.config.PolarisCircuitBreakerFeignClientAutoConfiguration; import com.tencent.cloud.polaris.circuitbreaker.config.PolarisCircuitBreakerFeignClientAutoConfiguration;
import com.tencent.cloud.polaris.circuitbreaker.reporter.ExceptionCircuitBreakerReporter;
import com.tencent.cloud.polaris.circuitbreaker.reporter.SuccessCircuitBreakerReporter;
import com.tencent.cloud.polaris.context.PolarisSDKContextManager;
import com.tencent.cloud.rpc.enhancement.config.RpcEnhancementReporterProperties;
import com.tencent.polaris.api.pojo.ServiceKey; import com.tencent.polaris.api.pojo.ServiceKey;
import com.tencent.polaris.circuitbreak.api.CircuitBreakAPI; import com.tencent.polaris.circuitbreak.api.CircuitBreakAPI;
import com.tencent.polaris.circuitbreak.factory.CircuitBreakAPIFactory; import com.tencent.polaris.circuitbreak.factory.CircuitBreakAPIFactory;
@ -44,7 +51,10 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration; import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory;
import org.springframework.cloud.client.circuitbreaker.Customizer;
import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
@ -136,7 +146,8 @@ public class PolarisCircuitBreakerRestTemplateIntegrationTest {
Utils.sleepUninterrupted(2000); Utils.sleepUninterrupted(2000);
assertThat(restTemplateFallbackFromCode2.getForObject("/example/service/b/info", String.class)).isEqualTo("\"this is a fallback class\""); assertThat(restTemplateFallbackFromCode2.getForObject("/example/service/b/info", String.class)).isEqualTo("\"this is a fallback class\"");
Utils.sleepUninterrupted(2000); Utils.sleepUninterrupted(2000);
assertThat(restTemplateFallbackFromCode3.getForEntity("/example/service/b/info", String.class).getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(restTemplateFallbackFromCode3.getForEntity("/example/service/b/info", String.class)
.getStatusCode()).isEqualTo(HttpStatus.OK);
Utils.sleepUninterrupted(2000); Utils.sleepUninterrupted(2000);
assertThat(restTemplateFallbackFromCode4.getForObject("/example/service/b/info", String.class)).isEqualTo("fallback"); assertThat(restTemplateFallbackFromCode4.getForObject("/example/service/b/info", String.class)).isEqualTo("fallback");
Utils.sleepUninterrupted(2000); Utils.sleepUninterrupted(2000);
@ -149,10 +160,17 @@ public class PolarisCircuitBreakerRestTemplateIntegrationTest {
@Configuration @Configuration
@EnableAutoConfiguration @EnableAutoConfiguration
@ImportAutoConfiguration({ PolarisCircuitBreakerFeignClientAutoConfiguration.class }) @ImportAutoConfiguration({PolarisCircuitBreakerFeignClientAutoConfiguration.class})
@EnableFeignClients @EnableFeignClients
public static class TestConfig { public static class TestConfig {
@Autowired(required = false)
private List<Customizer<PolarisCircuitBreakerFactory>> customizers = new ArrayList<>();
{
PolarisSDKContextManager.innerDestroy();
}
@Bean @Bean
@com.tencent.cloud.polaris.circuitbreaker.resttemplate.PolarisCircuitBreaker(fallback = "fallback") @com.tencent.cloud.polaris.circuitbreaker.resttemplate.PolarisCircuitBreaker(fallback = "fallback")
public RestTemplate defaultRestTemplate() { public RestTemplate defaultRestTemplate() {
@ -229,12 +247,15 @@ public class PolarisCircuitBreakerRestTemplateIntegrationTest {
NamingServer namingServer = NamingServer.startNamingServer(-1); NamingServer namingServer = NamingServer.startNamingServer(-1);
System.setProperty(SERVER_ADDRESS_ENV, String.format("127.0.0.1:%d", namingServer.getPort())); System.setProperty(SERVER_ADDRESS_ENV, String.format("127.0.0.1:%d", namingServer.getPort()));
ServiceKey serviceKey = new ServiceKey(NAMESPACE_TEST, TEST_SERVICE_NAME); ServiceKey serviceKey = new ServiceKey(NAMESPACE_TEST, TEST_SERVICE_NAME);
CircuitBreakerProto.CircuitBreakerRule.Builder circuitBreakerRuleBuilder = CircuitBreakerProto.CircuitBreakerRule.newBuilder(); CircuitBreakerProto.CircuitBreakerRule.Builder circuitBreakerRuleBuilder = CircuitBreakerProto.CircuitBreakerRule.newBuilder();
InputStream inputStream = PolarisCircuitBreakerRestTemplateIntegrationTest.class.getClassLoader().getResourceAsStream("circuitBreakerRule.json"); InputStream inputStream = PolarisCircuitBreakerRestTemplateIntegrationTest.class.getClassLoader()
String json = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)).lines().collect(Collectors.joining("")); .getResourceAsStream("circuitBreakerRule.json");
String json = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)).lines()
.collect(Collectors.joining(""));
JsonFormat.parser().ignoringUnknownFields().merge(json, circuitBreakerRuleBuilder); JsonFormat.parser().ignoringUnknownFields().merge(json, circuitBreakerRuleBuilder);
CircuitBreakerProto.CircuitBreakerRule circuitBreakerRule = circuitBreakerRuleBuilder.build(); CircuitBreakerProto.CircuitBreakerRule circuitBreakerRule = circuitBreakerRuleBuilder.build();
CircuitBreakerProto.CircuitBreaker circuitBreaker = CircuitBreakerProto.CircuitBreaker.newBuilder().addRules(circuitBreakerRule).build(); CircuitBreakerProto.CircuitBreaker circuitBreaker = CircuitBreakerProto.CircuitBreaker.newBuilder()
.addRules(circuitBreakerRule).build();
namingServer.getNamingService().setCircuitBreaker(serviceKey, circuitBreaker); namingServer.getNamingService().setCircuitBreaker(serviceKey, circuitBreaker);
return namingServer; return namingServer;
} }
@ -250,6 +271,30 @@ public class PolarisCircuitBreakerRestTemplateIntegrationTest {
return CircuitBreakAPIFactory.createCircuitBreakAPIByConfig(configuration); return CircuitBreakAPIFactory.createCircuitBreakAPIByConfig(configuration);
} }
@Bean
@ConditionalOnMissingBean(SuccessCircuitBreakerReporter.class)
public SuccessCircuitBreakerReporter successCircuitBreakerReporter(RpcEnhancementReporterProperties properties,
CircuitBreakAPI circuitBreakAPI) {
return new SuccessCircuitBreakerReporter(properties, circuitBreakAPI);
}
@Bean
@ConditionalOnMissingBean(ExceptionCircuitBreakerReporter.class)
public ExceptionCircuitBreakerReporter exceptionCircuitBreakerReporter(RpcEnhancementReporterProperties properties,
CircuitBreakAPI circuitBreakAPI) {
return new ExceptionCircuitBreakerReporter(properties, circuitBreakAPI);
}
@Bean
@ConditionalOnMissingBean(CircuitBreakerFactory.class)
public CircuitBreakerFactory polarisCircuitBreakerFactory(CircuitBreakAPI circuitBreakAPI,
PolarisSDKContextManager polarisSDKContextManager) {
PolarisCircuitBreakerFactory factory = new PolarisCircuitBreakerFactory(
circuitBreakAPI, polarisSDKContextManager.getConsumerAPI());
customizers.forEach(customizer -> customizer.customize(factory));
return factory;
}
@RestController @RestController
@RequestMapping("/example/service/b") @RequestMapping("/example/service/b")
public class ServiceBController { public class ServiceBController {
@ -302,14 +347,15 @@ public class PolarisCircuitBreakerRestTemplateIntegrationTest {
public static class PreDestroy implements DisposableBean { public static class PreDestroy implements DisposableBean {
private final NamingServer namingServer; private final NamingServer namingServer;
public PreDestroy(NamingServer namingServer) { public PreDestroy(NamingServer namingServer) {
this.namingServer = namingServer; this.namingServer = namingServer;
} }
@Override @Override
public void destroy() throws Exception { public void destroy() throws Exception {
namingServer.terminate(); namingServer.terminate();
} }
} }
} }

@ -23,9 +23,9 @@ 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.condition.ConditionalOnReflectRefreshType; import com.tencent.cloud.polaris.config.condition.ConditionalOnReflectRefreshType;
import com.tencent.cloud.polaris.config.config.PolarisConfigProperties; import com.tencent.cloud.polaris.config.config.PolarisConfigProperties;
import com.tencent.cloud.polaris.context.PolarisSDKContextManager;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration; import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import com.tencent.cloud.polaris.context.config.PolarisContextProperties; 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.api.core.ConfigFileService;
import com.tencent.polaris.configuration.factory.ConfigFileServiceFactory; import com.tencent.polaris.configuration.factory.ConfigFileServiceFactory;
@ -61,8 +61,8 @@ public class PolarisConfigBootstrapAutoConfiguration {
@Bean @Bean
@ConditionalOnConnectRemoteServerEnabled @ConditionalOnConnectRemoteServerEnabled
public ConfigFileService configFileService(SDKContext sdkContext) { public ConfigFileService configFileService(PolarisSDKContextManager polarisSDKContextManager) {
return ConfigFileServiceFactory.createConfigFileService(sdkContext); return ConfigFileServiceFactory.createConfigFileService(polarisSDKContextManager.getSDKContext());
} }
@Bean @Bean

@ -18,14 +18,12 @@
package com.tencent.cloud.polaris; package com.tencent.cloud.polaris;
import com.tencent.cloud.polaris.context.ConditionalOnPolarisEnabled; import com.tencent.cloud.polaris.context.ConditionalOnPolarisEnabled;
import com.tencent.cloud.polaris.context.PolarisSDKContextManager;
import com.tencent.cloud.polaris.discovery.PolarisDiscoveryHandler; import com.tencent.cloud.polaris.discovery.PolarisDiscoveryHandler;
import com.tencent.cloud.polaris.extend.consul.ConsulConfigModifier; import com.tencent.cloud.polaris.extend.consul.ConsulConfigModifier;
import com.tencent.cloud.polaris.extend.consul.ConsulContextProperties; import com.tencent.cloud.polaris.extend.consul.ConsulContextProperties;
import com.tencent.cloud.polaris.extend.nacos.NacosConfigModifier; import com.tencent.cloud.polaris.extend.nacos.NacosConfigModifier;
import com.tencent.cloud.polaris.extend.nacos.NacosContextProperties; import com.tencent.cloud.polaris.extend.nacos.NacosContextProperties;
import com.tencent.polaris.api.core.ConsumerAPI;
import com.tencent.polaris.api.core.ProviderAPI;
import com.tencent.polaris.client.api.SDKContext;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
@ -46,9 +44,8 @@ public class DiscoveryPropertiesAutoConfiguration {
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public PolarisDiscoveryHandler polarisDiscoveryHandler(PolarisDiscoveryProperties polarisDiscoveryProperties, public PolarisDiscoveryHandler polarisDiscoveryHandler(PolarisDiscoveryProperties polarisDiscoveryProperties,
ProviderAPI providerAPI, SDKContext sdkContext, PolarisSDKContextManager polarisSDKContextManager) {
ConsumerAPI polarisConsumer) { return new PolarisDiscoveryHandler(polarisDiscoveryProperties, polarisSDKContextManager);
return new PolarisDiscoveryHandler(polarisDiscoveryProperties, providerAPI, sdkContext, polarisConsumer);
} }
@Bean @Bean

@ -19,14 +19,13 @@
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.PolarisSDKContextManager;
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.rpc.GetAllInstancesRequest; import com.tencent.polaris.api.rpc.GetAllInstancesRequest;
import com.tencent.polaris.api.rpc.GetHealthyInstancesRequest; import com.tencent.polaris.api.rpc.GetHealthyInstancesRequest;
import com.tencent.polaris.api.rpc.GetServicesRequest; import com.tencent.polaris.api.rpc.GetServicesRequest;
import com.tencent.polaris.api.rpc.InstancesResponse; import com.tencent.polaris.api.rpc.InstancesResponse;
import com.tencent.polaris.api.rpc.ServicesResponse; import com.tencent.polaris.api.rpc.ServicesResponse;
import com.tencent.polaris.client.api.SDKContext;
/** /**
* Discovery Handler for Polaris. * Discovery Handler for Polaris.
@ -37,18 +36,12 @@ public class PolarisDiscoveryHandler {
private final PolarisDiscoveryProperties polarisDiscoveryProperties; private final PolarisDiscoveryProperties polarisDiscoveryProperties;
private final ProviderAPI providerAPI;
private final SDKContext sdkContext;
private final ConsumerAPI polarisConsumer; private final ConsumerAPI polarisConsumer;
public PolarisDiscoveryHandler(PolarisDiscoveryProperties polarisDiscoveryProperties, public PolarisDiscoveryHandler(PolarisDiscoveryProperties polarisDiscoveryProperties,
ProviderAPI providerAPI, SDKContext sdkContext, ConsumerAPI polarisConsumer) { PolarisSDKContextManager polarisSDKContextManager) {
this.polarisDiscoveryProperties = polarisDiscoveryProperties; this.polarisDiscoveryProperties = polarisDiscoveryProperties;
this.providerAPI = providerAPI; this.polarisConsumer = polarisSDKContextManager.getConsumerAPI();
this.sdkContext = sdkContext;
this.polarisConsumer = polarisConsumer;
} }
/** /**
@ -75,15 +68,7 @@ public class PolarisDiscoveryHandler {
GetAllInstancesRequest request = new GetAllInstancesRequest(); GetAllInstancesRequest request = new GetAllInstancesRequest();
request.setNamespace(namespace); request.setNamespace(namespace);
request.setService(service); request.setService(service);
return polarisConsumer.getAllInstance(request); return polarisConsumer.getAllInstances(request);
}
public ProviderAPI getProviderAPI() {
return providerAPI;
}
public SDKContext getSdkContext() {
return sdkContext;
} }
/** /**

@ -21,7 +21,7 @@ import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import com.tencent.cloud.polaris.discovery.PolarisDiscoveryHandler; import com.tencent.cloud.polaris.context.PolarisSDKContextManager;
import com.tencent.polaris.client.util.NamedThreadFactory; import com.tencent.polaris.client.util.NamedThreadFactory;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -45,14 +45,14 @@ public class PolarisRefreshApplicationReadyEventListener
private static final Logger LOG = LoggerFactory.getLogger(PolarisRefreshApplicationReadyEventListener.class); private static final Logger LOG = LoggerFactory.getLogger(PolarisRefreshApplicationReadyEventListener.class);
private static final int DELAY = 60; private static final int DELAY = 60;
private final PolarisDiscoveryHandler polarisDiscoveryHandler; private final PolarisSDKContextManager polarisSDKContextManager;
private final PolarisServiceStatusChangeListener polarisServiceStatusChangeListener; private final PolarisServiceStatusChangeListener polarisServiceStatusChangeListener;
private final ScheduledExecutorService refreshExecutor; private final ScheduledExecutorService refreshExecutor;
private ApplicationEventPublisher publisher; private ApplicationEventPublisher publisher;
public PolarisRefreshApplicationReadyEventListener(PolarisDiscoveryHandler polarisDiscoveryHandler, public PolarisRefreshApplicationReadyEventListener(PolarisSDKContextManager polarisSDKContextManager,
PolarisServiceStatusChangeListener polarisServiceStatusChangeListener) { PolarisServiceStatusChangeListener polarisServiceStatusChangeListener) {
this.polarisDiscoveryHandler = polarisDiscoveryHandler; this.polarisSDKContextManager = polarisSDKContextManager;
this.polarisServiceStatusChangeListener = polarisServiceStatusChangeListener; this.polarisServiceStatusChangeListener = polarisServiceStatusChangeListener;
this.refreshExecutor = Executors.newSingleThreadScheduledExecutor( this.refreshExecutor = Executors.newSingleThreadScheduledExecutor(
new NamedThreadFactory("polaris-service-refresh")); new NamedThreadFactory("polaris-service-refresh"));
@ -61,7 +61,7 @@ public class PolarisRefreshApplicationReadyEventListener
@Override @Override
public void onApplicationEvent(ApplicationReadyEvent event) { public void onApplicationEvent(ApplicationReadyEvent event) {
// Register service change listener. // Register service change listener.
polarisDiscoveryHandler.getSdkContext().getExtensions().getLocalRegistry() polarisSDKContextManager.getSDKContext().getExtensions().getLocalRegistry()
.registerResourceListener(polarisServiceStatusChangeListener); .registerResourceListener(polarisServiceStatusChangeListener);
// Begin scheduled refresh thread. // Begin scheduled refresh thread.

@ -18,7 +18,7 @@
package com.tencent.cloud.polaris.discovery.refresh; package com.tencent.cloud.polaris.discovery.refresh;
import com.tencent.cloud.polaris.context.ConditionalOnPolarisEnabled; import com.tencent.cloud.polaris.context.ConditionalOnPolarisEnabled;
import com.tencent.cloud.polaris.discovery.PolarisDiscoveryHandler; import com.tencent.cloud.polaris.context.PolarisSDKContextManager;
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;
@ -42,8 +42,8 @@ public class PolarisRefreshConfiguration {
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public PolarisRefreshApplicationReadyEventListener polarisServiceStatusApplicationReadyEventListener( public PolarisRefreshApplicationReadyEventListener polarisServiceStatusApplicationReadyEventListener(
PolarisDiscoveryHandler polarisDiscoveryHandler, PolarisSDKContextManager polarisSDKContextManager,
PolarisServiceStatusChangeListener polarisServiceStatusChangeListener) { PolarisServiceStatusChangeListener polarisServiceStatusChangeListener) {
return new PolarisRefreshApplicationReadyEventListener(polarisDiscoveryHandler, polarisServiceStatusChangeListener); return new PolarisRefreshApplicationReadyEventListener(polarisSDKContextManager, polarisServiceStatusChangeListener);
} }
} }

@ -18,7 +18,7 @@
package com.tencent.cloud.polaris.loadbalancer; package com.tencent.cloud.polaris.loadbalancer;
import com.tencent.cloud.polaris.context.ConditionalOnPolarisEnabled; import com.tencent.cloud.polaris.context.ConditionalOnPolarisEnabled;
import com.tencent.polaris.router.api.core.RouterAPI; import com.tencent.cloud.polaris.context.PolarisSDKContextManager;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
@ -79,20 +79,20 @@ public class PolarisLoadBalancerClientConfiguration {
@ConditionalOnMissingBean @ConditionalOnMissingBean
@ConditionalOnProperty(value = "spring.cloud.polaris.loadbalancer.strategy", havingValue = "polarisWeightedRandom") @ConditionalOnProperty(value = "spring.cloud.polaris.loadbalancer.strategy", havingValue = "polarisWeightedRandom")
public ReactorLoadBalancer<ServiceInstance> polarisWeightedLoadBalancer(Environment environment, public ReactorLoadBalancer<ServiceInstance> polarisWeightedLoadBalancer(Environment environment,
LoadBalancerClientFactory loadBalancerClientFactory, RouterAPI routerAPI) { LoadBalancerClientFactory loadBalancerClientFactory, PolarisSDKContextManager polarisSDKContextManager) {
String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME); String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
return new PolarisWeightedRandomLoadBalancer(name, return new PolarisWeightedRandomLoadBalancer(name,
loadBalancerClientFactory.getLazyProvider(name, ServiceInstanceListSupplier.class), routerAPI); loadBalancerClientFactory.getLazyProvider(name, ServiceInstanceListSupplier.class), polarisSDKContextManager.getRouterAPI());
} }
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
@ConditionalOnProperty(value = "spring.cloud.polaris.loadbalancer.strategy", havingValue = "polarisRingHash") @ConditionalOnProperty(value = "spring.cloud.polaris.loadbalancer.strategy", havingValue = "polarisRingHash")
public ReactorLoadBalancer<ServiceInstance> polarisRingHashLoadBalancer(Environment environment, public ReactorLoadBalancer<ServiceInstance> polarisRingHashLoadBalancer(Environment environment,
LoadBalancerClientFactory loadBalancerClientFactory, RouterAPI routerAPI) { LoadBalancerClientFactory loadBalancerClientFactory, PolarisSDKContextManager polarisSDKContextManager) {
String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME); String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
return new PolarisRingHashLoadBalancer(name, return new PolarisRingHashLoadBalancer(name,
loadBalancerClientFactory.getLazyProvider(name, ServiceInstanceListSupplier.class), routerAPI); loadBalancerClientFactory.getLazyProvider(name, ServiceInstanceListSupplier.class), polarisSDKContextManager.getRouterAPI());
} }
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)

@ -26,6 +26,7 @@ import java.util.concurrent.ScheduledExecutorService;
import com.tencent.cloud.common.metadata.StaticMetadataManager; import com.tencent.cloud.common.metadata.StaticMetadataManager;
import com.tencent.cloud.polaris.PolarisDiscoveryProperties; import com.tencent.cloud.polaris.PolarisDiscoveryProperties;
import com.tencent.cloud.polaris.context.PolarisSDKContextManager;
import com.tencent.cloud.polaris.discovery.PolarisDiscoveryHandler; import com.tencent.cloud.polaris.discovery.PolarisDiscoveryHandler;
import com.tencent.cloud.polaris.util.OkHttpUtil; import com.tencent.cloud.polaris.util.OkHttpUtil;
import com.tencent.cloud.rpc.enhancement.stat.config.PolarisStatProperties; import com.tencent.cloud.rpc.enhancement.stat.config.PolarisStatProperties;
@ -33,6 +34,7 @@ import com.tencent.polaris.api.config.global.StatReporterConfig;
import com.tencent.polaris.api.core.ProviderAPI; import com.tencent.polaris.api.core.ProviderAPI;
import com.tencent.polaris.api.exception.PolarisException; import com.tencent.polaris.api.exception.PolarisException;
import com.tencent.polaris.api.plugin.common.PluginTypes; import com.tencent.polaris.api.plugin.common.PluginTypes;
import com.tencent.polaris.api.plugin.stat.ReporterMetaInfo;
import com.tencent.polaris.api.plugin.stat.StatReporter; import com.tencent.polaris.api.plugin.stat.StatReporter;
import com.tencent.polaris.api.pojo.Instance; import com.tencent.polaris.api.pojo.Instance;
import com.tencent.polaris.api.rpc.InstanceDeregisterRequest; import com.tencent.polaris.api.rpc.InstanceDeregisterRequest;
@ -47,6 +49,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils; import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.cloud.client.serviceregistry.ServiceRegistry; import org.springframework.cloud.client.serviceregistry.ServiceRegistry;
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpHeaders;
@ -58,24 +61,25 @@ import static org.springframework.util.ReflectionUtils.rethrowRuntimeException;
* *
* @author Haotian Zhang, Andrew Shan, Jie Cheng, changjin wei() * @author Haotian Zhang, Andrew Shan, Jie Cheng, changjin wei()
*/ */
public class PolarisServiceRegistry implements ServiceRegistry<PolarisRegistration> { public class PolarisServiceRegistry implements ServiceRegistry<PolarisRegistration>, DisposableBean {
private static final Logger LOGGER = LoggerFactory.getLogger(PolarisServiceRegistry.class); private static final Logger LOGGER = LoggerFactory.getLogger(PolarisServiceRegistry.class);
private final PolarisDiscoveryProperties polarisDiscoveryProperties; private final PolarisDiscoveryProperties polarisDiscoveryProperties;
private final PolarisSDKContextManager polarisSDKContextManager;
private final PolarisDiscoveryHandler polarisDiscoveryHandler; private final PolarisDiscoveryHandler polarisDiscoveryHandler;
private final StaticMetadataManager staticMetadataManager; private final StaticMetadataManager staticMetadataManager;
private final ScheduledExecutorService heartbeatExecutor;
private final PolarisStatProperties polarisStatProperties; private final PolarisStatProperties polarisStatProperties;
private final ScheduledExecutorService heartbeatExecutor;
public PolarisServiceRegistry(PolarisDiscoveryProperties polarisDiscoveryProperties, public PolarisServiceRegistry(PolarisDiscoveryProperties polarisDiscoveryProperties,
PolarisDiscoveryHandler polarisDiscoveryHandler, PolarisSDKContextManager polarisSDKContextManager, PolarisDiscoveryHandler polarisDiscoveryHandler,
StaticMetadataManager staticMetadataManager, PolarisStatProperties polarisStatProperties) { StaticMetadataManager staticMetadataManager, PolarisStatProperties polarisStatProperties) {
this.polarisDiscoveryProperties = polarisDiscoveryProperties; this.polarisDiscoveryProperties = polarisDiscoveryProperties;
this.polarisSDKContextManager = polarisSDKContextManager;
this.polarisDiscoveryHandler = polarisDiscoveryHandler; this.polarisDiscoveryHandler = polarisDiscoveryHandler;
this.staticMetadataManager = staticMetadataManager; this.staticMetadataManager = staticMetadataManager;
@ -116,7 +120,7 @@ public class PolarisServiceRegistry implements ServiceRegistry<PolarisRegistrati
instanceRegisterRequest.setVersion(polarisDiscoveryProperties.getVersion()); instanceRegisterRequest.setVersion(polarisDiscoveryProperties.getVersion());
instanceRegisterRequest.setInstanceId(polarisDiscoveryProperties.getInstanceId()); instanceRegisterRequest.setInstanceId(polarisDiscoveryProperties.getInstanceId());
try { try {
ProviderAPI providerClient = polarisDiscoveryHandler.getProviderAPI(); ProviderAPI providerClient = polarisSDKContextManager.getProviderAPI();
InstanceRegisterResponse instanceRegisterResponse; InstanceRegisterResponse instanceRegisterResponse;
if (StringUtils.isBlank(polarisDiscoveryProperties.getHealthCheckUrl())) { if (StringUtils.isBlank(polarisDiscoveryProperties.getHealthCheckUrl())) {
instanceRegisterResponse = providerClient.registerInstance(instanceRegisterRequest); instanceRegisterResponse = providerClient.registerInstance(instanceRegisterRequest);
@ -134,10 +138,16 @@ public class PolarisServiceRegistry implements ServiceRegistry<PolarisRegistrati
staticMetadataManager.getMergedStaticMetadata()); staticMetadataManager.getMergedStaticMetadata());
if (Objects.nonNull(polarisStatProperties) && polarisStatProperties.isEnabled()) { if (Objects.nonNull(polarisStatProperties) && polarisStatProperties.isEnabled()) {
try { try {
StatReporter statReporter = (StatReporter) polarisDiscoveryHandler.getSdkContext().getPlugins() StatReporter statReporter = (StatReporter) polarisSDKContextManager.getSDKContext().getPlugins()
.getPlugin(PluginTypes.STAT_REPORTER.getBaseType(), StatReporterConfig.DEFAULT_REPORTER_PROMETHEUS); .getPlugin(PluginTypes.STAT_REPORTER.getBaseType(), StatReporterConfig.DEFAULT_REPORTER_PROMETHEUS);
if (Objects.nonNull(statReporter)) { if (Objects.nonNull(statReporter)) {
LOGGER.info("Stat server started on port: " + statReporter.metaInfo().getPort() + " (http)"); ReporterMetaInfo reporterMetaInfo = statReporter.metaInfo();
if (reporterMetaInfo.getPort() != null) {
LOGGER.info("Stat server started on port: " + reporterMetaInfo.getPort() + " (http)");
}
else {
LOGGER.info("Stat server is set to type of Push gateway");
}
} }
else { else {
LOGGER.warn("Plugin StatReporter not found"); LOGGER.warn("Plugin StatReporter not found");
@ -148,10 +158,12 @@ public class PolarisServiceRegistry implements ServiceRegistry<PolarisRegistrati
} }
} }
ServiceConfigImpl serviceConfig = (ServiceConfigImpl) polarisDiscoveryHandler.getSdkContext().getConfig() ServiceConfigImpl serviceConfig = (ServiceConfigImpl) polarisSDKContextManager.getSDKContext().getConfig()
.getProvider().getService(); .getProvider().getService();
serviceConfig.setNamespace(polarisDiscoveryProperties.getNamespace()); serviceConfig.setNamespace(polarisDiscoveryProperties.getNamespace());
serviceConfig.setName(serviceId); serviceConfig.setName(serviceId);
PolarisSDKContextManager.isRegistered = true;
} }
catch (Exception e) { catch (Exception e) {
LOGGER.error("polaris registry, {} register failed...{},", registration.getServiceId(), registration, e); LOGGER.error("polaris registry, {} register failed...{},", registration.getServiceId(), registration, e);
@ -176,7 +188,7 @@ public class PolarisServiceRegistry implements ServiceRegistry<PolarisRegistrati
deRegisterRequest.setPort(registration.getPort()); deRegisterRequest.setPort(registration.getPort());
try { try {
ProviderAPI providerClient = polarisDiscoveryHandler.getProviderAPI(); ProviderAPI providerClient = polarisSDKContextManager.getProviderAPI();
providerClient.deRegister(deRegisterRequest); providerClient.deRegister(deRegisterRequest);
} }
catch (Exception e) { catch (Exception e) {
@ -186,8 +198,9 @@ public class PolarisServiceRegistry implements ServiceRegistry<PolarisRegistrati
if (null != heartbeatExecutor) { if (null != heartbeatExecutor) {
heartbeatExecutor.shutdown(); heartbeatExecutor.shutdown();
} }
LOGGER.info("De-registration finished.");
PolarisSDKContextManager.isRegistered = false;
} }
LOGGER.info("De-registration finished.");
} }
@Override @Override
@ -205,7 +218,7 @@ public class PolarisServiceRegistry implements ServiceRegistry<PolarisRegistrati
String serviceName = registration.getServiceId(); String serviceName = registration.getServiceId();
InstancesResponse instancesResponse = polarisDiscoveryHandler.getInstances(serviceName); InstancesResponse instancesResponse = polarisDiscoveryHandler.getInstances(serviceName);
Instance[] instances = instancesResponse.getInstances(); Instance[] instances = instancesResponse.getInstances();
if (null == instances || instances.length == 0) { if (null == instances) {
return null; return null;
} }
for (Instance instance : instances) { for (Instance instance : instances) {
@ -242,7 +255,7 @@ public class PolarisServiceRegistry implements ServiceRegistry<PolarisRegistrati
return; return;
} }
polarisDiscoveryHandler.getProviderAPI().heartbeat(heartbeatRequest); polarisSDKContextManager.getProviderAPI().heartbeat(heartbeatRequest);
LOGGER.trace("Polaris heartbeat is sent"); LOGGER.trace("Polaris heartbeat is sent");
} }
catch (PolarisException e) { catch (PolarisException e) {
@ -253,4 +266,11 @@ public class PolarisServiceRegistry implements ServiceRegistry<PolarisRegistrati
} }
}, polarisDiscoveryProperties.getHeartbeatInterval(), polarisDiscoveryProperties.getHeartbeatInterval(), SECONDS); }, polarisDiscoveryProperties.getHeartbeatInterval(), polarisDiscoveryProperties.getHeartbeatInterval(), SECONDS);
} }
@Override
public void destroy() {
if (heartbeatExecutor != null) {
heartbeatExecutor.shutdown();
}
}
} }

@ -20,14 +20,13 @@ package com.tencent.cloud.polaris.registry;
import com.tencent.cloud.common.metadata.StaticMetadataManager; import com.tencent.cloud.common.metadata.StaticMetadataManager;
import com.tencent.cloud.polaris.PolarisDiscoveryProperties; import com.tencent.cloud.polaris.PolarisDiscoveryProperties;
import com.tencent.cloud.polaris.context.PolarisSDKContextManager;
import com.tencent.cloud.polaris.context.config.PolarisContextProperties; import com.tencent.cloud.polaris.context.config.PolarisContextProperties;
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.cloud.polaris.extend.consul.ConsulContextProperties; import com.tencent.cloud.polaris.extend.consul.ConsulContextProperties;
import com.tencent.cloud.polaris.extend.nacos.NacosContextProperties; import com.tencent.cloud.polaris.extend.nacos.NacosContextProperties;
import com.tencent.cloud.rpc.enhancement.stat.config.PolarisStatProperties; import com.tencent.cloud.rpc.enhancement.stat.config.PolarisStatProperties;
import com.tencent.polaris.assembly.api.AssemblyAPI;
import com.tencent.polaris.client.api.SDKContext;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.AutoConfigureAfter;
@ -57,9 +56,10 @@ public class PolarisServiceRegistryAutoConfiguration {
@Bean @Bean
public PolarisServiceRegistry polarisServiceRegistry( public PolarisServiceRegistry polarisServiceRegistry(
PolarisDiscoveryProperties polarisDiscoveryProperties, PolarisDiscoveryHandler polarisDiscoveryHandler, PolarisDiscoveryProperties polarisDiscoveryProperties, PolarisSDKContextManager polarisSDKContextManager,
PolarisDiscoveryHandler polarisDiscoveryHandler,
StaticMetadataManager staticMetadataManager, PolarisStatProperties polarisStatProperties) { StaticMetadataManager staticMetadataManager, PolarisStatProperties polarisStatProperties) {
return new PolarisServiceRegistry(polarisDiscoveryProperties, polarisDiscoveryHandler, return new PolarisServiceRegistry(polarisDiscoveryProperties, polarisSDKContextManager, polarisDiscoveryHandler,
staticMetadataManager, polarisStatProperties); staticMetadataManager, polarisStatProperties);
} }
@ -69,11 +69,12 @@ public class PolarisServiceRegistryAutoConfiguration {
PolarisDiscoveryProperties polarisDiscoveryProperties, PolarisDiscoveryProperties polarisDiscoveryProperties,
PolarisContextProperties polarisContextProperties, PolarisContextProperties polarisContextProperties,
@Autowired(required = false) ConsulContextProperties consulContextProperties, @Autowired(required = false) ConsulContextProperties consulContextProperties,
SDKContext context, StaticMetadataManager staticMetadataManager, NacosContextProperties nacosContextProperties, PolarisSDKContextManager polarisSDKContextManager, StaticMetadataManager staticMetadataManager,
NacosContextProperties nacosContextProperties,
@Autowired(required = false) ServletWebServerApplicationContext servletWebServerApplicationContext, @Autowired(required = false) ServletWebServerApplicationContext servletWebServerApplicationContext,
@Autowired(required = false) ReactiveWebServerApplicationContext reactiveWebServerApplicationContext) { @Autowired(required = false) ReactiveWebServerApplicationContext reactiveWebServerApplicationContext) {
return new PolarisRegistration(polarisDiscoveryProperties, polarisContextProperties, consulContextProperties, context, return new PolarisRegistration(polarisDiscoveryProperties, polarisContextProperties, consulContextProperties,
staticMetadataManager, nacosContextProperties, polarisSDKContextManager.getSDKContext(), staticMetadataManager, nacosContextProperties,
servletWebServerApplicationContext, reactiveWebServerApplicationContext); servletWebServerApplicationContext, reactiveWebServerApplicationContext);
} }
@ -83,9 +84,9 @@ public class PolarisServiceRegistryAutoConfiguration {
PolarisServiceRegistry registry, PolarisServiceRegistry registry,
AutoServiceRegistrationProperties autoServiceRegistrationProperties, AutoServiceRegistrationProperties autoServiceRegistrationProperties,
PolarisRegistration registration, PolarisRegistration registration,
@Autowired(required = false) AssemblyAPI assemblyAPI PolarisSDKContextManager polarisSDKContextManager
) { ) {
return new PolarisAutoServiceRegistration(registry, autoServiceRegistrationProperties, registration, assemblyAPI); return new PolarisAutoServiceRegistration(registry, autoServiceRegistrationProperties, registration, polarisSDKContextManager.getAssemblyAPI());
} }
@Bean @Bean

@ -20,8 +20,6 @@ package com.tencent.cloud.polaris;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration; import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import com.tencent.cloud.polaris.discovery.PolarisDiscoveryHandler; import com.tencent.cloud.polaris.discovery.PolarisDiscoveryHandler;
import com.tencent.cloud.polaris.extend.consul.ConsulContextProperties; import com.tencent.cloud.polaris.extend.consul.ConsulContextProperties;
import com.tencent.polaris.api.core.ConsumerAPI;
import com.tencent.polaris.api.core.ProviderAPI;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.AutoConfigurations;
@ -48,8 +46,6 @@ public class DiscoveryPropertiesAutoConfigurationTest {
assertThat(context).hasSingleBean(DiscoveryPropertiesAutoConfiguration.class); assertThat(context).hasSingleBean(DiscoveryPropertiesAutoConfiguration.class);
assertThat(context).hasSingleBean(PolarisDiscoveryProperties.class); assertThat(context).hasSingleBean(PolarisDiscoveryProperties.class);
assertThat(context).hasSingleBean(ConsulContextProperties.class); assertThat(context).hasSingleBean(ConsulContextProperties.class);
assertThat(context).hasSingleBean(ProviderAPI.class);
assertThat(context).hasSingleBean(ConsumerAPI.class);
assertThat(context).hasSingleBean(PolarisDiscoveryHandler.class); assertThat(context).hasSingleBean(PolarisDiscoveryHandler.class);
assertThat(context).hasSingleBean(DiscoveryConfigModifier.class); assertThat(context).hasSingleBean(DiscoveryConfigModifier.class);
}); });

@ -19,12 +19,12 @@
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.PolarisSDKContextManager;
import com.tencent.cloud.polaris.context.config.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; import com.tencent.polaris.test.mock.discovery.NamingServer;
import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.AutoConfigurations;
@ -67,11 +67,14 @@ public class PolarisDiscoveryAutoConfigurationTest {
} }
} }
@BeforeEach
void setUp() {
PolarisSDKContextManager.innerDestroy();
}
@Test @Test
public void testDefaultInitialization() { public void testDefaultInitialization() {
this.contextRunner.run(context -> { this.contextRunner.run(context -> {
assertThat(context).hasSingleBean(ProviderAPI.class);
assertThat(context).hasSingleBean(ConsumerAPI.class);
assertThat(context).hasSingleBean(PolarisDiscoveryProperties.class); assertThat(context).hasSingleBean(PolarisDiscoveryProperties.class);
assertThat(context).hasSingleBean(PolarisServiceDiscovery.class); assertThat(context).hasSingleBean(PolarisServiceDiscovery.class);
}); });

@ -17,10 +17,12 @@
package com.tencent.cloud.polaris.discovery; package com.tencent.cloud.polaris.discovery;
import com.tencent.cloud.polaris.context.PolarisSDKContextManager;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration; import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import com.tencent.polaris.test.mock.discovery.NamingServer; import com.tencent.polaris.test.mock.discovery.NamingServer;
import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.AutoConfigurations;
@ -62,6 +64,11 @@ public class PolarisDiscoveryClientConfigurationTest {
} }
} }
@BeforeEach
void setUp() {
PolarisSDKContextManager.innerDestroy();
}
@Test @Test
public void testDefaultInitialization() { public void testDefaultInitialization() {
this.contextRunner.run(context -> assertThat(context).hasSingleBean(PolarisDiscoveryClient.class)); this.contextRunner.run(context -> assertThat(context).hasSingleBean(PolarisDiscoveryClient.class));

@ -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.discovery;
import com.tencent.cloud.polaris.PolarisDiscoveryProperties;
import com.tencent.cloud.polaris.context.PolarisSDKContextManager;
import com.tencent.polaris.api.core.ConsumerAPI;
import com.tencent.polaris.api.exception.PolarisException;
import com.tencent.polaris.api.rpc.ServicesResponse;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import static com.tencent.polaris.test.common.Consts.NAMESPACE_TEST;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
/**
* Test for {@link PolarisDiscoveryHandler}.
*
* @author Haotian Zhang
*/
@ExtendWith(MockitoExtension.class)
public class PolarisDiscoveryHandlerTest {
private PolarisDiscoveryHandler polarisDiscoveryHandler;
@BeforeEach
void setUp() {
PolarisDiscoveryProperties polarisDiscoveryProperties = mock(PolarisDiscoveryProperties.class);
doReturn(NAMESPACE_TEST).when(polarisDiscoveryProperties).getNamespace();
ConsumerAPI consumerAPI = mock(ConsumerAPI.class);
ServicesResponse servicesResponse = mock(ServicesResponse.class);
doReturn(servicesResponse).when(consumerAPI).getServices(any());
PolarisSDKContextManager polarisSDKContextManager = mock(PolarisSDKContextManager.class);
doReturn(consumerAPI).when(polarisSDKContextManager).getConsumerAPI();
polarisDiscoveryHandler = new PolarisDiscoveryHandler(polarisDiscoveryProperties, polarisSDKContextManager);
}
@Test
public void testGetServices() throws PolarisException {
ServicesResponse servicesResponse = polarisDiscoveryHandler.getServices();
assertThat(servicesResponse).isNotNull();
}
}

@ -17,11 +17,13 @@
package com.tencent.cloud.polaris.discovery.reactive; package com.tencent.cloud.polaris.discovery.reactive;
import com.tencent.cloud.polaris.context.PolarisSDKContextManager;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration; import com.tencent.cloud.polaris.context.config.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.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.AutoConfigurations;
@ -65,6 +67,11 @@ public class PolarisReactiveDiscoveryClientConfigurationTest {
} }
} }
@BeforeEach
void setUp() {
PolarisSDKContextManager.innerDestroy();
}
@Test @Test
public void testDefaultInitialization() { public void testDefaultInitialization() {
this.contextRunner.run(context -> assertThat(context).hasSingleBean(PolarisReactiveDiscoveryClient.class)); this.contextRunner.run(context -> assertThat(context).hasSingleBean(PolarisReactiveDiscoveryClient.class));

@ -20,6 +20,7 @@ import java.util.Collections;
import java.util.Map; import java.util.Map;
import com.tencent.cloud.polaris.PolarisDiscoveryProperties; import com.tencent.cloud.polaris.PolarisDiscoveryProperties;
import com.tencent.cloud.polaris.context.PolarisSDKContextManager;
import com.tencent.cloud.polaris.discovery.PolarisDiscoveryAutoConfiguration; import com.tencent.cloud.polaris.discovery.PolarisDiscoveryAutoConfiguration;
import com.tencent.cloud.polaris.discovery.PolarisDiscoveryClient; import com.tencent.cloud.polaris.discovery.PolarisDiscoveryClient;
import com.tencent.cloud.polaris.discovery.PolarisDiscoveryClientConfiguration; import com.tencent.cloud.polaris.discovery.PolarisDiscoveryClientConfiguration;
@ -27,6 +28,7 @@ import com.tencent.cloud.polaris.discovery.PolarisDiscoveryHandler;
import com.tencent.polaris.test.mock.discovery.NamingServer; import com.tencent.polaris.test.mock.discovery.NamingServer;
import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.AutoConfigurations;
@ -75,6 +77,11 @@ public class PolarisDiscoveryEndpointTest {
} }
} }
@BeforeEach
void setUp() {
PolarisSDKContextManager.innerDestroy();
}
@Test @Test
public void testPolarisDiscoveryEndpoint() { public void testPolarisDiscoveryEndpoint() {
this.contextRunner.run(context -> { this.contextRunner.run(context -> {

@ -20,8 +20,9 @@ package com.tencent.cloud.polaris.extend.consul;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import com.tencent.polaris.client.api.SDKContext; import com.tencent.cloud.polaris.context.PolarisSDKContextManager;
import com.tencent.polaris.factory.config.global.ServerConnectorConfigImpl; import com.tencent.polaris.factory.config.global.ServerConnectorConfigImpl;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.ExtendWith;
@ -53,7 +54,12 @@ public class ConsulContextPropertiesTest {
private ConsulContextProperties consulContextProperties; private ConsulContextProperties consulContextProperties;
@Autowired @Autowired
private SDKContext sdkContext; private PolarisSDKContextManager polarisSDKContextManager;
@BeforeEach
void setUp() {
PolarisSDKContextManager.innerDestroy();
}
@Test @Test
public void testDefaultInitialization() { public void testDefaultInitialization() {
@ -67,8 +73,9 @@ public class ConsulContextPropertiesTest {
@Test @Test
public void testModify() { public void testModify() {
assertThat(sdkContext).isNotNull(); assertThat(polarisSDKContextManager).isNotNull();
com.tencent.polaris.api.config.Configuration configuration = sdkContext.getConfig(); com.tencent.polaris.api.config.Configuration configuration = polarisSDKContextManager.getSDKContext()
.getConfig();
List<ServerConnectorConfigImpl> serverConnectorConfigs = configuration.getGlobal().getServerConnectors(); List<ServerConnectorConfigImpl> serverConnectorConfigs = configuration.getGlobal().getServerConnectors();
Map<String, String> metadata = null; Map<String, String> metadata = null;
for (ServerConnectorConfigImpl serverConnectorConfig : serverConnectorConfigs) { for (ServerConnectorConfigImpl serverConnectorConfig : serverConnectorConfigs) {
@ -86,5 +93,8 @@ public class ConsulContextPropertiesTest {
@SpringBootApplication @SpringBootApplication
protected static class TestApplication { protected static class TestApplication {
static {
PolarisSDKContextManager.innerDestroy();
}
} }
} }

@ -22,8 +22,8 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Optional; import java.util.Optional;
import com.tencent.cloud.polaris.context.PolarisSDKContextManager;
import com.tencent.polaris.api.config.plugin.DefaultPlugins; import com.tencent.polaris.api.config.plugin.DefaultPlugins;
import com.tencent.polaris.client.api.SDKContext;
import com.tencent.polaris.factory.config.global.ServerConnectorConfigImpl; import com.tencent.polaris.factory.config.global.ServerConnectorConfigImpl;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.ExtendWith;
@ -51,7 +51,7 @@ public class NacosContextPropertiesTest {
private NacosContextProperties nacosContextProperties; private NacosContextProperties nacosContextProperties;
@Autowired @Autowired
private SDKContext sdkContext; private PolarisSDKContextManager polarisSDKContextManager;
@Test @Test
public void testDefaultInitialization() { public void testDefaultInitialization() {
@ -66,8 +66,9 @@ public class NacosContextPropertiesTest {
@Test @Test
public void testModify() { public void testModify() {
assertThat(sdkContext).isNotNull(); assertThat(polarisSDKContextManager).isNotNull();
com.tencent.polaris.api.config.Configuration configuration = sdkContext.getConfig(); com.tencent.polaris.api.config.Configuration configuration = polarisSDKContextManager.getSDKContext()
.getConfig();
List<ServerConnectorConfigImpl> serverConnectorConfigs = configuration.getGlobal().getServerConnectors(); List<ServerConnectorConfigImpl> serverConnectorConfigs = configuration.getGlobal().getServerConnectors();
Optional<ServerConnectorConfigImpl> optionalServerConnectorConfig = serverConnectorConfigs.stream().filter( Optional<ServerConnectorConfigImpl> optionalServerConnectorConfig = serverConnectorConfigs.stream().filter(
item -> "nacos".equals(item.getId()) item -> "nacos".equals(item.getId())
@ -88,5 +89,9 @@ public class NacosContextPropertiesTest {
@SpringBootApplication @SpringBootApplication
protected static class TestApplication { protected static class TestApplication {
static {
PolarisSDKContextManager.innerDestroy();
}
} }
} }

@ -1,76 +0,0 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.tencent.cloud.polaris.loadbalancer;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import com.tencent.polaris.router.api.core.RouterAPI;
import org.junit.jupiter.api.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 org.assertj.core.api.Assertions.assertThat;
/**
* Test for {@link PolarisLoadBalancerAutoConfiguration}.
*
* @author Haotian Zhang
*/
public class PolarisRouterAutoConfigurationTest {
private final ApplicationContextRunner blockingContextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(
PolarisLoadBalancerTest.class,
PolarisContextAutoConfiguration.class,
PolarisLoadBalancerAutoConfiguration.class))
.withPropertyValues("spring.cloud.loadbalancer.configurations=polaris", "spring.application.name=test");
private final ApplicationContextRunner noPolarisContextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(
PolarisLoadBalancerTest.class,
PolarisContextAutoConfiguration.class,
PolarisLoadBalancerAutoConfiguration.class));
/**
* Test for BlockingDiscovery.
*/
@Test
public void test1() {
this.blockingContextRunner.run(context -> {
assertThat(context).hasSingleBean(RouterAPI.class);
});
}
/**
* Test for no Polaris.
*/
@Test
public void test2() {
this.noPolarisContextRunner.run(context -> {
assertThat(context).hasSingleBean(RouterAPI.class);
});
}
@Configuration
@EnableAutoConfiguration
static class PolarisLoadBalancerTest {
}
}

@ -17,8 +17,9 @@
package com.tencent.cloud.polaris.loadbalancer; package com.tencent.cloud.polaris.loadbalancer;
import com.tencent.cloud.polaris.context.PolarisSDKContextManager;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration; import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import com.tencent.polaris.router.api.core.RouterAPI; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoExtension;
@ -53,10 +54,14 @@ public class PolarisWeightedRandomLoadBalancerAutoConfigurationTest {
PolarisLoadBalancerAutoConfiguration.class, PolarisLoadBalancerAutoConfiguration.class,
PolarisContextAutoConfiguration.class)); PolarisContextAutoConfiguration.class));
@BeforeEach
void setUp() {
PolarisSDKContextManager.innerDestroy();
}
@Test @Test
public void testDefaultInitialization() { public void testDefaultInitialization() {
this.contextRunner.run(context -> { this.contextRunner.run(context -> {
assertThat(context).hasSingleBean(RouterAPI.class);
assertThat(context).hasSingleBean(RestTemplate.class); assertThat(context).hasSingleBean(RestTemplate.class);
assertThatThrownBy(() -> { assertThatThrownBy(() -> {
context.getBean(RestTemplate.class).getForEntity("http://wrong.url", String.class); context.getBean(RestTemplate.class).getForEntity("http://wrong.url", String.class);
@ -67,7 +72,6 @@ public class PolarisWeightedRandomLoadBalancerAutoConfigurationTest {
@Test @Test
public void testRandomInitialization() { public void testRandomInitialization() {
this.contextRunner.withPropertyValues("spring.cloud.polaris.loadbalancer.strategy=random").run(context -> { this.contextRunner.withPropertyValues("spring.cloud.polaris.loadbalancer.strategy=random").run(context -> {
assertThat(context).hasSingleBean(RouterAPI.class);
assertThat(context).hasSingleBean(RestTemplate.class); assertThat(context).hasSingleBean(RestTemplate.class);
assertThatThrownBy(() -> { assertThatThrownBy(() -> {
context.getBean(RestTemplate.class).getForEntity("http://wrong.url", String.class); context.getBean(RestTemplate.class).getForEntity("http://wrong.url", String.class);
@ -77,25 +81,24 @@ public class PolarisWeightedRandomLoadBalancerAutoConfigurationTest {
@Test @Test
public void testPolarisWeightedInitialization() { public void testPolarisWeightedInitialization() {
this.contextRunner.withPropertyValues("spring.cloud.polaris.loadbalancer.strategy=polarisWeightedRandom").run(context -> { this.contextRunner.withPropertyValues("spring.cloud.polaris.loadbalancer.strategy=polarisWeightedRandom")
assertThat(context).hasSingleBean(RouterAPI.class); .run(context -> {
assertThat(context).hasSingleBean(RestTemplate.class); assertThat(context).hasSingleBean(RestTemplate.class);
assertThatThrownBy(() -> { assertThatThrownBy(() -> {
context.getBean(RestTemplate.class).getForEntity("http://wrong.url", String.class); context.getBean(RestTemplate.class).getForEntity("http://wrong.url", String.class);
}).isInstanceOf(Exception.class); }).isInstanceOf(Exception.class);
}); });
} }
@Test @Test
public void testPolarisRingHashInitialization() { public void testPolarisRingHashInitialization() {
this.contextRunner this.contextRunner
.withPropertyValues("spring.cloud.polaris.loadbalancer.strategy=polarisRingHash").run(context -> { .withPropertyValues("spring.cloud.polaris.loadbalancer.strategy=polarisRingHash").run(context -> {
assertThat(context).hasSingleBean(RouterAPI.class);
assertThat(context).hasSingleBean(RestTemplate.class); assertThat(context).hasSingleBean(RestTemplate.class);
assertThatThrownBy(() -> { assertThatThrownBy(() -> {
context.getBean(RestTemplate.class).getForEntity("http://wrong.url", String.class); context.getBean(RestTemplate.class).getForEntity("http://wrong.url", String.class);
}).isInstanceOf(Exception.class); }).isInstanceOf(Exception.class);
}); });
} }
@Configuration @Configuration

@ -17,12 +17,14 @@
package com.tencent.cloud.polaris.registry; package com.tencent.cloud.polaris.registry;
import com.tencent.cloud.polaris.context.PolarisSDKContextManager;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration; import com.tencent.cloud.polaris.context.config.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;
import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.AutoConfigurations;
@ -65,6 +67,11 @@ public class PolarisServiceRegistryAutoConfigurationTest {
} }
} }
@BeforeEach
void setUp() {
PolarisSDKContextManager.innerDestroy();
}
@Test @Test
public void testDefaultInitialization() { public void testDefaultInitialization() {
this.contextRunner.run(context -> { this.contextRunner.run(context -> {

@ -17,6 +17,7 @@
package com.tencent.cloud.polaris.registry; package com.tencent.cloud.polaris.registry;
import com.tencent.cloud.polaris.context.PolarisSDKContextManager;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration; import com.tencent.cloud.polaris.context.config.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;
@ -24,6 +25,7 @@ import com.tencent.polaris.api.pojo.ServiceKey;
import com.tencent.polaris.test.mock.discovery.NamingServer; import com.tencent.polaris.test.mock.discovery.NamingServer;
import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.mockito.Mockito; import org.mockito.Mockito;
@ -89,6 +91,11 @@ public class PolarisServiceRegistryTest {
} }
} }
@BeforeEach
void setUp() {
PolarisSDKContextManager.innerDestroy();
}
@Test @Test
public void testRegister() { public void testRegister() {
this.contextRunner.run(context -> { this.contextRunner.run(context -> {

@ -18,6 +18,7 @@
package com.tencent.cloud.polaris.ratelimit.config; package com.tencent.cloud.polaris.ratelimit.config;
import com.tencent.cloud.polaris.context.PolarisSDKContextManager;
import com.tencent.cloud.polaris.context.ServiceRuleManager; import com.tencent.cloud.polaris.context.ServiceRuleManager;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration; import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import com.tencent.cloud.polaris.ratelimit.filter.QuotaCheckReactiveFilter; import com.tencent.cloud.polaris.ratelimit.filter.QuotaCheckReactiveFilter;
@ -27,9 +28,6 @@ import com.tencent.cloud.polaris.ratelimit.resolver.RateLimitRuleArgumentServlet
import com.tencent.cloud.polaris.ratelimit.spi.PolarisRateLimiterLabelReactiveResolver; import com.tencent.cloud.polaris.ratelimit.spi.PolarisRateLimiterLabelReactiveResolver;
import com.tencent.cloud.polaris.ratelimit.spi.PolarisRateLimiterLabelServletResolver; import com.tencent.cloud.polaris.ratelimit.spi.PolarisRateLimiterLabelServletResolver;
import com.tencent.cloud.polaris.ratelimit.spi.PolarisRateLimiterLimitedFallback; import com.tencent.cloud.polaris.ratelimit.spi.PolarisRateLimiterLimitedFallback;
import com.tencent.polaris.client.api.SDKContext;
import com.tencent.polaris.ratelimit.api.core.LimitAPI;
import com.tencent.polaris.ratelimit.factory.LimitAPIFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.AutoConfigureAfter;
@ -58,12 +56,6 @@ import static jakarta.servlet.DispatcherType.REQUEST;
@ConditionalOnPolarisRateLimitEnabled @ConditionalOnPolarisRateLimitEnabled
public class PolarisRateLimitAutoConfiguration { public class PolarisRateLimitAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public LimitAPI limitAPI(SDKContext polarisContext) {
return LimitAPIFactory.createLimitAPIByContext(polarisContext);
}
/** /**
* Create when web application type is SERVLET. * Create when web application type is SERVLET.
*/ */
@ -79,11 +71,12 @@ public class PolarisRateLimitAutoConfiguration {
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public QuotaCheckServletFilter quotaCheckFilter(LimitAPI limitAPI, public QuotaCheckServletFilter quotaCheckFilter(PolarisSDKContextManager polarisSDKContextManager,
PolarisRateLimitProperties polarisRateLimitProperties, PolarisRateLimitProperties polarisRateLimitProperties,
RateLimitRuleArgumentServletResolver rateLimitRuleArgumentResolver, RateLimitRuleArgumentServletResolver rateLimitRuleArgumentResolver,
@Autowired(required = false) PolarisRateLimiterLimitedFallback polarisRateLimiterLimitedFallback) { @Autowired(required = false) PolarisRateLimiterLimitedFallback polarisRateLimiterLimitedFallback) {
return new QuotaCheckServletFilter(limitAPI, polarisRateLimitProperties, rateLimitRuleArgumentResolver, polarisRateLimiterLimitedFallback); return new QuotaCheckServletFilter(polarisSDKContextManager.getLimitAPI(), polarisRateLimitProperties,
rateLimitRuleArgumentResolver, polarisRateLimiterLimitedFallback);
} }
@Bean @Bean
@ -97,7 +90,6 @@ public class PolarisRateLimitAutoConfiguration {
return registrationBean; return registrationBean;
} }
} }
/** /**
@ -114,11 +106,12 @@ public class PolarisRateLimitAutoConfiguration {
} }
@Bean @Bean
public QuotaCheckReactiveFilter quotaCheckReactiveFilter(LimitAPI limitAPI, public QuotaCheckReactiveFilter quotaCheckReactiveFilter(PolarisSDKContextManager polarisSDKContextManager,
PolarisRateLimitProperties polarisRateLimitProperties, PolarisRateLimitProperties polarisRateLimitProperties,
RateLimitRuleArgumentReactiveResolver rateLimitRuleArgumentResolver, RateLimitRuleArgumentReactiveResolver rateLimitRuleArgumentResolver,
@Nullable PolarisRateLimiterLimitedFallback polarisRateLimiterLimitedFallback) { @Nullable PolarisRateLimiterLimitedFallback polarisRateLimiterLimitedFallback) {
return new QuotaCheckReactiveFilter(limitAPI, polarisRateLimitProperties, rateLimitRuleArgumentResolver, polarisRateLimiterLimitedFallback); return new QuotaCheckReactiveFilter(polarisSDKContextManager.getLimitAPI(), polarisRateLimitProperties,
rateLimitRuleArgumentResolver, polarisRateLimiterLimitedFallback);
} }
} }
} }

@ -15,12 +15,17 @@
* specific language governing permissions and limitations under the License. * specific language governing permissions and limitations under the License.
*/ */
package com.tencent.cloud.polaris.ratelimit.controller; package com.tencent.cloud.polaris.context;
import com.tencent.cloud.polaris.ratelimit.config.PolarisRateLimitProperties;
import com.tencent.cloud.polaris.ratelimit.filter.QuotaCheckServletFilter;
import com.tencent.cloud.polaris.ratelimit.resolver.RateLimitRuleArgumentServletResolver;
import com.tencent.cloud.polaris.ratelimit.spi.PolarisRateLimiterLimitedFallback;
import com.tencent.polaris.api.pojo.ServiceKey; import com.tencent.polaris.api.pojo.ServiceKey;
import com.tencent.polaris.ratelimit.api.core.LimitAPI; import com.tencent.polaris.ratelimit.api.core.LimitAPI;
import com.tencent.polaris.ratelimit.api.rpc.QuotaResponse; import com.tencent.polaris.ratelimit.api.rpc.QuotaResponse;
import com.tencent.polaris.ratelimit.api.rpc.QuotaResultCode; import com.tencent.polaris.ratelimit.api.rpc.QuotaResultCode;
import com.tencent.polaris.ratelimit.factory.LimitAPIFactory;
import com.tencent.polaris.test.mock.discovery.NamingServer; import com.tencent.polaris.test.mock.discovery.NamingServer;
import com.tencent.polaris.test.mock.discovery.NamingService; import com.tencent.polaris.test.mock.discovery.NamingService;
import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterAll;
@ -36,6 +41,7 @@ import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.web.client.HttpClientErrorException.TooManyRequests; import org.springframework.web.client.HttpClientErrorException.TooManyRequests;
import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestClientException;
@ -142,5 +148,19 @@ public class CalleeControllerTests {
return new RestTemplate(); return new RestTemplate();
} }
@Bean
public LimitAPI limitAPI(PolarisSDKContextManager polarisSDKContextManager) {
return LimitAPIFactory.createLimitAPIByContext(polarisSDKContextManager.getSDKContext());
}
@Bean
@Primary
public QuotaCheckServletFilter quotaCheckFilter(LimitAPI limitAPI,
PolarisRateLimitProperties polarisRateLimitProperties,
RateLimitRuleArgumentServletResolver rateLimitRuleArgumentResolver,
@Autowired(required = false) PolarisRateLimiterLimitedFallback polarisRateLimiterLimitedFallback) {
return new QuotaCheckServletFilter(limitAPI, polarisRateLimitProperties,
rateLimitRuleArgumentResolver, polarisRateLimiterLimitedFallback);
}
} }
} }

@ -15,7 +15,7 @@
* specific language governing permissions and limitations under the License. * specific language governing permissions and limitations under the License.
*/ */
package com.tencent.cloud.polaris.ratelimit.controller; package com.tencent.cloud.polaris.context;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;

@ -22,7 +22,6 @@ import com.tencent.cloud.polaris.ratelimit.filter.QuotaCheckReactiveFilter;
import com.tencent.cloud.polaris.ratelimit.filter.QuotaCheckServletFilter; import com.tencent.cloud.polaris.ratelimit.filter.QuotaCheckServletFilter;
import com.tencent.cloud.polaris.ratelimit.resolver.RateLimitRuleArgumentReactiveResolver; import com.tencent.cloud.polaris.ratelimit.resolver.RateLimitRuleArgumentReactiveResolver;
import com.tencent.cloud.polaris.ratelimit.resolver.RateLimitRuleArgumentServletResolver; import com.tencent.cloud.polaris.ratelimit.resolver.RateLimitRuleArgumentServletResolver;
import com.tencent.polaris.ratelimit.api.core.LimitAPI;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.AutoConfigurations;
@ -54,7 +53,6 @@ public class PolarisRateLimitAutoConfigurationTest {
PolarisRateLimitProperties.class, PolarisRateLimitProperties.class,
PolarisRateLimitAutoConfiguration.class)) PolarisRateLimitAutoConfiguration.class))
.run(context -> { .run(context -> {
assertThat(context).hasSingleBean(LimitAPI.class);
assertThat(context).doesNotHaveBean(RateLimitRuleArgumentServletResolver.class); assertThat(context).doesNotHaveBean(RateLimitRuleArgumentServletResolver.class);
assertThat(context).doesNotHaveBean(RateLimitRuleArgumentReactiveResolver.class); assertThat(context).doesNotHaveBean(RateLimitRuleArgumentReactiveResolver.class);
assertThat(context).doesNotHaveBean(PolarisRateLimitAutoConfiguration.QuotaCheckFilterConfig.class); assertThat(context).doesNotHaveBean(PolarisRateLimitAutoConfiguration.QuotaCheckFilterConfig.class);
@ -73,7 +71,6 @@ public class PolarisRateLimitAutoConfigurationTest {
PolarisRateLimitProperties.class, PolarisRateLimitProperties.class,
PolarisRateLimitAutoConfiguration.class)) PolarisRateLimitAutoConfiguration.class))
.run(context -> { .run(context -> {
assertThat(context).hasSingleBean(LimitAPI.class);
assertThat(context).hasSingleBean(RateLimitRuleArgumentServletResolver.class); assertThat(context).hasSingleBean(RateLimitRuleArgumentServletResolver.class);
assertThat(context).hasSingleBean(PolarisRateLimitAutoConfiguration.QuotaCheckFilterConfig.class); assertThat(context).hasSingleBean(PolarisRateLimitAutoConfiguration.QuotaCheckFilterConfig.class);
assertThat(context).hasSingleBean(QuotaCheckServletFilter.class); assertThat(context).hasSingleBean(QuotaCheckServletFilter.class);
@ -92,7 +89,6 @@ public class PolarisRateLimitAutoConfigurationTest {
PolarisRateLimitProperties.class, PolarisRateLimitProperties.class,
PolarisRateLimitAutoConfiguration.class)) PolarisRateLimitAutoConfiguration.class))
.run(context -> { .run(context -> {
assertThat(context).hasSingleBean(LimitAPI.class);
assertThat(context).doesNotHaveBean(RateLimitRuleArgumentServletResolver.class); assertThat(context).doesNotHaveBean(RateLimitRuleArgumentServletResolver.class);
assertThat(context).hasSingleBean(RateLimitRuleArgumentReactiveResolver.class); assertThat(context).hasSingleBean(RateLimitRuleArgumentReactiveResolver.class);
assertThat(context).doesNotHaveBean(PolarisRateLimitAutoConfiguration.QuotaCheckFilterConfig.class); assertThat(context).doesNotHaveBean(PolarisRateLimitAutoConfiguration.QuotaCheckFilterConfig.class);

@ -21,12 +21,12 @@ package com.tencent.cloud.polaris.router.config;
import java.util.List; import java.util.List;
import com.tencent.cloud.common.pojo.PolarisServiceInstance; import com.tencent.cloud.common.pojo.PolarisServiceInstance;
import com.tencent.cloud.polaris.context.PolarisSDKContextManager;
import com.tencent.cloud.polaris.router.PolarisRouterServiceInstanceListSupplier; import com.tencent.cloud.polaris.router.PolarisRouterServiceInstanceListSupplier;
import com.tencent.cloud.polaris.router.spi.RouterRequestInterceptor; import com.tencent.cloud.polaris.router.spi.RouterRequestInterceptor;
import com.tencent.cloud.polaris.router.spi.RouterResponseInterceptor; import com.tencent.cloud.polaris.router.spi.RouterResponseInterceptor;
import com.tencent.cloud.rpc.enhancement.transformer.InstanceTransformer; import com.tencent.cloud.rpc.enhancement.transformer.InstanceTransformer;
import com.tencent.cloud.rpc.enhancement.transformer.PolarisInstanceTransformer; import com.tencent.cloud.rpc.enhancement.transformer.PolarisInstanceTransformer;
import com.tencent.polaris.router.api.core.RouterAPI;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
@ -72,11 +72,11 @@ public class LoadBalancerConfiguration {
@ConditionalOnBean(ReactiveDiscoveryClient.class) @ConditionalOnBean(ReactiveDiscoveryClient.class)
public ServiceInstanceListSupplier polarisRouterDiscoveryClientServiceInstanceListSupplier( public ServiceInstanceListSupplier polarisRouterDiscoveryClientServiceInstanceListSupplier(
ConfigurableApplicationContext context, ConfigurableApplicationContext context,
RouterAPI routerAPI, List<RouterRequestInterceptor> requestInterceptors, PolarisSDKContextManager polarisSDKContextManager, List<RouterRequestInterceptor> requestInterceptors,
List<RouterResponseInterceptor> responseInterceptors, InstanceTransformer instanceTransformer) { List<RouterResponseInterceptor> responseInterceptors, InstanceTransformer instanceTransformer) {
return new PolarisRouterServiceInstanceListSupplier( return new PolarisRouterServiceInstanceListSupplier(
ServiceInstanceListSupplier.builder().withDiscoveryClient().build(context), ServiceInstanceListSupplier.builder().withDiscoveryClient().build(context),
routerAPI, polarisSDKContextManager.getRouterAPI(),
requestInterceptors, requestInterceptors,
responseInterceptors, responseInterceptors,
instanceTransformer); instanceTransformer);
@ -93,11 +93,11 @@ public class LoadBalancerConfiguration {
@ConditionalOnBean(DiscoveryClient.class) @ConditionalOnBean(DiscoveryClient.class)
public ServiceInstanceListSupplier polarisRouterDiscoveryClientServiceInstanceListSupplier( public ServiceInstanceListSupplier polarisRouterDiscoveryClientServiceInstanceListSupplier(
ConfigurableApplicationContext context, ConfigurableApplicationContext context,
RouterAPI routerAPI, List<RouterRequestInterceptor> requestInterceptors, PolarisSDKContextManager polarisSDKContextManager, List<RouterRequestInterceptor> requestInterceptors,
List<RouterResponseInterceptor> responseInterceptors, InstanceTransformer instanceTransformer) { List<RouterResponseInterceptor> responseInterceptors, InstanceTransformer instanceTransformer) {
return new PolarisRouterServiceInstanceListSupplier( return new PolarisRouterServiceInstanceListSupplier(
ServiceInstanceListSupplier.builder().withBlockingDiscoveryClient().build(context), ServiceInstanceListSupplier.builder().withBlockingDiscoveryClient().build(context),
routerAPI, polarisSDKContextManager.getRouterAPI(),
requestInterceptors, requestInterceptors,
responseInterceptors, responseInterceptors,
instanceTransformer); instanceTransformer);

@ -21,7 +21,6 @@ package com.tencent.cloud.polaris.router.config;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration; import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import com.tencent.cloud.polaris.router.PolarisRouterServiceInstanceListSupplier; import com.tencent.cloud.polaris.router.PolarisRouterServiceInstanceListSupplier;
import com.tencent.cloud.rpc.enhancement.transformer.PolarisInstanceTransformer; import com.tencent.cloud.rpc.enhancement.transformer.PolarisInstanceTransformer;
import com.tencent.polaris.router.api.core.RouterAPI;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.AutoConfigurations;
@ -63,7 +62,6 @@ public class LoadBalancerConfigurationTest {
.withBean(PolarisInstanceTransformer.class) .withBean(PolarisInstanceTransformer.class)
.run(context -> { .run(context -> {
assertThat(context).hasSingleBean(LoadBalancerConfiguration.PolarisReactiveSupportConfiguration.class); assertThat(context).hasSingleBean(LoadBalancerConfiguration.PolarisReactiveSupportConfiguration.class);
assertThat(context).hasSingleBean(RouterAPI.class);
assertThat(context).hasSingleBean(ReactiveDiscoveryClient.class); assertThat(context).hasSingleBean(ReactiveDiscoveryClient.class);
assertThat(context).hasSingleBean(PolarisRouterServiceInstanceListSupplier.class); assertThat(context).hasSingleBean(PolarisRouterServiceInstanceListSupplier.class);
}); });
@ -81,7 +79,6 @@ public class LoadBalancerConfigurationTest {
.run(context -> { .run(context -> {
assertThat(context).hasSingleBean(LoadBalancerConfiguration.PolarisBlockingSupportConfiguration.class); assertThat(context).hasSingleBean(LoadBalancerConfiguration.PolarisBlockingSupportConfiguration.class);
assertThat(context).hasSingleBean(DiscoveryClient.class); assertThat(context).hasSingleBean(DiscoveryClient.class);
assertThat(context).hasSingleBean(RouterAPI.class);
assertThat(context).hasSingleBean(PolarisRouterServiceInstanceListSupplier.class); assertThat(context).hasSingleBean(PolarisRouterServiceInstanceListSupplier.class);
}); });
} }

@ -70,7 +70,7 @@
</developers> </developers>
<properties> <properties>
<revision>1.12.0-2022.0.1-SNAPSHOT</revision> <revision>1.12.0-2022.0.2-SNAPSHOT</revision>
<!-- Dependencies --> <!-- Dependencies -->
<polaris.version>1.13.0-SNAPSHOT</polaris.version> <polaris.version>1.13.0-SNAPSHOT</polaris.version>

@ -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.tsf.adapter.config;
import com.tencent.polaris.circuitbreak.api.flow.CircuitBreakerFlow;
import com.tencent.polaris.client.api.SDKContext;
/**
* TsfRouterFlow.
*
* @author sean yu
*/
public class TsfCircuitBreakerFlow implements CircuitBreakerFlow {
@Override
public String getName() {
return PolarisTsfFlowConfigModifier.TSF_FLOW_NAME;
}
@Override
public void setSDKContext(SDKContext 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.tsf.adapter.config;
import com.tencent.polaris.client.api.SDKContext;
import com.tencent.polaris.ratelimit.api.flow.LimitFlow;
/**
* TsfRouterFlow.
*
* @author sean yu
*/
public class TsfLimitFlow implements LimitFlow {
@Override
public String getName() {
return PolarisTsfFlowConfigModifier.TSF_FLOW_NAME;
}
@Override
public void setSDKContext(SDKContext sdkContext) {
}
}

@ -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.plugin.featureenv;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Test for {@link FeatureEnvAutoConfiguration}.
*
* @author Hoatian Zhang
*/
@ExtendWith(MockitoExtension.class)
public class FeatureEnvAutoConfigurationTest {
private final ApplicationContextRunner enabledApplicationContextRunner = new ApplicationContextRunner();
private final ApplicationContextRunner disabledApplicationContextRunner = new ApplicationContextRunner();
@Test
public void testEnabled() {
this.enabledApplicationContextRunner.withConfiguration(AutoConfigurations.of(FeatureEnvAutoConfiguration.class))
.run(context -> {
assertThat(context).hasSingleBean(FeatureEnvProperties.class);
assertThat(context).hasSingleBean(FeatureEnvRouterRequestInterceptor.class);
});
}
@Test
public void testDisabled() {
this.disabledApplicationContextRunner.withConfiguration(AutoConfigurations.of(FeatureEnvAutoConfiguration.class))
.withPropertyValues("spring.cloud.tencent.plugin.router.feature-env.enabled=false")
.run(context -> {
assertThat(context).doesNotHaveBean(FeatureEnvProperties.class);
assertThat(context).doesNotHaveBean(FeatureEnvRouterRequestInterceptor.class);
});
}
}

@ -23,7 +23,7 @@ import com.tencent.cloud.plugin.gateway.staining.rule.RuleStainingExecutor;
import com.tencent.cloud.plugin.gateway.staining.rule.RuleStainingProperties; import com.tencent.cloud.plugin.gateway.staining.rule.RuleStainingProperties;
import com.tencent.cloud.plugin.gateway.staining.rule.RuleTrafficStainer; import com.tencent.cloud.plugin.gateway.staining.rule.RuleTrafficStainer;
import com.tencent.cloud.plugin.gateway.staining.rule.StainingRuleManager; import com.tencent.cloud.plugin.gateway.staining.rule.StainingRuleManager;
import com.tencent.polaris.client.api.SDKContext; import com.tencent.cloud.polaris.context.PolarisSDKContextManager;
import com.tencent.polaris.configuration.api.core.ConfigFileService; import com.tencent.polaris.configuration.api.core.ConfigFileService;
import com.tencent.polaris.configuration.factory.ConfigFileServiceFactory; import com.tencent.polaris.configuration.factory.ConfigFileServiceFactory;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@ -65,8 +65,8 @@ public class SCGPluginsAutoConfigurationTest {
public static class TestApplication { public static class TestApplication {
@Bean @Bean
public ConfigFileService configFileService(SDKContext sdkContext) { public ConfigFileService configFileService(PolarisSDKContextManager polarisSDKContextManager) {
return ConfigFileServiceFactory.createConfigFileService(sdkContext); return ConfigFileServiceFactory.createConfigFileService(polarisSDKContextManager.getSDKContext());
} }
} }
} }

@ -0,0 +1,207 @@
/*
* 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.util.List;
import java.util.Objects;
import com.tencent.cloud.polaris.context.config.PolarisContextProperties;
import com.tencent.polaris.api.control.Destroyable;
import com.tencent.polaris.api.core.ConsumerAPI;
import com.tencent.polaris.api.core.ProviderAPI;
import com.tencent.polaris.assembly.api.AssemblyAPI;
import com.tencent.polaris.assembly.factory.AssemblyAPIFactory;
import com.tencent.polaris.circuitbreak.api.CircuitBreakAPI;
import com.tencent.polaris.circuitbreak.factory.CircuitBreakAPIFactory;
import com.tencent.polaris.client.api.SDKContext;
import com.tencent.polaris.factory.api.DiscoveryAPIFactory;
import com.tencent.polaris.factory.api.RouterAPIFactory;
import com.tencent.polaris.ratelimit.api.core.LimitAPI;
import com.tencent.polaris.ratelimit.factory.LimitAPIFactory;
import com.tencent.polaris.router.api.core.RouterAPI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;
/**
* Manager for static Polaris SDK context.
*
* @author Haotian Zhang
*/
public class PolarisSDKContextManager {
private static final Logger LOG = LoggerFactory.getLogger(PolarisSDKContextManager.class);
/**
* Constant for checking before destroy SDK context.
*/
public volatile static boolean isRegistered = false;
private volatile static SDKContext sdkContext;
private volatile static ProviderAPI providerAPI;
private volatile static ConsumerAPI consumerAPI;
private volatile static RouterAPI routerAPI;
private volatile static CircuitBreakAPI circuitBreakAPI;
private volatile static LimitAPI limitAPI;
private volatile static AssemblyAPI assemblyAPI;
private final PolarisContextProperties properties;
private final Environment environment;
private final List<PolarisConfigModifier> modifierList;
public PolarisSDKContextManager(PolarisContextProperties properties, Environment environment, List<PolarisConfigModifier> modifierList) {
this.properties = properties;
this.environment = environment;
this.modifierList = modifierList;
}
/**
* Don't call this method directly.
*/
public static void innerDestroy() {
if (Objects.nonNull(sdkContext)) {
try {
// destroy ProviderAPI
if (Objects.nonNull(providerAPI)) {
((AutoCloseable) providerAPI).close();
providerAPI = null;
}
// destroy ConsumerAPI
if (Objects.nonNull(consumerAPI)) {
((AutoCloseable) consumerAPI).close();
consumerAPI = null;
}
// destroy RouterAPI
if (Objects.nonNull(routerAPI)) {
((Destroyable) routerAPI).destroy();
routerAPI = null;
}
// destroy CircuitBreakAPI
if (Objects.nonNull(circuitBreakAPI)) {
((Destroyable) circuitBreakAPI).destroy();
circuitBreakAPI = null;
}
// destroy LimitAPI
if (Objects.nonNull(limitAPI)) {
((AutoCloseable) limitAPI).close();
limitAPI = null;
}
// destroy AssemblyAPI
if (Objects.nonNull(assemblyAPI)) {
((Destroyable) assemblyAPI).destroy();
assemblyAPI = null;
}
sdkContext.destroy();
sdkContext = null;
LOG.info("Polaris SDK context is destroyed.");
}
catch (Throwable throwable) {
LOG.error("destroy Polaris SDK context failed.", throwable);
}
}
}
public void init() {
if (null == sdkContext) {
try {
// init SDKContext
sdkContext = SDKContext.initContextByConfig(properties.configuration(modifierList,
() -> environment.getProperty("spring.cloud.client.ip-address"),
() -> environment.getProperty("server.port", Integer.class, 0)));
sdkContext.init();
// init ProviderAPI
providerAPI = DiscoveryAPIFactory.createProviderAPIByContext(sdkContext);
// init ConsumerAPI
consumerAPI = DiscoveryAPIFactory.createConsumerAPIByContext(sdkContext);
// init RouterAPI
routerAPI = RouterAPIFactory.createRouterAPIByContext(sdkContext);
// init CircuitBreakAPI
circuitBreakAPI = CircuitBreakAPIFactory.createCircuitBreakAPIByContext(sdkContext);
// init LimitAPI
limitAPI = LimitAPIFactory.createLimitAPIByContext(sdkContext);
// init AssemblyAPI
assemblyAPI = AssemblyAPIFactory.createAssemblyAPIByContext(sdkContext);
// add shutdown hook
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
long startTimestamp = System.currentTimeMillis();
long delay = 0;
while (true) {
if (!isRegistered || delay >= 60000) {
innerDestroy();
break;
}
else {
delay = System.currentTimeMillis() - startTimestamp;
}
}
}));
LOG.info("create Polaris SDK context successfully. properties: {}, ", properties);
}
catch (Throwable throwable) {
LOG.error("create Polaris SDK context failed. properties: {}, ", properties, throwable);
throw throwable;
}
}
}
public SDKContext getSDKContext() {
init();
return sdkContext;
}
public ProviderAPI getProviderAPI() {
init();
return providerAPI;
}
public ConsumerAPI getConsumerAPI() {
init();
return consumerAPI;
}
public RouterAPI getRouterAPI() {
init();
return routerAPI;
}
public CircuitBreakAPI getCircuitBreakAPI() {
init();
return circuitBreakAPI;
}
public LimitAPI getLimitAPI() {
init();
return limitAPI;
}
public AssemblyAPI getAssemblyAPI() {
return assemblyAPI;
}
}

@ -23,16 +23,10 @@ import java.util.List;
import com.tencent.cloud.polaris.context.ConditionalOnPolarisEnabled; import com.tencent.cloud.polaris.context.ConditionalOnPolarisEnabled;
import com.tencent.cloud.polaris.context.ModifyAddress; import com.tencent.cloud.polaris.context.ModifyAddress;
import com.tencent.cloud.polaris.context.PolarisConfigModifier; import com.tencent.cloud.polaris.context.PolarisConfigModifier;
import com.tencent.cloud.polaris.context.PolarisSDKContextManager;
import com.tencent.cloud.polaris.context.ServiceRuleManager; import com.tencent.cloud.polaris.context.ServiceRuleManager;
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.api.exception.PolarisException;
import com.tencent.polaris.assembly.api.AssemblyAPI;
import com.tencent.polaris.assembly.factory.AssemblyAPIFactory;
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.RouterAPIFactory;
import com.tencent.polaris.router.api.core.RouterAPI;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties;
@ -48,36 +42,10 @@ import org.springframework.core.env.Environment;
@EnableConfigurationProperties({PolarisContextProperties.class}) @EnableConfigurationProperties({PolarisContextProperties.class})
public class PolarisContextAutoConfiguration { public class PolarisContextAutoConfiguration {
@Bean(name = "polarisContext", initMethod = "init", destroyMethod = "destroy") @Bean(initMethod = "init")
@ConditionalOnMissingBean @ConditionalOnMissingBean
public SDKContext polarisContext(PolarisContextProperties properties, Environment environment, List<PolarisConfigModifier> modifierList) throws PolarisException { public PolarisSDKContextManager polarisSDKContextManager(PolarisContextProperties properties, Environment environment, List<PolarisConfigModifier> modifierList) throws PolarisException {
return SDKContext.initContextByConfig(properties.configuration(modifierList, () -> { return new PolarisSDKContextManager(properties, environment, modifierList);
return environment.getProperty("spring.cloud.client.ip-address");
}, () -> {
return environment.getProperty("spring.cloud.polaris.local-port", Integer.class, 0);
}));
}
@Bean
@ConditionalOnMissingBean
public ProviderAPI polarisProvider(SDKContext polarisContext) throws PolarisException {
return DiscoveryAPIFactory.createProviderAPIByContext(polarisContext);
}
@Bean
@ConditionalOnMissingBean
public ConsumerAPI polarisConsumer(SDKContext polarisContext) throws PolarisException {
return DiscoveryAPIFactory.createConsumerAPIByContext(polarisContext);
}
@Bean
public RouterAPI polarisRouter(SDKContext polarisContext) throws PolarisException {
return RouterAPIFactory.createRouterAPIByContext(polarisContext);
}
@Bean
public AssemblyAPI assemblyAPI(SDKContext polarisContext) throws PolarisException {
return AssemblyAPIFactory.createAssemblyAPIByContext(polarisContext);
} }
@Bean @Bean
@ -87,7 +55,7 @@ public class PolarisContextAutoConfiguration {
} }
@Bean @Bean
public ServiceRuleManager serviceRuleManager(SDKContext sdkContext, ConsumerAPI consumerAPI) { public ServiceRuleManager serviceRuleManager(PolarisSDKContextManager polarisSDKContextManager) {
return new ServiceRuleManager(sdkContext, consumerAPI); return new ServiceRuleManager(polarisSDKContextManager.getSDKContext(), polarisSDKContextManager.getConsumerAPI());
} }
} }

@ -20,8 +20,8 @@ package com.tencent.cloud.polaris.context.config;
import com.tencent.cloud.common.metadata.StaticMetadataManager; import com.tencent.cloud.common.metadata.StaticMetadataManager;
import com.tencent.cloud.polaris.context.ConditionalOnPolarisEnabled; import com.tencent.cloud.polaris.context.ConditionalOnPolarisEnabled;
import com.tencent.cloud.polaris.context.PolarisSDKContextManager;
import com.tencent.cloud.polaris.context.PostInitPolarisSDKContext; 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.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
@ -37,7 +37,7 @@ public class PolarisContextPostConfiguration {
@Bean @Bean
public PostInitPolarisSDKContext postInitPolarisSDKContext( public PostInitPolarisSDKContext postInitPolarisSDKContext(
SDKContext sdkContext, StaticMetadataManager staticMetadataManager) { PolarisSDKContextManager polarisSDKContextManager, StaticMetadataManager staticMetadataManager) {
return new PostInitPolarisSDKContext(sdkContext, staticMetadataManager); return new PostInitPolarisSDKContext(polarisSDKContextManager.getSDKContext(), staticMetadataManager);
} }
} }

@ -83,8 +83,10 @@ public class PolarisContextProperties {
defaultHost = ipAddressSupplier.get(); defaultHost = ipAddressSupplier.get();
this.localIpAddress = defaultHost; this.localIpAddress = defaultHost;
} }
Integer defaultPort = this.localPort;
if (this.localPort == null || this.localPort <= 0) { if (this.localPort == null || this.localPort <= 0) {
this.localPort = portSupplier.get(); defaultPort = portSupplier.get();
this.localPort = defaultPort;
} }
configuration.getGlobal().getAPI().setBindIP(defaultHost); configuration.getGlobal().getAPI().setBindIP(defaultHost);
@ -149,4 +151,16 @@ public class PolarisContextProperties {
public void setService(String service) { public void setService(String service) {
this.service = service; this.service = service;
} }
@Override
public String toString() {
return "PolarisContextProperties{" +
"address='" + address + '\'' +
", localIpAddress='" + localIpAddress + '\'' +
", localPort=" + localPort +
", enabled=" + enabled +
", namespace='" + namespace + '\'' +
", service='" + service + '\'' +
'}';
}
} }

@ -43,14 +43,14 @@ import static org.assertj.core.api.Assertions.assertThat;
public class PolarisContextGetHostTest { public class PolarisContextGetHostTest {
@Autowired @Autowired
private SDKContext polarisContext; private PolarisSDKContextManager polarisSDKContextManager;
@Autowired @Autowired
private PolarisContextProperties polarisContextProperties; private PolarisContextProperties polarisContextProperties;
@Test @Test
public void testGetConfigHost() { public void testGetConfigHost() {
String bindIP = polarisContext.getConfig().getGlobal().getAPI().getBindIP(); String bindIP = polarisSDKContextManager.getSDKContext().getConfig().getGlobal().getAPI().getBindIP();
assertThat(StringUtils.isBlank(bindIP)).isFalse(); assertThat(StringUtils.isBlank(bindIP)).isFalse();
assertThat(bindIP).isEqualTo("192.168.1.1"); assertThat(bindIP).isEqualTo("192.168.1.1");
assertThat(polarisContextProperties.getAddress()).isEqualTo("grpc://127.0.0.1:8091"); assertThat(polarisContextProperties.getAddress()).isEqualTo("grpc://127.0.0.1:8091");

@ -17,7 +17,7 @@
package com.tencent.cloud.polaris.context.config; package com.tencent.cloud.polaris.context.config;
import com.tencent.polaris.client.api.SDKContext; import com.tencent.cloud.polaris.context.PolarisSDKContextManager;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.AutoConfigurations;
@ -42,8 +42,8 @@ public class PolarisContextAutoConfigurationTest {
@Test @Test
public void testProperties() { public void testProperties() {
contextRunner.run(context -> { contextRunner.run(context -> {
final SDKContext sdkContext = context.getBean(SDKContext.class); PolarisSDKContextManager polarisSDKContextManager = context.getBean(PolarisSDKContextManager.class);
assertThat(sdkContext).isNotNull(); assertThat(polarisSDKContextManager).isNotNull();
}); });
} }
} }

@ -22,6 +22,7 @@ import java.util.List;
import com.tencent.cloud.common.pojo.PolarisServiceInstance; import com.tencent.cloud.common.pojo.PolarisServiceInstance;
import com.tencent.cloud.polaris.context.ConditionalOnPolarisEnabled; import com.tencent.cloud.polaris.context.ConditionalOnPolarisEnabled;
import com.tencent.cloud.polaris.context.PolarisSDKContextManager;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration; import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import com.tencent.cloud.rpc.enhancement.feign.EnhancedFeignBeanPostProcessor; import com.tencent.cloud.rpc.enhancement.feign.EnhancedFeignBeanPostProcessor;
import com.tencent.cloud.rpc.enhancement.feign.PolarisLoadBalancerFeignRequestTransformer; import com.tencent.cloud.rpc.enhancement.feign.PolarisLoadBalancerFeignRequestTransformer;
@ -45,9 +46,6 @@ import com.tencent.cloud.rpc.enhancement.transformer.InstanceTransformer;
import com.tencent.cloud.rpc.enhancement.transformer.PolarisInstanceTransformer; import com.tencent.cloud.rpc.enhancement.transformer.PolarisInstanceTransformer;
import com.tencent.cloud.rpc.enhancement.webclient.EnhancedWebClientExchangeFilterFunction; import com.tencent.cloud.rpc.enhancement.webclient.EnhancedWebClientExchangeFilterFunction;
import com.tencent.cloud.rpc.enhancement.webclient.PolarisLoadBalancerClientRequestTransformer; import com.tencent.cloud.rpc.enhancement.webclient.PolarisLoadBalancerClientRequestTransformer;
import com.tencent.polaris.api.core.ConsumerAPI;
import com.tencent.polaris.assembly.api.AssemblyAPI;
import com.tencent.polaris.client.api.SDKContext;
import org.springframework.beans.factory.SmartInitializingSingleton; import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -101,50 +99,50 @@ public class RpcEnhancementAutoConfiguration {
public EnhancedPluginRunner enhancedFeignPluginRunner( public EnhancedPluginRunner enhancedFeignPluginRunner(
@Autowired(required = false) List<EnhancedPlugin> enhancedPlugins, @Autowired(required = false) List<EnhancedPlugin> enhancedPlugins,
@Autowired(required = false) Registration registration, @Autowired(required = false) Registration registration,
SDKContext sdkContext) { PolarisSDKContextManager polarisSDKContextManager) {
return new DefaultEnhancedPluginRunner(enhancedPlugins, registration, sdkContext); return new DefaultEnhancedPluginRunner(enhancedPlugins, registration, polarisSDKContextManager.getSDKContext());
} }
@Bean @Bean
public SuccessPolarisReporter successPolarisReporter(RpcEnhancementReporterProperties properties, public SuccessPolarisReporter successPolarisReporter(RpcEnhancementReporterProperties properties,
ConsumerAPI consumerAPI) { PolarisSDKContextManager polarisSDKContextManager) {
return new SuccessPolarisReporter(properties, consumerAPI); return new SuccessPolarisReporter(properties, polarisSDKContextManager.getConsumerAPI());
} }
@Bean @Bean
public ExceptionPolarisReporter exceptionPolarisReporter(RpcEnhancementReporterProperties properties, public ExceptionPolarisReporter exceptionPolarisReporter(RpcEnhancementReporterProperties properties,
ConsumerAPI consumerAPI) { PolarisSDKContextManager polarisSDKContextManager) {
return new ExceptionPolarisReporter(properties, consumerAPI); return new ExceptionPolarisReporter(properties, polarisSDKContextManager.getConsumerAPI());
} }
@Bean @Bean
public AssemblyClientExceptionHook assemblyClientExceptionHook(AssemblyAPI assemblyAPI, InstanceTransformer instanceTransformer) { public AssemblyClientExceptionHook assemblyClientExceptionHook(PolarisSDKContextManager polarisSDKContextManager, InstanceTransformer instanceTransformer) {
return new AssemblyClientExceptionHook(assemblyAPI, instanceTransformer); return new AssemblyClientExceptionHook(polarisSDKContextManager.getAssemblyAPI(), instanceTransformer);
} }
@Bean @Bean
public AssemblyClientPostHook assemblyClientPostHook(AssemblyAPI assemblyAPI, InstanceTransformer instanceTransformer) { public AssemblyClientPostHook assemblyClientPostHook(PolarisSDKContextManager polarisSDKContextManager, InstanceTransformer instanceTransformer) {
return new AssemblyClientPostHook(assemblyAPI, instanceTransformer); return new AssemblyClientPostHook(polarisSDKContextManager.getAssemblyAPI(), instanceTransformer);
} }
@Bean @Bean
public AssemblyClientPreHook assemblyClientPreHook(AssemblyAPI assemblyAPI) { public AssemblyClientPreHook assemblyClientPreHook(PolarisSDKContextManager polarisSDKContextManager) {
return new AssemblyClientPreHook(assemblyAPI); return new AssemblyClientPreHook(polarisSDKContextManager.getAssemblyAPI());
} }
@Bean @Bean
public AssemblyServerExceptionHook assemblyServerExceptionHook(AssemblyAPI assemblyAPI) { public AssemblyServerExceptionHook assemblyServerExceptionHook(PolarisSDKContextManager polarisSDKContextManager) {
return new AssemblyServerExceptionHook(assemblyAPI); return new AssemblyServerExceptionHook(polarisSDKContextManager.getAssemblyAPI());
} }
@Bean @Bean
public AssemblyServerPostHook assemblyServerPostHook(AssemblyAPI assemblyAPI) { public AssemblyServerPostHook assemblyServerPostHook(PolarisSDKContextManager polarisSDKContextManager) {
return new AssemblyServerPostHook(assemblyAPI); return new AssemblyServerPostHook(polarisSDKContextManager.getAssemblyAPI());
} }
@Bean @Bean
public AssemblyServerPreHook assemblyServerPreHook(AssemblyAPI assemblyAPI) { public AssemblyServerPreHook assemblyServerPreHook(PolarisSDKContextManager polarisSDKContextManager) {
return new AssemblyServerPreHook(assemblyAPI); return new AssemblyServerPreHook(polarisSDKContextManager.getAssemblyAPI());
} }
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
@ -288,7 +286,5 @@ public class RpcEnhancementAutoConfiguration {
public EnhancedGatewayGlobalFilter enhancedPolarisGatewayReporter(@Lazy EnhancedPluginRunner pluginRunner) { public EnhancedGatewayGlobalFilter enhancedPolarisGatewayReporter(@Lazy EnhancedPluginRunner pluginRunner) {
return new EnhancedGatewayGlobalFilter(pluginRunner); return new EnhancedGatewayGlobalFilter(pluginRunner);
} }
} }
} }

@ -23,7 +23,6 @@ import com.tencent.cloud.rpc.enhancement.plugin.EnhancedPluginRunner;
import com.tencent.cloud.rpc.enhancement.plugin.reporter.ExceptionPolarisReporter; import com.tencent.cloud.rpc.enhancement.plugin.reporter.ExceptionPolarisReporter;
import com.tencent.cloud.rpc.enhancement.plugin.reporter.SuccessPolarisReporter; import com.tencent.cloud.rpc.enhancement.plugin.reporter.SuccessPolarisReporter;
import com.tencent.cloud.rpc.enhancement.resttemplate.EnhancedRestTemplateInterceptor; import com.tencent.cloud.rpc.enhancement.resttemplate.EnhancedRestTemplateInterceptor;
import com.tencent.polaris.api.core.ConsumerAPI;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.AutoConfigurations;
@ -55,7 +54,6 @@ public class RpcEnhancementAutoConfigurationTest {
@Test @Test
public void testDefaultInitialization() { public void testDefaultInitialization() {
this.contextRunner.run(context -> { this.contextRunner.run(context -> {
assertThat(context).hasSingleBean(ConsumerAPI.class);
assertThat(context).hasSingleBean(EnhancedPluginRunner.class); assertThat(context).hasSingleBean(EnhancedPluginRunner.class);
assertThat(context).hasSingleBean(EnhancedFeignBeanPostProcessor.class); assertThat(context).hasSingleBean(EnhancedFeignBeanPostProcessor.class);
assertThat(context).hasSingleBean(SuccessPolarisReporter.class); assertThat(context).hasSingleBean(SuccessPolarisReporter.class);

@ -22,11 +22,11 @@ import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import com.tencent.cloud.polaris.context.PolarisSDKContextManager;
import com.tencent.cloud.rpc.enhancement.plugin.DefaultEnhancedPluginRunner; import com.tencent.cloud.rpc.enhancement.plugin.DefaultEnhancedPluginRunner;
import com.tencent.cloud.rpc.enhancement.plugin.EnhancedPlugin; import com.tencent.cloud.rpc.enhancement.plugin.EnhancedPlugin;
import com.tencent.cloud.rpc.enhancement.plugin.EnhancedPluginContext; import com.tencent.cloud.rpc.enhancement.plugin.EnhancedPluginContext;
import com.tencent.cloud.rpc.enhancement.plugin.EnhancedPluginType; import com.tencent.cloud.rpc.enhancement.plugin.EnhancedPluginType;
import com.tencent.polaris.client.api.SDKContext;
import feign.Client; import feign.Client;
import feign.Request; import feign.Request;
import feign.RequestTemplate; import feign.RequestTemplate;
@ -58,7 +58,7 @@ import static org.mockito.Mockito.mock;
public class EnhancedFeignClientTest { public class EnhancedFeignClientTest {
@Autowired @Autowired
private SDKContext sdkContext; private PolarisSDKContextManager polarisSDKContextManager;
@Test @Test
public void testConstructor() { public void testConstructor() {
@ -80,7 +80,8 @@ public class EnhancedFeignClientTest {
List<EnhancedPlugin> enhancedPlugins = getMockEnhancedFeignPlugins(); List<EnhancedPlugin> enhancedPlugins = getMockEnhancedFeignPlugins();
try { try {
new EnhancedFeignClient(mock(Client.class), new DefaultEnhancedPluginRunner(enhancedPlugins, null, sdkContext)); new EnhancedFeignClient(mock(Client.class),
new DefaultEnhancedPluginRunner(enhancedPlugins, null, polarisSDKContextManager.getSDKContext()));
} }
catch (Throwable e) { catch (Throwable e) {
fail("Exception encountered.", e); fail("Exception encountered.", e);
@ -109,7 +110,8 @@ public class EnhancedFeignClientTest {
RequestTemplate requestTemplate = new RequestTemplate(); RequestTemplate requestTemplate = new RequestTemplate();
requestTemplate.feignTarget(target); requestTemplate.feignTarget(target);
EnhancedFeignClient polarisFeignClient = new EnhancedFeignClient(delegate, new DefaultEnhancedPluginRunner(getMockEnhancedFeignPlugins(), null, sdkContext)); EnhancedFeignClient polarisFeignClient = new EnhancedFeignClient(delegate,
new DefaultEnhancedPluginRunner(getMockEnhancedFeignPlugins(), null, polarisSDKContextManager.getSDKContext()));
// 200 // 200
Response response = polarisFeignClient.execute(Request.create(Request.HttpMethod.GET, "http://localhost:8080/test", Response response = polarisFeignClient.execute(Request.create(Request.HttpMethod.GET, "http://localhost:8080/test",

@ -17,8 +17,9 @@
package com.tencent.cloud.rpc.enhancement.stat.config; package com.tencent.cloud.rpc.enhancement.stat.config;
import com.tencent.polaris.client.api.SDKContext; import com.tencent.cloud.polaris.context.PolarisSDKContextManager;
import com.tencent.polaris.plugins.stat.prometheus.handler.PrometheusHandlerConfig; import com.tencent.polaris.plugins.stat.prometheus.handler.PrometheusHandlerConfig;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.AutoConfigurations;
@ -62,11 +63,17 @@ public class StatConfigModifierTest {
.withPropertyValues("spring.application.name=test") .withPropertyValues("spring.application.name=test")
.withPropertyValues("spring.cloud.gateway.enabled=false"); .withPropertyValues("spring.cloud.gateway.enabled=false");
@BeforeEach
void setUp() {
PolarisSDKContextManager.innerDestroy();
}
@Test @Test
void testPull() { void testPull() {
pullContextRunner.run(context -> { pullContextRunner.run(context -> {
SDKContext sdkContext = context.getBean(SDKContext.class); PolarisSDKContextManager polarisSDKContextManager = context.getBean(PolarisSDKContextManager.class);
PrometheusHandlerConfig prometheusHandlerConfig = sdkContext.getConfig().getGlobal().getStatReporter() PrometheusHandlerConfig prometheusHandlerConfig = polarisSDKContextManager.getSDKContext().getConfig()
.getGlobal().getStatReporter()
.getPluginConfig(DEFAULT_REPORTER_PROMETHEUS, PrometheusHandlerConfig.class); .getPluginConfig(DEFAULT_REPORTER_PROMETHEUS, PrometheusHandlerConfig.class);
assertThat(prometheusHandlerConfig.getType()).isEqualTo("pull"); assertThat(prometheusHandlerConfig.getType()).isEqualTo("pull");
assertThat(prometheusHandlerConfig.getHost()).isEqualTo("127.0.0.1"); assertThat(prometheusHandlerConfig.getHost()).isEqualTo("127.0.0.1");
@ -78,8 +85,9 @@ public class StatConfigModifierTest {
@Test @Test
void testPush() { void testPush() {
pushContextRunner.run(context -> { pushContextRunner.run(context -> {
SDKContext sdkContext = context.getBean(SDKContext.class); PolarisSDKContextManager polarisSDKContextManager = context.getBean(PolarisSDKContextManager.class);
PrometheusHandlerConfig prometheusHandlerConfig = sdkContext.getConfig().getGlobal().getStatReporter() PrometheusHandlerConfig prometheusHandlerConfig = polarisSDKContextManager.getSDKContext().getConfig()
.getGlobal().getStatReporter()
.getPluginConfig(DEFAULT_REPORTER_PROMETHEUS, PrometheusHandlerConfig.class); .getPluginConfig(DEFAULT_REPORTER_PROMETHEUS, PrometheusHandlerConfig.class);
assertThat(prometheusHandlerConfig.getType()).isEqualTo("push"); assertThat(prometheusHandlerConfig.getType()).isEqualTo("push");
assertThat(prometheusHandlerConfig.getAddress()).isEqualTo("127.0.0.1:9091"); assertThat(prometheusHandlerConfig.getAddress()).isEqualTo("127.0.0.1:9091");
@ -90,8 +98,9 @@ public class StatConfigModifierTest {
@Test @Test
void testDisabled() { void testDisabled() {
disabledContextRunner.run(context -> { disabledContextRunner.run(context -> {
SDKContext sdkContext = context.getBean(SDKContext.class); PolarisSDKContextManager polarisSDKContextManager = context.getBean(PolarisSDKContextManager.class);
PrometheusHandlerConfig prometheusHandlerConfig = sdkContext.getConfig().getGlobal().getStatReporter() PrometheusHandlerConfig prometheusHandlerConfig = polarisSDKContextManager.getSDKContext().getConfig()
.getGlobal().getStatReporter()
.getPluginConfig(DEFAULT_REPORTER_PROMETHEUS, PrometheusHandlerConfig.class); .getPluginConfig(DEFAULT_REPORTER_PROMETHEUS, PrometheusHandlerConfig.class);
assertThat(prometheusHandlerConfig.getPort()).isEqualTo(-1); assertThat(prometheusHandlerConfig.getPort()).isEqualTo(-1);
}); });

Loading…
Cancel
Save