diff --git a/CHANGELOG.md b/CHANGELOG.md index b8059147e..bf3c972d9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,3 +5,4 @@ - [feat:Remove error log from `DecodeTransferMetadataReactiveFilter`.](https://github.com/Tencent/spring-cloud-tencent/pull/990) - [Feature: add AssemblyFlow to support tsf.](https://github.com/Tencent/spring-cloud-tencent/pull/994) - [Refactoring: Refactor Circuitbreaker ut.](https://github.com/Tencent/spring-cloud-tencent/pull/998) +- [feat:refactor SDKContext as static.](https://github.com/Tencent/spring-cloud-tencent/pull/1005) diff --git a/README-zh.md b/README-zh.md index f108454ac..02d1d6806 100644 --- a/README-zh.md +++ b/README-zh.md @@ -78,7 +78,7 @@ Spring Cloud Tencent 所有组件都已上传到 Maven 中央仓库,只需要 com.tencent.cloud spring-cloud-tencent-dependencies - 1.11.1-2020.0.6 + 1.11.4-2020.0.6 pom import diff --git a/README.md b/README.md index b92663998..5123a19af 100644 --- a/README.md +++ b/README.md @@ -80,7 +80,7 @@ For example: com.tencent.cloud spring-cloud-tencent-dependencies - 1.11.1-2020.0.6 + 1.11.4-2020.0.6 pom import diff --git a/spring-cloud-starter-tencent-polaris-circuitbreaker/src/main/java/com/tencent/cloud/polaris/circuitbreaker/config/PolarisCircuitBreakerAutoConfiguration.java b/spring-cloud-starter-tencent-polaris-circuitbreaker/src/main/java/com/tencent/cloud/polaris/circuitbreaker/config/PolarisCircuitBreakerAutoConfiguration.java index 70999eff4..61c72b340 100644 --- a/spring-cloud-starter-tencent-polaris-circuitbreaker/src/main/java/com/tencent/cloud/polaris/circuitbreaker/config/PolarisCircuitBreakerAutoConfiguration.java +++ b/spring-cloud-starter-tencent-polaris-circuitbreaker/src/main/java/com/tencent/cloud/polaris/circuitbreaker/config/PolarisCircuitBreakerAutoConfiguration.java @@ -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.SuccessCircuitBreakerReporter; 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.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.boot.autoconfigure.AutoConfigureAfter; @@ -58,29 +55,31 @@ public class PolarisCircuitBreakerAutoConfiguration { private List> customizers = new ArrayList<>(); @Bean - @ConditionalOnMissingBean(CircuitBreakAPI.class) - public CircuitBreakAPI circuitBreakAPI(SDKContext polarisContext) { - return CircuitBreakAPIFactory.createCircuitBreakAPIByContext(polarisContext); + @ConditionalOnClass(name = "org.springframework.web.client.RestTemplate") + public static PolarisCircuitBreakerRestTemplateBeanPostProcessor polarisCircuitBreakerRestTemplateBeanPostProcessor( + ApplicationContext applicationContext) { + return new PolarisCircuitBreakerRestTemplateBeanPostProcessor(applicationContext); } @Bean @ConditionalOnMissingBean(SuccessCircuitBreakerReporter.class) public SuccessCircuitBreakerReporter successCircuitBreakerReporter(RpcEnhancementReporterProperties properties, - CircuitBreakAPI circuitBreakAPI) { - return new SuccessCircuitBreakerReporter(properties, circuitBreakAPI); + PolarisSDKContextManager polarisSDKContextManager) { + return new SuccessCircuitBreakerReporter(properties, polarisSDKContextManager.getCircuitBreakAPI()); } @Bean @ConditionalOnMissingBean(ExceptionCircuitBreakerReporter.class) public ExceptionCircuitBreakerReporter exceptionCircuitBreakerReporter(RpcEnhancementReporterProperties properties, - CircuitBreakAPI circuitBreakAPI) { - return new ExceptionCircuitBreakerReporter(properties, circuitBreakAPI); + PolarisSDKContextManager polarisSDKContextManager) { + return new ExceptionCircuitBreakerReporter(properties, polarisSDKContextManager.getCircuitBreakAPI()); } @Bean @ConditionalOnMissingBean(CircuitBreakerFactory.class) - public CircuitBreakerFactory polarisCircuitBreakerFactory(CircuitBreakAPI circuitBreakAPI, ConsumerAPI consumerAPI) { - PolarisCircuitBreakerFactory factory = new PolarisCircuitBreakerFactory(circuitBreakAPI, consumerAPI); + public CircuitBreakerFactory polarisCircuitBreakerFactory(PolarisSDKContextManager polarisSDKContextManager) { + PolarisCircuitBreakerFactory factory = new PolarisCircuitBreakerFactory( + polarisSDKContextManager.getCircuitBreakAPI(), polarisSDKContextManager.getConsumerAPI()); customizers.forEach(customizer -> customizer.customize(factory)); return factory; } @@ -92,11 +91,4 @@ public class PolarisCircuitBreakerAutoConfiguration { return new CircuitBreakerConfigModifier(properties); } - @Bean - @ConditionalOnClass(name = "org.springframework.web.client.RestTemplate") - public static PolarisCircuitBreakerRestTemplateBeanPostProcessor polarisCircuitBreakerRestTemplateBeanPostProcessor( - ApplicationContext applicationContext) { - return new PolarisCircuitBreakerRestTemplateBeanPostProcessor(applicationContext); - } - } diff --git a/spring-cloud-starter-tencent-polaris-circuitbreaker/src/main/java/com/tencent/cloud/polaris/circuitbreaker/config/ReactivePolarisCircuitBreakerAutoConfiguration.java b/spring-cloud-starter-tencent-polaris-circuitbreaker/src/main/java/com/tencent/cloud/polaris/circuitbreaker/config/ReactivePolarisCircuitBreakerAutoConfiguration.java index fba34d253..460df385d 100644 --- a/spring-cloud-starter-tencent-polaris-circuitbreaker/src/main/java/com/tencent/cloud/polaris/circuitbreaker/config/ReactivePolarisCircuitBreakerAutoConfiguration.java +++ b/spring-cloud-starter-tencent-polaris-circuitbreaker/src/main/java/com/tencent/cloud/polaris/circuitbreaker/config/ReactivePolarisCircuitBreakerAutoConfiguration.java @@ -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.reporter.ExceptionCircuitBreakerReporter; 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.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.boot.autoconfigure.AutoConfigureAfter; @@ -47,7 +44,7 @@ import org.springframework.context.annotation.Configuration; * @author seanyu 2023-02-27 */ @Configuration(proxyBeanMethods = false) -@ConditionalOnClass(name = { "reactor.core.publisher.Mono", "reactor.core.publisher.Flux" }) +@ConditionalOnClass(name = {"reactor.core.publisher.Mono", "reactor.core.publisher.Flux"}) @ConditionalOnPolarisCircuitBreakerEnabled @AutoConfigureAfter(RpcEnhancementAutoConfiguration.class) public class ReactivePolarisCircuitBreakerAutoConfiguration { @@ -55,30 +52,25 @@ public class ReactivePolarisCircuitBreakerAutoConfiguration { @Autowired(required = false) private List> customizers = new ArrayList<>(); - @Bean - @ConditionalOnMissingBean(CircuitBreakAPI.class) - public CircuitBreakAPI circuitBreakAPI(SDKContext polarisContext) { - return CircuitBreakAPIFactory.createCircuitBreakAPIByContext(polarisContext); - } - @Bean @ConditionalOnMissingBean(SuccessCircuitBreakerReporter.class) public SuccessCircuitBreakerReporter successCircuitBreakerReporter(RpcEnhancementReporterProperties properties, - CircuitBreakAPI circuitBreakAPI) { - return new SuccessCircuitBreakerReporter(properties, circuitBreakAPI); + PolarisSDKContextManager polarisSDKContextManager) { + return new SuccessCircuitBreakerReporter(properties, polarisSDKContextManager.getCircuitBreakAPI()); } @Bean @ConditionalOnMissingBean(ExceptionCircuitBreakerReporter.class) public ExceptionCircuitBreakerReporter exceptionCircuitBreakerReporter(RpcEnhancementReporterProperties properties, - CircuitBreakAPI circuitBreakAPI) { - return new ExceptionCircuitBreakerReporter(properties, circuitBreakAPI); + PolarisSDKContextManager polarisSDKContextManager) { + return new ExceptionCircuitBreakerReporter(properties, polarisSDKContextManager.getCircuitBreakAPI()); } @Bean @ConditionalOnMissingBean(ReactiveCircuitBreakerFactory.class) - public ReactiveCircuitBreakerFactory polarisReactiveCircuitBreakerFactory(CircuitBreakAPI circuitBreakAPI, ConsumerAPI consumerAPI) { - ReactivePolarisCircuitBreakerFactory factory = new ReactivePolarisCircuitBreakerFactory(circuitBreakAPI, consumerAPI); + public ReactiveCircuitBreakerFactory polarisReactiveCircuitBreakerFactory(PolarisSDKContextManager polarisSDKContextManager) { + ReactivePolarisCircuitBreakerFactory factory = new ReactivePolarisCircuitBreakerFactory( + polarisSDKContextManager.getCircuitBreakAPI(), polarisSDKContextManager.getConsumerAPI()); customizers.forEach(customizer -> customizer.customize(factory)); return factory; } diff --git a/spring-cloud-starter-tencent-polaris-circuitbreaker/src/test/java/com/tencent/cloud/polaris/circuitbreaker/PolarisCircuitBreakerMockServerTest.java b/spring-cloud-starter-tencent-polaris-circuitbreaker/src/test/java/com/tencent/cloud/polaris/circuitbreaker/PolarisCircuitBreakerMockServerTest.java index d8fca4068..5c2c1338a 100644 --- a/spring-cloud-starter-tencent-polaris-circuitbreaker/src/test/java/com/tencent/cloud/polaris/circuitbreaker/PolarisCircuitBreakerMockServerTest.java +++ b/spring-cloud-starter-tencent-polaris-circuitbreaker/src/test/java/com/tencent/cloud/polaris/circuitbreaker/PolarisCircuitBreakerMockServerTest.java @@ -30,6 +30,7 @@ import java.util.stream.Collectors; import com.google.protobuf.util.JsonFormat; 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.core.ConsumerAPI; import com.tencent.polaris.api.pojo.ServiceKey; @@ -76,7 +77,7 @@ public class PolarisCircuitBreakerMockServerTest { .thenReturn(NAMESPACE_TEST); mockedApplicationContextAwareUtils.when(() -> ApplicationContextAwareUtils.getProperties("spring.cloud.polaris.service")) .thenReturn(SERVICE_CIRCUIT_BREAKER); - + PolarisSDKContextManager.innerDestroy(); namingServer = NamingServer.startNamingServer(-1); System.setProperty(SERVER_ADDRESS_ENV, String.format("127.0.0.1:%d", namingServer.getPort())); @@ -96,7 +97,9 @@ public class PolarisCircuitBreakerMockServerTest { if (null != namingServer) { namingServer.terminate(); } - mockedApplicationContextAwareUtils.close(); + if (null != mockedApplicationContextAwareUtils) { + mockedApplicationContextAwareUtils.close(); + } } @Test @@ -143,7 +146,6 @@ public class PolarisCircuitBreakerMockServerTest { .collectList().block()) .isEqualTo(Collections.singletonList("fallback")); - } } diff --git a/spring-cloud-starter-tencent-polaris-circuitbreaker/src/test/java/com/tencent/cloud/polaris/circuitbreaker/config/PolarisCircuitBreakerAutoConfigurationTest.java b/spring-cloud-starter-tencent-polaris-circuitbreaker/src/test/java/com/tencent/cloud/polaris/circuitbreaker/config/PolarisCircuitBreakerAutoConfigurationTest.java index a35694c2b..54db3d4e7 100644 --- a/spring-cloud-starter-tencent-polaris-circuitbreaker/src/test/java/com/tencent/cloud/polaris/circuitbreaker/config/PolarisCircuitBreakerAutoConfigurationTest.java +++ b/spring-cloud-starter-tencent-polaris-circuitbreaker/src/test/java/com/tencent/cloud/polaris/circuitbreaker/config/PolarisCircuitBreakerAutoConfigurationTest.java @@ -20,7 +20,6 @@ package com.tencent.cloud.polaris.circuitbreaker.config; import com.tencent.cloud.polaris.circuitbreaker.common.CircuitBreakerConfigModifier; import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration; import com.tencent.cloud.rpc.enhancement.config.RpcEnhancementAutoConfiguration; -import com.tencent.polaris.circuitbreak.api.CircuitBreakAPI; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; @@ -61,7 +60,6 @@ public class PolarisCircuitBreakerAutoConfigurationTest { assertThat(context).hasSingleBean(PolarisCircuitBreakerAutoConfiguration.class); assertThat(context).hasSingleBean(CircuitBreakerFactory.class); assertThat(context).hasSingleBean(CircuitBreakerConfigModifier.class); - assertThat(context).hasSingleBean(CircuitBreakAPI.class); assertThat(context).hasSingleBean(CircuitBreakerNameResolver.class); }); } @@ -72,10 +70,7 @@ public class PolarisCircuitBreakerAutoConfigurationTest { assertThat(context).hasSingleBean(ReactivePolarisCircuitBreakerAutoConfiguration.class); assertThat(context).hasSingleBean(ReactiveCircuitBreakerFactory.class); assertThat(context).hasSingleBean(CircuitBreakerConfigModifier.class); - assertThat(context).hasSingleBean(CircuitBreakAPI.class); }); } - - } diff --git a/spring-cloud-starter-tencent-polaris-circuitbreaker/src/test/java/com/tencent/cloud/polaris/circuitbreaker/feign/PolarisCircuitBreakerFeignIntegrationTest.java b/spring-cloud-starter-tencent-polaris-circuitbreaker/src/test/java/com/tencent/cloud/polaris/circuitbreaker/feign/PolarisCircuitBreakerFeignIntegrationTest.java index 085a8e9fe..cdde3388f 100644 --- a/spring-cloud-starter-tencent-polaris-circuitbreaker/src/test/java/com/tencent/cloud/polaris/circuitbreaker/feign/PolarisCircuitBreakerFeignIntegrationTest.java +++ b/spring-cloud-starter-tencent-polaris-circuitbreaker/src/test/java/com/tencent/cloud/polaris/circuitbreaker/feign/PolarisCircuitBreakerFeignIntegrationTest.java @@ -24,14 +24,22 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.InvocationTargetException; import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; import java.util.stream.Collectors; 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.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.circuitbreak.api.CircuitBreakAPI; import com.tencent.polaris.circuitbreak.factory.CircuitBreakAPIFactory; 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.test.common.TestUtils; 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.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.ImportAutoConfiguration; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; 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.openfeign.EnableFeignClients; import org.springframework.cloud.openfeign.FallbackFactory; @@ -71,7 +82,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen "feign.circuitbreaker.enabled=true", "spring.cloud.polaris.namespace=" + NAMESPACE_TEST, "spring.cloud.polaris.service=test" -}) + }) public class PolarisCircuitBreakerFeignIntegrationTest { private static final String TEST_SERVICE_NAME = "test-service-callee"; @@ -89,7 +100,7 @@ public class PolarisCircuitBreakerFeignIntegrationTest { private BazService bazService; @Test - public void contextLoads() throws Exception { + public void contextLoads() { assertThat(echoService).isNotNull(); assertThat(fooService).isNotNull(); } @@ -113,12 +124,52 @@ public class PolarisCircuitBreakerFeignIntegrationTest { 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 @EnableAutoConfiguration - @ImportAutoConfiguration({ PolarisCircuitBreakerFeignClientAutoConfiguration.class }) + @ImportAutoConfiguration({PolarisCircuitBreakerFeignClientAutoConfiguration.class}) @EnableFeignClients public static class TestConfig { + @Autowired(required = false) + private List> customizers = new ArrayList<>(); + @Bean public EchoServiceFallback 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())); ServiceKey serviceKey = new ServiceKey(NAMESPACE_TEST, TEST_SERVICE_NAME); - CircuitBreakerProto.CircuitBreakerRule.Builder circuitBreakerRuleBuilder = CircuitBreakerProto.CircuitBreakerRule.newBuilder(); - InputStream inputStream = PolarisCircuitBreakerFeignIntegrationTest.class.getClassLoader().getResourceAsStream("circuitBreakerRule.json"); - String json = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)).lines().collect(Collectors.joining("")); + CircuitBreakerProto.CircuitBreakerRule.Builder circuitBreakerRuleBuilder = CircuitBreakerProto.CircuitBreakerRule.newBuilder(); + InputStream inputStream = PolarisCircuitBreakerFeignIntegrationTest.class.getClassLoader() + .getResourceAsStream("circuitBreakerRule.json"); + String json = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)).lines() + .collect(Collectors.joining("")); JsonFormat.parser().ignoringUnknownFields().merge(json, circuitBreakerRuleBuilder); 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); return namingServer; } @@ -156,43 +210,33 @@ public class PolarisCircuitBreakerFeignIntegrationTest { return CircuitBreakAPIFactory.createCircuitBreakAPIByConfig(configuration); } - } - - @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(); + @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); + } - @FeignClient(value = TEST_SERVICE_NAME, contextId = "4") - public interface BazClient extends BazService { + @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; + } } public static class EchoServiceFallback implements EchoService { @@ -219,7 +263,7 @@ public class PolarisCircuitBreakerFeignIntegrationTest { public static class CustomFallbackFactory implements FallbackFactory { - private FooService fooService = new FooServiceFallback(); + private final FooService fooService = new FooServiceFallback(); @Override public FooService create(Throwable throwable) { @@ -231,9 +275,11 @@ public class PolarisCircuitBreakerFeignIntegrationTest { public static class PreDestroy implements DisposableBean { private final NamingServer namingServer; + public PreDestroy(NamingServer namingServer) { this.namingServer = namingServer; } + @Override public void destroy() throws Exception { namingServer.terminate(); diff --git a/spring-cloud-starter-tencent-polaris-circuitbreaker/src/test/java/com/tencent/cloud/polaris/circuitbreaker/gateway/PolarisCircuitBreakerGatewayIntegrationTest.java b/spring-cloud-starter-tencent-polaris-circuitbreaker/src/test/java/com/tencent/cloud/polaris/circuitbreaker/gateway/PolarisCircuitBreakerGatewayIntegrationTest.java index ab07a1a3b..2aec7cc5a 100644 --- a/spring-cloud-starter-tencent-polaris-circuitbreaker/src/test/java/com/tencent/cloud/polaris/circuitbreaker/gateway/PolarisCircuitBreakerGatewayIntegrationTest.java +++ b/spring-cloud-starter-tencent-polaris-circuitbreaker/src/test/java/com/tencent/cloud/polaris/circuitbreaker/gateway/PolarisCircuitBreakerGatewayIntegrationTest.java @@ -23,16 +23,24 @@ import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; +import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; +import java.util.List; import java.util.Set; import java.util.stream.Collectors; 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.circuitbreak.api.CircuitBreakAPI; import com.tencent.polaris.circuitbreak.factory.CircuitBreakAPIFactory; 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.test.common.TestUtils; 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.annotation.Autowired; 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.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.gateway.filter.factory.SpringCloudCircuitBreakerFilterFactory; import org.springframework.cloud.gateway.route.RouteLocator; @@ -152,6 +163,9 @@ public class PolarisCircuitBreakerGatewayIntegrationTest { @EnableAutoConfiguration public static class TestApplication { + @Autowired(required = false) + private List> customizers = new ArrayList<>(); + @Bean public PreDestroy preDestroy(NamingServer 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())); ServiceKey serviceKey = new ServiceKey(NAMESPACE_TEST, TEST_SERVICE_NAME); - CircuitBreakerProto.CircuitBreakerRule.Builder circuitBreakerRuleBuilder = CircuitBreakerProto.CircuitBreakerRule.newBuilder(); - InputStream inputStream = PolarisCircuitBreakerGatewayIntegrationTest.class.getClassLoader().getResourceAsStream("circuitBreakerRule.json"); - String json = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)).lines().collect(Collectors.joining("")); + CircuitBreakerProto.CircuitBreakerRule.Builder circuitBreakerRuleBuilder = CircuitBreakerProto.CircuitBreakerRule.newBuilder(); + InputStream inputStream = PolarisCircuitBreakerGatewayIntegrationTest.class.getClassLoader() + .getResourceAsStream("circuitBreakerRule.json"); + String json = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)).lines() + .collect(Collectors.joining("")); JsonFormat.parser().ignoringUnknownFields().merge(json, circuitBreakerRuleBuilder); 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); return namingServer; } @@ -179,6 +196,34 @@ public class PolarisCircuitBreakerGatewayIntegrationTest { 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 public RouteLocator myRoutes(RouteLocatorBuilder builder) { Set codeSets = new HashSet<>(); @@ -225,9 +270,11 @@ public class PolarisCircuitBreakerGatewayIntegrationTest { public static class PreDestroy implements DisposableBean { private final NamingServer namingServer; + public PreDestroy(NamingServer namingServer) { this.namingServer = namingServer; } + @Override public void destroy() throws Exception { namingServer.terminate(); diff --git a/spring-cloud-starter-tencent-polaris-circuitbreaker/src/test/java/com/tencent/cloud/polaris/circuitbreaker/resttemplate/PolarisCircuitBreakerRestTemplateIntegrationTest.java b/spring-cloud-starter-tencent-polaris-circuitbreaker/src/test/java/com/tencent/cloud/polaris/circuitbreaker/resttemplate/PolarisCircuitBreakerRestTemplateIntegrationTest.java index 75d931f2e..1d12a2dc0 100644 --- a/spring-cloud-starter-tencent-polaris-circuitbreaker/src/test/java/com/tencent/cloud/polaris/circuitbreaker/resttemplate/PolarisCircuitBreakerRestTemplateIntegrationTest.java +++ b/spring-cloud-starter-tencent-polaris-circuitbreaker/src/test/java/com/tencent/cloud/polaris/circuitbreaker/resttemplate/PolarisCircuitBreakerRestTemplateIntegrationTest.java @@ -24,11 +24,18 @@ import java.io.InputStreamReader; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; +import java.util.ArrayList; import java.util.HashMap; +import java.util.List; import java.util.stream.Collectors; 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.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.circuitbreak.api.CircuitBreakAPI; 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.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.ImportAutoConfiguration; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; 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.openfeign.EnableFeignClients; import org.springframework.context.ApplicationContext; @@ -136,7 +146,8 @@ public class PolarisCircuitBreakerRestTemplateIntegrationTest { Utils.sleepUninterrupted(2000); assertThat(restTemplateFallbackFromCode2.getForObject("/example/service/b/info", String.class)).isEqualTo("\"this is a fallback class\""); 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); assertThat(restTemplateFallbackFromCode4.getForObject("/example/service/b/info", String.class)).isEqualTo("fallback"); Utils.sleepUninterrupted(2000); @@ -149,10 +160,17 @@ public class PolarisCircuitBreakerRestTemplateIntegrationTest { @Configuration @EnableAutoConfiguration - @ImportAutoConfiguration({ PolarisCircuitBreakerFeignClientAutoConfiguration.class }) + @ImportAutoConfiguration({PolarisCircuitBreakerFeignClientAutoConfiguration.class}) @EnableFeignClients public static class TestConfig { + @Autowired(required = false) + private List> customizers = new ArrayList<>(); + + { + PolarisSDKContextManager.innerDestroy(); + } + @Bean @com.tencent.cloud.polaris.circuitbreaker.resttemplate.PolarisCircuitBreaker(fallback = "fallback") public RestTemplate defaultRestTemplate() { @@ -229,12 +247,15 @@ public class PolarisCircuitBreakerRestTemplateIntegrationTest { NamingServer namingServer = NamingServer.startNamingServer(-1); System.setProperty(SERVER_ADDRESS_ENV, String.format("127.0.0.1:%d", namingServer.getPort())); ServiceKey serviceKey = new ServiceKey(NAMESPACE_TEST, TEST_SERVICE_NAME); - CircuitBreakerProto.CircuitBreakerRule.Builder circuitBreakerRuleBuilder = CircuitBreakerProto.CircuitBreakerRule.newBuilder(); - InputStream inputStream = PolarisCircuitBreakerRestTemplateIntegrationTest.class.getClassLoader().getResourceAsStream("circuitBreakerRule.json"); - String json = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)).lines().collect(Collectors.joining("")); + CircuitBreakerProto.CircuitBreakerRule.Builder circuitBreakerRuleBuilder = CircuitBreakerProto.CircuitBreakerRule.newBuilder(); + InputStream inputStream = PolarisCircuitBreakerRestTemplateIntegrationTest.class.getClassLoader() + .getResourceAsStream("circuitBreakerRule.json"); + String json = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)).lines() + .collect(Collectors.joining("")); JsonFormat.parser().ignoringUnknownFields().merge(json, circuitBreakerRuleBuilder); 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); return namingServer; } @@ -250,6 +271,30 @@ public class PolarisCircuitBreakerRestTemplateIntegrationTest { 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 @RequestMapping("/example/service/b") public class ServiceBController { @@ -302,14 +347,15 @@ public class PolarisCircuitBreakerRestTemplateIntegrationTest { public static class PreDestroy implements DisposableBean { private final NamingServer namingServer; + public PreDestroy(NamingServer namingServer) { this.namingServer = namingServer; } + @Override public void destroy() throws Exception { namingServer.terminate(); } } - } diff --git a/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/PolarisConfigBootstrapAutoConfiguration.java b/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/PolarisConfigBootstrapAutoConfiguration.java index 237533c64..925342f9c 100644 --- a/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/PolarisConfigBootstrapAutoConfiguration.java +++ b/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/PolarisConfigBootstrapAutoConfiguration.java @@ -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.condition.ConditionalOnReflectRefreshType; 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.PolarisContextProperties; -import com.tencent.polaris.client.api.SDKContext; import com.tencent.polaris.configuration.api.core.ConfigFileService; import com.tencent.polaris.configuration.factory.ConfigFileServiceFactory; @@ -60,8 +60,8 @@ public class PolarisConfigBootstrapAutoConfiguration { @Bean @ConditionalOnConnectRemoteServerEnabled - public ConfigFileService configFileService(SDKContext sdkContext) { - return ConfigFileServiceFactory.createConfigFileService(sdkContext); + public ConfigFileService configFileService(PolarisSDKContextManager polarisSDKContextManager) { + return ConfigFileServiceFactory.createConfigFileService(polarisSDKContextManager.getSDKContext()); } @Bean diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/DiscoveryPropertiesAutoConfiguration.java b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/DiscoveryPropertiesAutoConfiguration.java index 258ba7799..8d4a751b6 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/DiscoveryPropertiesAutoConfiguration.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/DiscoveryPropertiesAutoConfiguration.java @@ -18,14 +18,12 @@ package com.tencent.cloud.polaris; 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.extend.consul.ConsulConfigModifier; import com.tencent.cloud.polaris.extend.consul.ConsulContextProperties; import com.tencent.cloud.polaris.extend.nacos.NacosConfigModifier; 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.boot.autoconfigure.condition.ConditionalOnMissingBean; @@ -46,9 +44,8 @@ public class DiscoveryPropertiesAutoConfiguration { @Bean @ConditionalOnMissingBean public PolarisDiscoveryHandler polarisDiscoveryHandler(PolarisDiscoveryProperties polarisDiscoveryProperties, - ProviderAPI providerAPI, SDKContext sdkContext, - ConsumerAPI polarisConsumer) { - return new PolarisDiscoveryHandler(polarisDiscoveryProperties, providerAPI, sdkContext, polarisConsumer); + PolarisSDKContextManager polarisSDKContextManager) { + return new PolarisDiscoveryHandler(polarisDiscoveryProperties, polarisSDKContextManager); } @Bean @@ -65,13 +62,13 @@ public class DiscoveryPropertiesAutoConfiguration { @Bean @ConditionalOnMissingBean - public NacosConfigModifier nacosConfigModifier(@Autowired(required = false) NacosContextProperties nacosContextProperties) { - return new NacosConfigModifier(nacosContextProperties); + public PolarisDiscoveryConfigModifier polarisDiscoveryConfigModifier(PolarisDiscoveryProperties polarisDiscoveryProperties) { + return new PolarisDiscoveryConfigModifier(polarisDiscoveryProperties); } @Bean @ConditionalOnMissingBean - public PolarisDiscoveryConfigModifier polarisDiscoveryConfigModifier(PolarisDiscoveryProperties polarisDiscoveryProperties) { - return new PolarisDiscoveryConfigModifier(polarisDiscoveryProperties); + public NacosConfigModifier nacosConfigModifier(@Autowired(required = false) NacosContextProperties nacosContextProperties) { + return new NacosConfigModifier(nacosContextProperties); } } diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/PolarisDiscoveryHandler.java b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/PolarisDiscoveryHandler.java index 688562d76..cce659d14 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/PolarisDiscoveryHandler.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/PolarisDiscoveryHandler.java @@ -19,14 +19,13 @@ 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.core.ProviderAPI; import com.tencent.polaris.api.rpc.GetAllInstancesRequest; import com.tencent.polaris.api.rpc.GetHealthyInstancesRequest; import com.tencent.polaris.api.rpc.GetServicesRequest; import com.tencent.polaris.api.rpc.InstancesResponse; import com.tencent.polaris.api.rpc.ServicesResponse; -import com.tencent.polaris.client.api.SDKContext; /** * Discovery Handler for Polaris. @@ -37,18 +36,12 @@ public class PolarisDiscoveryHandler { private final PolarisDiscoveryProperties polarisDiscoveryProperties; - private final ProviderAPI providerAPI; - - private final SDKContext sdkContext; - private final ConsumerAPI polarisConsumer; public PolarisDiscoveryHandler(PolarisDiscoveryProperties polarisDiscoveryProperties, - ProviderAPI providerAPI, SDKContext sdkContext, ConsumerAPI polarisConsumer) { + PolarisSDKContextManager polarisSDKContextManager) { this.polarisDiscoveryProperties = polarisDiscoveryProperties; - this.providerAPI = providerAPI; - this.sdkContext = sdkContext; - this.polarisConsumer = polarisConsumer; + this.polarisConsumer = polarisSDKContextManager.getConsumerAPI(); } /** @@ -75,15 +68,7 @@ public class PolarisDiscoveryHandler { GetAllInstancesRequest request = new GetAllInstancesRequest(); request.setNamespace(namespace); request.setService(service); - return polarisConsumer.getAllInstance(request); - } - - public ProviderAPI getProviderAPI() { - return providerAPI; - } - - public SDKContext getSdkContext() { - return sdkContext; + return polarisConsumer.getAllInstances(request); } /** diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/refresh/PolarisRefreshApplicationReadyEventListener.java b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/refresh/PolarisRefreshApplicationReadyEventListener.java index 22fa821aa..6bbe9b2db 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/refresh/PolarisRefreshApplicationReadyEventListener.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/refresh/PolarisRefreshApplicationReadyEventListener.java @@ -21,7 +21,7 @@ import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; 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 org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -32,7 +32,6 @@ import org.springframework.cloud.client.discovery.event.HeartbeatEvent; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationEventPublisherAware; import org.springframework.context.ApplicationListener; -import org.springframework.lang.NonNull; import static com.tencent.cloud.polaris.discovery.refresh.PolarisServiceStatusChangeListener.INDEX; @@ -46,13 +45,14 @@ public class PolarisRefreshApplicationReadyEventListener private static final Logger LOG = LoggerFactory.getLogger(PolarisRefreshApplicationReadyEventListener.class); private static final int DELAY = 60; - private final PolarisDiscoveryHandler polarisDiscoveryHandler; + private final PolarisSDKContextManager polarisSDKContextManager; private final PolarisServiceStatusChangeListener polarisServiceStatusChangeListener; private final ScheduledExecutorService refreshExecutor; private ApplicationEventPublisher publisher; - public PolarisRefreshApplicationReadyEventListener(PolarisDiscoveryHandler polarisDiscoveryHandler, PolarisServiceStatusChangeListener polarisServiceStatusChangeListener) { - this.polarisDiscoveryHandler = polarisDiscoveryHandler; + public PolarisRefreshApplicationReadyEventListener(PolarisSDKContextManager polarisSDKContextManager, + PolarisServiceStatusChangeListener polarisServiceStatusChangeListener) { + this.polarisSDKContextManager = polarisSDKContextManager; this.polarisServiceStatusChangeListener = polarisServiceStatusChangeListener; this.refreshExecutor = Executors.newSingleThreadScheduledExecutor( new NamedThreadFactory("polaris-service-refresh")); @@ -61,7 +61,7 @@ public class PolarisRefreshApplicationReadyEventListener @Override public void onApplicationEvent(ApplicationReadyEvent event) { // Register service change listener. - polarisDiscoveryHandler.getSdkContext().getExtensions().getLocalRegistry() + polarisSDKContextManager.getSDKContext().getExtensions().getLocalRegistry() .registerResourceListener(polarisServiceStatusChangeListener); // Begin scheduled refresh thread. @@ -84,12 +84,12 @@ public class PolarisRefreshApplicationReadyEventListener } @Override - public void setApplicationEventPublisher(@NonNull ApplicationEventPublisher applicationEventPublisher) { + public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { this.publisher = applicationEventPublisher; } @Override - public void destroy() throws Exception { + public void destroy() { refreshExecutor.shutdown(); } } diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/refresh/PolarisRefreshConfiguration.java b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/refresh/PolarisRefreshConfiguration.java index c0523fa51..d8abf683c 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/refresh/PolarisRefreshConfiguration.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/discovery/refresh/PolarisRefreshConfiguration.java @@ -18,7 +18,7 @@ package com.tencent.cloud.polaris.discovery.refresh; 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.context.annotation.Bean; @@ -42,8 +42,8 @@ public class PolarisRefreshConfiguration { @Bean @ConditionalOnMissingBean public PolarisRefreshApplicationReadyEventListener polarisServiceStatusApplicationReadyEventListener( - PolarisDiscoveryHandler polarisDiscoveryHandler, + PolarisSDKContextManager polarisSDKContextManager, PolarisServiceStatusChangeListener polarisServiceStatusChangeListener) { - return new PolarisRefreshApplicationReadyEventListener(polarisDiscoveryHandler, polarisServiceStatusChangeListener); + return new PolarisRefreshApplicationReadyEventListener(polarisSDKContextManager, polarisServiceStatusChangeListener); } } diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/loadbalancer/PolarisLoadBalancerClientConfiguration.java b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/loadbalancer/PolarisLoadBalancerClientConfiguration.java index bda6babc3..934b95bd7 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/loadbalancer/PolarisLoadBalancerClientConfiguration.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/loadbalancer/PolarisLoadBalancerClientConfiguration.java @@ -18,7 +18,7 @@ package com.tencent.cloud.polaris.loadbalancer; 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.ConditionalOnMissingBean; @@ -79,20 +79,20 @@ public class PolarisLoadBalancerClientConfiguration { @ConditionalOnMissingBean @ConditionalOnProperty(value = "spring.cloud.polaris.loadbalancer.strategy", havingValue = "polarisWeightedRandom") public ReactorLoadBalancer polarisWeightedLoadBalancer(Environment environment, - LoadBalancerClientFactory loadBalancerClientFactory, RouterAPI routerAPI) { + LoadBalancerClientFactory loadBalancerClientFactory, PolarisSDKContextManager polarisSDKContextManager) { String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME); return new PolarisWeightedRandomLoadBalancer(name, - loadBalancerClientFactory.getLazyProvider(name, ServiceInstanceListSupplier.class), routerAPI); + loadBalancerClientFactory.getLazyProvider(name, ServiceInstanceListSupplier.class), polarisSDKContextManager.getRouterAPI()); } @Bean @ConditionalOnMissingBean @ConditionalOnProperty(value = "spring.cloud.polaris.loadbalancer.strategy", havingValue = "polarisRingHash") public ReactorLoadBalancer polarisRingHashLoadBalancer(Environment environment, - LoadBalancerClientFactory loadBalancerClientFactory, RouterAPI routerAPI) { + LoadBalancerClientFactory loadBalancerClientFactory, PolarisSDKContextManager polarisSDKContextManager) { String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME); return new PolarisRingHashLoadBalancer(name, - loadBalancerClientFactory.getLazyProvider(name, ServiceInstanceListSupplier.class), routerAPI); + loadBalancerClientFactory.getLazyProvider(name, ServiceInstanceListSupplier.class), polarisSDKContextManager.getRouterAPI()); } @Configuration(proxyBeanMethods = false) diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/registry/PolarisServiceRegistry.java b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/registry/PolarisServiceRegistry.java index 63e340386..557b10735 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/registry/PolarisServiceRegistry.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/main/java/com/tencent/cloud/polaris/registry/PolarisServiceRegistry.java @@ -26,6 +26,7 @@ import java.util.concurrent.ScheduledExecutorService; import com.tencent.cloud.common.metadata.StaticMetadataManager; 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.util.OkHttpUtil; 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.exception.PolarisException; 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.pojo.Instance; import com.tencent.polaris.api.rpc.InstanceDeregisterRequest; @@ -47,6 +49,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeanUtils; +import org.springframework.beans.factory.DisposableBean; import org.springframework.cloud.client.serviceregistry.ServiceRegistry; 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(魏昌进) */ -public class PolarisServiceRegistry implements ServiceRegistry { +public class PolarisServiceRegistry implements ServiceRegistry, DisposableBean { private static final Logger LOGGER = LoggerFactory.getLogger(PolarisServiceRegistry.class); private final PolarisDiscoveryProperties polarisDiscoveryProperties; + private final PolarisSDKContextManager polarisSDKContextManager; + private final PolarisDiscoveryHandler polarisDiscoveryHandler; private final StaticMetadataManager staticMetadataManager; - - private final ScheduledExecutorService heartbeatExecutor; - private final PolarisStatProperties polarisStatProperties; + private final ScheduledExecutorService heartbeatExecutor; public PolarisServiceRegistry(PolarisDiscoveryProperties polarisDiscoveryProperties, - PolarisDiscoveryHandler polarisDiscoveryHandler, + PolarisSDKContextManager polarisSDKContextManager, PolarisDiscoveryHandler polarisDiscoveryHandler, StaticMetadataManager staticMetadataManager, PolarisStatProperties polarisStatProperties) { this.polarisDiscoveryProperties = polarisDiscoveryProperties; + this.polarisSDKContextManager = polarisSDKContextManager; this.polarisDiscoveryHandler = polarisDiscoveryHandler; this.staticMetadataManager = staticMetadataManager; @@ -116,7 +120,7 @@ public class PolarisServiceRegistry implements ServiceRegistry { - assertThat(context).hasSingleBean(ProviderAPI.class); - assertThat(context).hasSingleBean(ConsumerAPI.class); assertThat(context).hasSingleBean(PolarisDiscoveryProperties.class); assertThat(context).hasSingleBean(PolarisServiceDiscovery.class); }); diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/discovery/PolarisDiscoveryClientConfigurationTest.java b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/discovery/PolarisDiscoveryClientConfigurationTest.java index b53fce9f2..b33dc8c52 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/discovery/PolarisDiscoveryClientConfigurationTest.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/discovery/PolarisDiscoveryClientConfigurationTest.java @@ -17,10 +17,12 @@ package com.tencent.cloud.polaris.discovery; +import com.tencent.cloud.polaris.context.PolarisSDKContextManager; import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration; import com.tencent.polaris.test.mock.discovery.NamingServer; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; @@ -62,6 +64,11 @@ public class PolarisDiscoveryClientConfigurationTest { } } + @BeforeEach + void setUp() { + PolarisSDKContextManager.innerDestroy(); + } + @Test public void testDefaultInitialization() { this.contextRunner.run(context -> assertThat(context).hasSingleBean(PolarisDiscoveryClient.class)); diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/discovery/PolarisDiscoveryHandlerTest.java b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/discovery/PolarisDiscoveryHandlerTest.java new file mode 100644 index 000000000..821e366e9 --- /dev/null +++ b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/discovery/PolarisDiscoveryHandlerTest.java @@ -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(); + } +} diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/discovery/reactive/PolarisReactiveDiscoveryClientConfigurationTest.java b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/discovery/reactive/PolarisReactiveDiscoveryClientConfigurationTest.java index 8b6e5813b..d4efe34e7 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/discovery/reactive/PolarisReactiveDiscoveryClientConfigurationTest.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/discovery/reactive/PolarisReactiveDiscoveryClientConfigurationTest.java @@ -17,11 +17,13 @@ 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.discovery.PolarisDiscoveryClientConfiguration; import com.tencent.polaris.test.mock.discovery.NamingServer; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; @@ -36,7 +38,7 @@ import static org.assertj.core.api.Assertions.assertThat; /** * Test for {@link PolarisReactiveDiscoveryClientConfiguration}. * - * @author Haotian Zhang + * @author Haotian Zhang, youta */ public class PolarisReactiveDiscoveryClientConfigurationTest { @@ -45,7 +47,8 @@ public class PolarisReactiveDiscoveryClientConfigurationTest { private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() .withConfiguration(AutoConfigurations.of( PolarisContextAutoConfiguration.class, - PolarisReactiveDiscoveryClientConfiguration.class, PolarisDiscoveryClientConfiguration.class, + PolarisReactiveDiscoveryClientConfiguration.class, + PolarisDiscoveryClientConfiguration.class, PolarisContextAutoConfiguration.class)) .withPropertyValues("spring.application.name=" + SERVICE_PROVIDER) .withPropertyValues("server.port=" + PORT) @@ -64,6 +67,11 @@ public class PolarisReactiveDiscoveryClientConfigurationTest { } } + @BeforeEach + void setUp() { + PolarisSDKContextManager.innerDestroy(); + } + @Test public void testDefaultInitialization() { this.contextRunner.run(context -> assertThat(context).hasSingleBean(PolarisReactiveDiscoveryClient.class)); @@ -74,6 +82,7 @@ public class PolarisReactiveDiscoveryClientConfigurationTest { contextRunner.run(context -> assertThat(context).hasBean("polarisReactiveDiscoveryClientHealthIndicator")); } + @Configuration @EnableAutoConfiguration static class PolarisReactiveDiscoveryClientConfiguration { diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/endpoint/PolarisDiscoveryEndpointTest.java b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/endpoint/PolarisDiscoveryEndpointTest.java index d8ff2b813..bb1bbb481 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/endpoint/PolarisDiscoveryEndpointTest.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/endpoint/PolarisDiscoveryEndpointTest.java @@ -20,6 +20,7 @@ import java.util.Collections; import java.util.Map; 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.PolarisDiscoveryClient; 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 org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; @@ -75,6 +77,11 @@ public class PolarisDiscoveryEndpointTest { } } + @BeforeEach + void setUp() { + PolarisSDKContextManager.innerDestroy(); + } + @Test public void testPolarisDiscoveryEndpoint() { this.contextRunner.run(context -> { diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/extend/consul/ConsulContextPropertiesTest.java b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/extend/consul/ConsulContextPropertiesTest.java index ec5580159..1d545b4e5 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/extend/consul/ConsulContextPropertiesTest.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/extend/consul/ConsulContextPropertiesTest.java @@ -20,8 +20,9 @@ package com.tencent.cloud.polaris.extend.consul; import java.util.List; 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 org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -53,7 +54,12 @@ public class ConsulContextPropertiesTest { private ConsulContextProperties consulContextProperties; @Autowired - private SDKContext sdkContext; + private PolarisSDKContextManager polarisSDKContextManager; + + @BeforeEach + void setUp() { + PolarisSDKContextManager.innerDestroy(); + } @Test public void testDefaultInitialization() { @@ -67,8 +73,9 @@ public class ConsulContextPropertiesTest { @Test public void testModify() { - assertThat(sdkContext).isNotNull(); - com.tencent.polaris.api.config.Configuration configuration = sdkContext.getConfig(); + assertThat(polarisSDKContextManager).isNotNull(); + com.tencent.polaris.api.config.Configuration configuration = polarisSDKContextManager.getSDKContext() + .getConfig(); List serverConnectorConfigs = configuration.getGlobal().getServerConnectors(); Map metadata = null; for (ServerConnectorConfigImpl serverConnectorConfig : serverConnectorConfigs) { @@ -86,5 +93,8 @@ public class ConsulContextPropertiesTest { @SpringBootApplication protected static class TestApplication { + static { + PolarisSDKContextManager.innerDestroy(); + } } } diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/extend/nacos/NacosContextPropertiesTest.java b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/extend/nacos/NacosContextPropertiesTest.java index 7c1bc2db6..acdf55d58 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/extend/nacos/NacosContextPropertiesTest.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/extend/nacos/NacosContextPropertiesTest.java @@ -21,8 +21,8 @@ import java.util.List; import java.util.Map; import java.util.Optional; +import com.tencent.cloud.polaris.context.PolarisSDKContextManager; import com.tencent.polaris.api.config.plugin.DefaultPlugins; -import com.tencent.polaris.client.api.SDKContext; import com.tencent.polaris.factory.config.global.ServerConnectorConfigImpl; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -50,7 +50,7 @@ public class NacosContextPropertiesTest { private NacosContextProperties nacosContextProperties; @Autowired - private SDKContext sdkContext; + private PolarisSDKContextManager polarisSDKContextManager; @Test public void testDefaultInitialization() { @@ -65,8 +65,9 @@ public class NacosContextPropertiesTest { @Test public void testModify() { - assertThat(sdkContext).isNotNull(); - com.tencent.polaris.api.config.Configuration configuration = sdkContext.getConfig(); + assertThat(polarisSDKContextManager).isNotNull(); + com.tencent.polaris.api.config.Configuration configuration = polarisSDKContextManager.getSDKContext() + .getConfig(); List serverConnectorConfigs = configuration.getGlobal().getServerConnectors(); Optional optionalServerConnectorConfig = serverConnectorConfigs.stream().filter( item -> "nacos".equals(item.getId()) @@ -87,5 +88,9 @@ public class NacosContextPropertiesTest { @SpringBootApplication protected static class TestApplication { + + static { + PolarisSDKContextManager.innerDestroy(); + } } } diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/loadbalancer/PolarisRouterAutoConfigurationTest.java b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/loadbalancer/PolarisRouterAutoConfigurationTest.java deleted file mode 100644 index 9e9fc863d..000000000 --- a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/loadbalancer/PolarisRouterAutoConfigurationTest.java +++ /dev/null @@ -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 { - - } -} diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/loadbalancer/PolarisWeightedRandomLoadBalancerAutoConfigurationTest.java b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/loadbalancer/PolarisWeightedRandomLoadBalancerAutoConfigurationTest.java index 12b9b77ec..c45baf194 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/loadbalancer/PolarisWeightedRandomLoadBalancerAutoConfigurationTest.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/loadbalancer/PolarisWeightedRandomLoadBalancerAutoConfigurationTest.java @@ -17,8 +17,9 @@ package com.tencent.cloud.polaris.loadbalancer; +import com.tencent.cloud.polaris.context.PolarisSDKContextManager; 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.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; @@ -53,10 +54,14 @@ public class PolarisWeightedRandomLoadBalancerAutoConfigurationTest { PolarisLoadBalancerAutoConfiguration.class, PolarisContextAutoConfiguration.class)); + @BeforeEach + void setUp() { + PolarisSDKContextManager.innerDestroy(); + } + @Test public void testDefaultInitialization() { this.contextRunner.run(context -> { - assertThat(context).hasSingleBean(RouterAPI.class); assertThat(context).hasSingleBean(RestTemplate.class); assertThatThrownBy(() -> { context.getBean(RestTemplate.class).getForEntity("http://wrong.url", String.class); @@ -67,7 +72,6 @@ public class PolarisWeightedRandomLoadBalancerAutoConfigurationTest { @Test public void testRandomInitialization() { this.contextRunner.withPropertyValues("spring.cloud.polaris.loadbalancer.strategy=random").run(context -> { - assertThat(context).hasSingleBean(RouterAPI.class); assertThat(context).hasSingleBean(RestTemplate.class); assertThatThrownBy(() -> { context.getBean(RestTemplate.class).getForEntity("http://wrong.url", String.class); @@ -77,25 +81,24 @@ public class PolarisWeightedRandomLoadBalancerAutoConfigurationTest { @Test public void testPolarisWeightedInitialization() { - this.contextRunner.withPropertyValues("spring.cloud.polaris.loadbalancer.strategy=polarisWeightedRandom").run(context -> { - assertThat(context).hasSingleBean(RouterAPI.class); - assertThat(context).hasSingleBean(RestTemplate.class); - assertThatThrownBy(() -> { - context.getBean(RestTemplate.class).getForEntity("http://wrong.url", String.class); - }).isInstanceOf(Exception.class); - }); + this.contextRunner.withPropertyValues("spring.cloud.polaris.loadbalancer.strategy=polarisWeightedRandom") + .run(context -> { + assertThat(context).hasSingleBean(RestTemplate.class); + assertThatThrownBy(() -> { + context.getBean(RestTemplate.class).getForEntity("http://wrong.url", String.class); + }).isInstanceOf(Exception.class); + }); } @Test public void testPolarisRingHashInitialization() { this.contextRunner .withPropertyValues("spring.cloud.polaris.loadbalancer.strategy=polarisRingHash").run(context -> { - assertThat(context).hasSingleBean(RouterAPI.class); assertThat(context).hasSingleBean(RestTemplate.class); assertThatThrownBy(() -> { context.getBean(RestTemplate.class).getForEntity("http://wrong.url", String.class); }).isInstanceOf(Exception.class); - }); + }); } @Configuration diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/registry/PolarisServiceRegistryAutoConfigurationTest.java b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/registry/PolarisServiceRegistryAutoConfigurationTest.java index 77a0ef49c..9aae14ceb 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/registry/PolarisServiceRegistryAutoConfigurationTest.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/registry/PolarisServiceRegistryAutoConfigurationTest.java @@ -17,12 +17,14 @@ 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.discovery.PolarisDiscoveryAutoConfiguration; import com.tencent.cloud.polaris.discovery.PolarisDiscoveryClientConfiguration; import com.tencent.polaris.test.mock.discovery.NamingServer; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; @@ -65,6 +67,11 @@ public class PolarisServiceRegistryAutoConfigurationTest { } } + @BeforeEach + void setUp() { + PolarisSDKContextManager.innerDestroy(); + } + @Test public void testDefaultInitialization() { this.contextRunner.run(context -> { diff --git a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/registry/PolarisServiceRegistryTest.java b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/registry/PolarisServiceRegistryTest.java index bd3dbf2a7..e51d9facc 100644 --- a/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/registry/PolarisServiceRegistryTest.java +++ b/spring-cloud-starter-tencent-polaris-discovery/src/test/java/com/tencent/cloud/polaris/registry/PolarisServiceRegistryTest.java @@ -17,6 +17,7 @@ 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.discovery.PolarisDiscoveryAutoConfiguration; 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 org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -89,6 +91,11 @@ public class PolarisServiceRegistryTest { } } + @BeforeEach + void setUp() { + PolarisSDKContextManager.innerDestroy(); + } + @Test public void testRegister() { this.contextRunner.run(context -> { diff --git a/spring-cloud-starter-tencent-polaris-ratelimit/src/main/java/com/tencent/cloud/polaris/ratelimit/config/PolarisRateLimitAutoConfiguration.java b/spring-cloud-starter-tencent-polaris-ratelimit/src/main/java/com/tencent/cloud/polaris/ratelimit/config/PolarisRateLimitAutoConfiguration.java index d33c0e604..cce3b9bca 100644 --- a/spring-cloud-starter-tencent-polaris-ratelimit/src/main/java/com/tencent/cloud/polaris/ratelimit/config/PolarisRateLimitAutoConfiguration.java +++ b/spring-cloud-starter-tencent-polaris-ratelimit/src/main/java/com/tencent/cloud/polaris/ratelimit/config/PolarisRateLimitAutoConfiguration.java @@ -18,6 +18,7 @@ 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.config.PolarisContextAutoConfiguration; 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.PolarisRateLimiterLabelServletResolver; 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.boot.autoconfigure.AutoConfigureAfter; @@ -58,12 +56,6 @@ import static javax.servlet.DispatcherType.REQUEST; @ConditionalOnPolarisRateLimitEnabled public class PolarisRateLimitAutoConfiguration { - @Bean - @ConditionalOnMissingBean - public LimitAPI limitAPI(SDKContext polarisContext) { - return LimitAPIFactory.createLimitAPIByContext(polarisContext); - } - /** * Create when web application type is SERVLET. */ @@ -79,11 +71,12 @@ public class PolarisRateLimitAutoConfiguration { @Bean @ConditionalOnMissingBean - public QuotaCheckServletFilter quotaCheckFilter(LimitAPI limitAPI, + public QuotaCheckServletFilter quotaCheckFilter(PolarisSDKContextManager polarisSDKContextManager, PolarisRateLimitProperties polarisRateLimitProperties, RateLimitRuleArgumentServletResolver rateLimitRuleArgumentResolver, @Autowired(required = false) PolarisRateLimiterLimitedFallback polarisRateLimiterLimitedFallback) { - return new QuotaCheckServletFilter(limitAPI, polarisRateLimitProperties, rateLimitRuleArgumentResolver, polarisRateLimiterLimitedFallback); + return new QuotaCheckServletFilter(polarisSDKContextManager.getLimitAPI(), polarisRateLimitProperties, + rateLimitRuleArgumentResolver, polarisRateLimiterLimitedFallback); } @Bean @@ -97,7 +90,6 @@ public class PolarisRateLimitAutoConfiguration { return registrationBean; } - } /** @@ -114,11 +106,12 @@ public class PolarisRateLimitAutoConfiguration { } @Bean - public QuotaCheckReactiveFilter quotaCheckReactiveFilter(LimitAPI limitAPI, + public QuotaCheckReactiveFilter quotaCheckReactiveFilter(PolarisSDKContextManager polarisSDKContextManager, PolarisRateLimitProperties polarisRateLimitProperties, RateLimitRuleArgumentReactiveResolver rateLimitRuleArgumentResolver, @Nullable PolarisRateLimiterLimitedFallback polarisRateLimiterLimitedFallback) { - return new QuotaCheckReactiveFilter(limitAPI, polarisRateLimitProperties, rateLimitRuleArgumentResolver, polarisRateLimiterLimitedFallback); + return new QuotaCheckReactiveFilter(polarisSDKContextManager.getLimitAPI(), polarisRateLimitProperties, + rateLimitRuleArgumentResolver, polarisRateLimiterLimitedFallback); } } } diff --git a/spring-cloud-starter-tencent-polaris-ratelimit/src/test/java/com/tencent/cloud/polaris/ratelimit/controller/CalleeControllerTests.java b/spring-cloud-starter-tencent-polaris-ratelimit/src/test/java/com/tencent/cloud/polaris/context/CalleeControllerTests.java similarity index 81% rename from spring-cloud-starter-tencent-polaris-ratelimit/src/test/java/com/tencent/cloud/polaris/ratelimit/controller/CalleeControllerTests.java rename to spring-cloud-starter-tencent-polaris-ratelimit/src/test/java/com/tencent/cloud/polaris/context/CalleeControllerTests.java index cef5b6585..cf157182a 100644 --- a/spring-cloud-starter-tencent-polaris-ratelimit/src/test/java/com/tencent/cloud/polaris/ratelimit/controller/CalleeControllerTests.java +++ b/spring-cloud-starter-tencent-polaris-ratelimit/src/test/java/com/tencent/cloud/polaris/context/CalleeControllerTests.java @@ -15,12 +15,17 @@ * 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.ratelimit.api.core.LimitAPI; import com.tencent.polaris.ratelimit.api.rpc.QuotaResponse; 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.NamingService; import org.junit.jupiter.api.AfterAll; @@ -36,6 +41,7 @@ import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.boot.web.server.LocalServerPort; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.web.client.HttpClientErrorException.TooManyRequests; import org.springframework.web.client.RestClientException; @@ -142,5 +148,19 @@ public class CalleeControllerTests { 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); + } } } diff --git a/spring-cloud-starter-tencent-polaris-ratelimit/src/test/java/com/tencent/cloud/polaris/ratelimit/controller/TestController.java b/spring-cloud-starter-tencent-polaris-ratelimit/src/test/java/com/tencent/cloud/polaris/context/TestController.java similarity index 95% rename from spring-cloud-starter-tencent-polaris-ratelimit/src/test/java/com/tencent/cloud/polaris/ratelimit/controller/TestController.java rename to spring-cloud-starter-tencent-polaris-ratelimit/src/test/java/com/tencent/cloud/polaris/context/TestController.java index 234b9507f..f56db9b4b 100644 --- a/spring-cloud-starter-tencent-polaris-ratelimit/src/test/java/com/tencent/cloud/polaris/ratelimit/controller/TestController.java +++ b/spring-cloud-starter-tencent-polaris-ratelimit/src/test/java/com/tencent/cloud/polaris/context/TestController.java @@ -15,7 +15,7 @@ * 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.RequestMapping; diff --git a/spring-cloud-starter-tencent-polaris-ratelimit/src/test/java/com/tencent/cloud/polaris/ratelimit/config/PolarisRateLimitAutoConfigurationTest.java b/spring-cloud-starter-tencent-polaris-ratelimit/src/test/java/com/tencent/cloud/polaris/ratelimit/config/PolarisRateLimitAutoConfigurationTest.java index c21a71f3e..9a959e511 100644 --- a/spring-cloud-starter-tencent-polaris-ratelimit/src/test/java/com/tencent/cloud/polaris/ratelimit/config/PolarisRateLimitAutoConfigurationTest.java +++ b/spring-cloud-starter-tencent-polaris-ratelimit/src/test/java/com/tencent/cloud/polaris/ratelimit/config/PolarisRateLimitAutoConfigurationTest.java @@ -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.resolver.RateLimitRuleArgumentReactiveResolver; import com.tencent.cloud.polaris.ratelimit.resolver.RateLimitRuleArgumentServletResolver; -import com.tencent.polaris.ratelimit.api.core.LimitAPI; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; @@ -55,7 +54,6 @@ public class PolarisRateLimitAutoConfigurationTest { PolarisRateLimitProperties.class, PolarisRateLimitAutoConfiguration.class)) .run(context -> { - assertThat(context).hasSingleBean(LimitAPI.class); assertThat(context).doesNotHaveBean(RateLimitRuleArgumentServletResolver.class); assertThat(context).doesNotHaveBean(RateLimitRuleArgumentReactiveResolver.class); assertThat(context).doesNotHaveBean(PolarisRateLimitAutoConfiguration.QuotaCheckFilterConfig.class); @@ -73,7 +71,6 @@ public class PolarisRateLimitAutoConfigurationTest { PolarisRateLimitProperties.class, PolarisRateLimitAutoConfiguration.class)) .run(context -> { - assertThat(context).hasSingleBean(LimitAPI.class); assertThat(context).hasSingleBean(RateLimitRuleArgumentServletResolver.class); assertThat(context).hasSingleBean(PolarisRateLimitAutoConfiguration.QuotaCheckFilterConfig.class); assertThat(context).hasSingleBean(QuotaCheckServletFilter.class); @@ -91,7 +88,6 @@ public class PolarisRateLimitAutoConfigurationTest { PolarisRateLimitProperties.class, PolarisRateLimitAutoConfiguration.class)) .run(context -> { - assertThat(context).hasSingleBean(LimitAPI.class); assertThat(context).doesNotHaveBean(RateLimitRuleArgumentServletResolver.class); assertThat(context).hasSingleBean(RateLimitRuleArgumentReactiveResolver.class); assertThat(context).doesNotHaveBean(PolarisRateLimitAutoConfiguration.QuotaCheckFilterConfig.class); diff --git a/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/config/LoadBalancerConfiguration.java b/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/config/LoadBalancerConfiguration.java index 035c67562..b41bdb0d4 100644 --- a/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/config/LoadBalancerConfiguration.java +++ b/spring-cloud-starter-tencent-polaris-router/src/main/java/com/tencent/cloud/polaris/router/config/LoadBalancerConfiguration.java @@ -21,12 +21,12 @@ package com.tencent.cloud.polaris.router.config; import java.util.List; 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.spi.RouterRequestInterceptor; import com.tencent.cloud.polaris.router.spi.RouterResponseInterceptor; import com.tencent.cloud.rpc.enhancement.transformer.InstanceTransformer; 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.ConditionalOnClass; @@ -73,11 +73,11 @@ public class LoadBalancerConfiguration { @ConditionalOnBean(ReactiveDiscoveryClient.class) public ServiceInstanceListSupplier polarisRouterDiscoveryClientServiceInstanceListSupplier( ConfigurableApplicationContext context, - RouterAPI routerAPI, List requestInterceptors, + PolarisSDKContextManager polarisSDKContextManager, List requestInterceptors, List responseInterceptors, InstanceTransformer instanceTransformer) { return new PolarisRouterServiceInstanceListSupplier( ServiceInstanceListSupplier.builder().withDiscoveryClient().build(context), - routerAPI, + polarisSDKContextManager.getRouterAPI(), requestInterceptors, responseInterceptors, instanceTransformer); @@ -94,11 +94,11 @@ public class LoadBalancerConfiguration { @ConditionalOnBean(DiscoveryClient.class) public ServiceInstanceListSupplier polarisRouterDiscoveryClientServiceInstanceListSupplier( ConfigurableApplicationContext context, - RouterAPI routerAPI, List requestInterceptors, + PolarisSDKContextManager polarisSDKContextManager, List requestInterceptors, List responseInterceptors, InstanceTransformer instanceTransformer) { return new PolarisRouterServiceInstanceListSupplier( ServiceInstanceListSupplier.builder().withBlockingDiscoveryClient().build(context), - routerAPI, + polarisSDKContextManager.getRouterAPI(), requestInterceptors, responseInterceptors, instanceTransformer); diff --git a/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/config/LoadBalancerConfigurationTest.java b/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/config/LoadBalancerConfigurationTest.java index 8998dd57f..e6e1b17db 100644 --- a/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/config/LoadBalancerConfigurationTest.java +++ b/spring-cloud-starter-tencent-polaris-router/src/test/java/com/tencent/cloud/polaris/router/config/LoadBalancerConfigurationTest.java @@ -21,7 +21,6 @@ package com.tencent.cloud.polaris.router.config; import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration; import com.tencent.cloud.polaris.router.PolarisRouterServiceInstanceListSupplier; import com.tencent.cloud.rpc.enhancement.transformer.PolarisInstanceTransformer; -import com.tencent.polaris.router.api.core.RouterAPI; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; @@ -63,7 +62,6 @@ public class LoadBalancerConfigurationTest { .withBean(PolarisInstanceTransformer.class) .run(context -> { assertThat(context).hasSingleBean(LoadBalancerConfiguration.PolarisReactiveSupportConfiguration.class); - assertThat(context).hasSingleBean(RouterAPI.class); assertThat(context).hasSingleBean(ReactiveDiscoveryClient.class); assertThat(context).hasSingleBean(PolarisRouterServiceInstanceListSupplier.class); }); @@ -81,7 +79,6 @@ public class LoadBalancerConfigurationTest { .run(context -> { assertThat(context).hasSingleBean(LoadBalancerConfiguration.PolarisBlockingSupportConfiguration.class); assertThat(context).hasSingleBean(DiscoveryClient.class); - assertThat(context).hasSingleBean(RouterAPI.class); assertThat(context).hasSingleBean(PolarisRouterServiceInstanceListSupplier.class); }); } diff --git a/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-tsf-adapter-plugin/src/test/java/com/tencent/cloud/tsf/adapter/config/TsfCircuitBreakerFlow.java b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-tsf-adapter-plugin/src/test/java/com/tencent/cloud/tsf/adapter/config/TsfCircuitBreakerFlow.java new file mode 100644 index 000000000..e01d3af4e --- /dev/null +++ b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-tsf-adapter-plugin/src/test/java/com/tencent/cloud/tsf/adapter/config/TsfCircuitBreakerFlow.java @@ -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) { + + } +} diff --git a/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-tsf-adapter-plugin/src/test/java/com/tencent/cloud/tsf/adapter/config/TsfDiscoveryFlow.java b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-tsf-adapter-plugin/src/test/java/com/tencent/cloud/tsf/adapter/config/TsfDiscoveryFlow.java index d183d23ef..b0283242f 100644 --- a/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-tsf-adapter-plugin/src/test/java/com/tencent/cloud/tsf/adapter/config/TsfDiscoveryFlow.java +++ b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-tsf-adapter-plugin/src/test/java/com/tencent/cloud/tsf/adapter/config/TsfDiscoveryFlow.java @@ -37,4 +37,9 @@ public class TsfDiscoveryFlow implements DiscoveryFlow { public void setSDKContext(SDKContext sdkContext) { } + + @Override + public void destroy() { + + } } diff --git a/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-tsf-adapter-plugin/src/test/java/com/tencent/cloud/tsf/adapter/config/TsfLimitFlow.java b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-tsf-adapter-plugin/src/test/java/com/tencent/cloud/tsf/adapter/config/TsfLimitFlow.java new file mode 100644 index 000000000..3ac9b4b1e --- /dev/null +++ b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-tsf-adapter-plugin/src/test/java/com/tencent/cloud/tsf/adapter/config/TsfLimitFlow.java @@ -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) { + + } +} diff --git a/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-tsf-adapter-plugin/src/test/resources/META-INF/services/com.tencent.polaris.circuitbreak.api.flow.CircuitBreakerFlow b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-tsf-adapter-plugin/src/test/resources/META-INF/services/com.tencent.polaris.circuitbreak.api.flow.CircuitBreakerFlow new file mode 100644 index 000000000..92c38e742 --- /dev/null +++ b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-tsf-adapter-plugin/src/test/resources/META-INF/services/com.tencent.polaris.circuitbreak.api.flow.CircuitBreakerFlow @@ -0,0 +1 @@ +com.tencent.cloud.tsf.adapter.config.TsfCircuitBreakerFlow \ No newline at end of file diff --git a/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-tsf-adapter-plugin/src/test/resources/META-INF/services/com.tencent.polaris.ratelimit.api.flow.LimitFlow b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-tsf-adapter-plugin/src/test/resources/META-INF/services/com.tencent.polaris.ratelimit.api.flow.LimitFlow new file mode 100644 index 000000000..54507bb07 --- /dev/null +++ b/spring-cloud-tencent-plugin-starters/spring-cloud-starter-tencent-tsf-adapter-plugin/src/test/resources/META-INF/services/com.tencent.polaris.ratelimit.api.flow.LimitFlow @@ -0,0 +1 @@ +com.tencent.cloud.tsf.adapter.config.TsfLimitFlow \ No newline at end of file diff --git a/spring-cloud-tencent-plugin-starters/spring-cloud-tencent-featureenv-plugin/src/test/java/com/tencent/cloud/plugin/featureenv/FeatureEnvAutoConfigurationTest.java b/spring-cloud-tencent-plugin-starters/spring-cloud-tencent-featureenv-plugin/src/test/java/com/tencent/cloud/plugin/featureenv/FeatureEnvAutoConfigurationTest.java new file mode 100644 index 000000000..c90ab28da --- /dev/null +++ b/spring-cloud-tencent-plugin-starters/spring-cloud-tencent-featureenv-plugin/src/test/java/com/tencent/cloud/plugin/featureenv/FeatureEnvAutoConfigurationTest.java @@ -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); + }); + } +} diff --git a/spring-cloud-tencent-plugin-starters/spring-cloud-tencent-gateway-plugin/src/test/java/com/tencent/cloud/plugin/gateway/SCGPluginsAutoConfigurationTest.java b/spring-cloud-tencent-plugin-starters/spring-cloud-tencent-gateway-plugin/src/test/java/com/tencent/cloud/plugin/gateway/SCGPluginsAutoConfigurationTest.java index 363450c6c..125867a18 100644 --- a/spring-cloud-tencent-plugin-starters/spring-cloud-tencent-gateway-plugin/src/test/java/com/tencent/cloud/plugin/gateway/SCGPluginsAutoConfigurationTest.java +++ b/spring-cloud-tencent-plugin-starters/spring-cloud-tencent-gateway-plugin/src/test/java/com/tencent/cloud/plugin/gateway/SCGPluginsAutoConfigurationTest.java @@ -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.RuleTrafficStainer; 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.factory.ConfigFileServiceFactory; import org.junit.jupiter.api.Test; @@ -65,8 +65,8 @@ public class SCGPluginsAutoConfigurationTest { public static class TestApplication { @Bean - public ConfigFileService configFileService(SDKContext sdkContext) { - return ConfigFileServiceFactory.createConfigFileService(sdkContext); + public ConfigFileService configFileService(PolarisSDKContextManager polarisSDKContextManager) { + return ConfigFileServiceFactory.createConfigFileService(polarisSDKContextManager.getSDKContext()); } } } diff --git a/spring-cloud-tencent-polaris-context/src/main/java/com/tencent/cloud/polaris/context/PolarisSDKContextManager.java b/spring-cloud-tencent-polaris-context/src/main/java/com/tencent/cloud/polaris/context/PolarisSDKContextManager.java new file mode 100644 index 000000000..e72abefd2 --- /dev/null +++ b/spring-cloud-tencent-polaris-context/src/main/java/com/tencent/cloud/polaris/context/PolarisSDKContextManager.java @@ -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 modifierList; + + public PolarisSDKContextManager(PolarisContextProperties properties, Environment environment, List 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("spring.cloud.polaris.local-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; + } +} diff --git a/spring-cloud-tencent-polaris-context/src/main/java/com/tencent/cloud/polaris/context/config/PolarisContextAutoConfiguration.java b/spring-cloud-tencent-polaris-context/src/main/java/com/tencent/cloud/polaris/context/config/PolarisContextAutoConfiguration.java index 104a4e057..1593fdd5f 100644 --- a/spring-cloud-tencent-polaris-context/src/main/java/com/tencent/cloud/polaris/context/config/PolarisContextAutoConfiguration.java +++ b/spring-cloud-tencent-polaris-context/src/main/java/com/tencent/cloud/polaris/context/config/PolarisContextAutoConfiguration.java @@ -23,21 +23,14 @@ import java.util.List; import com.tencent.cloud.polaris.context.ConditionalOnPolarisEnabled; import com.tencent.cloud.polaris.context.ModifyAddress; import com.tencent.cloud.polaris.context.PolarisConfigModifier; +import com.tencent.cloud.polaris.context.PolarisSDKContextManager; 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.assembly.api.AssemblyAPI; -import com.tencent.polaris.assembly.factory.AssemblyAPIFactory; 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.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; /** @@ -45,39 +38,14 @@ import org.springframework.core.env.Environment; * * @author Haotian Zhang */ -@Configuration(proxyBeanMethods = false) @ConditionalOnPolarisEnabled @EnableConfigurationProperties({PolarisContextProperties.class}) public class PolarisContextAutoConfiguration { - @Bean(name = "polarisContext", initMethod = "init", destroyMethod = "destroy") + @Bean(initMethod = "init") @ConditionalOnMissingBean - public SDKContext polarisContext(PolarisContextProperties properties, Environment environment, List modifierList) throws PolarisException { - return SDKContext.initContextByConfig(properties.configuration(modifierList, - () -> environment.getProperty("spring.cloud.client.ip-address"), - () -> 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); + public PolarisSDKContextManager polarisSDKContextManager(PolarisContextProperties properties, Environment environment, List modifierList) throws PolarisException { + return new PolarisSDKContextManager(properties, environment, modifierList); } @Bean @@ -87,8 +55,7 @@ public class PolarisContextAutoConfiguration { } @Bean - @ConditionalOnMissingBean - public ServiceRuleManager serviceRuleManager(SDKContext sdkContext, ConsumerAPI consumerAPI) { - return new ServiceRuleManager(sdkContext, consumerAPI); + public ServiceRuleManager serviceRuleManager(PolarisSDKContextManager polarisSDKContextManager) { + return new ServiceRuleManager(polarisSDKContextManager.getSDKContext(), polarisSDKContextManager.getConsumerAPI()); } } diff --git a/spring-cloud-tencent-polaris-context/src/main/java/com/tencent/cloud/polaris/context/config/PolarisContextPostConfiguration.java b/spring-cloud-tencent-polaris-context/src/main/java/com/tencent/cloud/polaris/context/config/PolarisContextPostConfiguration.java index 36b8664ce..319ad40d2 100644 --- a/spring-cloud-tencent-polaris-context/src/main/java/com/tencent/cloud/polaris/context/config/PolarisContextPostConfiguration.java +++ b/spring-cloud-tencent-polaris-context/src/main/java/com/tencent/cloud/polaris/context/config/PolarisContextPostConfiguration.java @@ -20,8 +20,8 @@ package com.tencent.cloud.polaris.context.config; import com.tencent.cloud.common.metadata.StaticMetadataManager; import com.tencent.cloud.polaris.context.ConditionalOnPolarisEnabled; +import com.tencent.cloud.polaris.context.PolarisSDKContextManager; import com.tencent.cloud.polaris.context.PostInitPolarisSDKContext; -import com.tencent.polaris.client.api.SDKContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -36,7 +36,8 @@ import org.springframework.context.annotation.Configuration; public class PolarisContextPostConfiguration { @Bean - public PostInitPolarisSDKContext postInitPolarisSDKContext(SDKContext sdkContext, StaticMetadataManager staticMetadataManager) { - return new PostInitPolarisSDKContext(sdkContext, staticMetadataManager); + public PostInitPolarisSDKContext postInitPolarisSDKContext( + PolarisSDKContextManager polarisSDKContextManager, StaticMetadataManager staticMetadataManager) { + return new PostInitPolarisSDKContext(polarisSDKContextManager.getSDKContext(), staticMetadataManager); } } diff --git a/spring-cloud-tencent-polaris-context/src/main/java/com/tencent/cloud/polaris/context/config/PolarisContextProperties.java b/spring-cloud-tencent-polaris-context/src/main/java/com/tencent/cloud/polaris/context/config/PolarisContextProperties.java index f77eaa4f5..7bde159b3 100644 --- a/spring-cloud-tencent-polaris-context/src/main/java/com/tencent/cloud/polaris/context/config/PolarisContextProperties.java +++ b/spring-cloud-tencent-polaris-context/src/main/java/com/tencent/cloud/polaris/context/config/PolarisContextProperties.java @@ -149,4 +149,16 @@ public class PolarisContextProperties { public void setService(String service) { this.service = service; } + + @Override + public String toString() { + return "PolarisContextProperties{" + + "address='" + address + '\'' + + ", localIpAddress='" + localIpAddress + '\'' + + ((this.localPort == null || this.localPort <= 0) ? "" : ", localPort=" + localPort) + + ", enabled=" + enabled + + ", namespace='" + namespace + '\'' + + ((StringUtils.isBlank(this.service)) ? "" : ", service='" + service + '\'') + + '}'; + } } diff --git a/spring-cloud-tencent-polaris-context/src/test/java/com/tencent/cloud/polaris/context/PolarisContextGetHostTest.java b/spring-cloud-tencent-polaris-context/src/test/java/com/tencent/cloud/polaris/context/PolarisContextGetHostTest.java index c9b9258cc..1d4475304 100644 --- a/spring-cloud-tencent-polaris-context/src/test/java/com/tencent/cloud/polaris/context/PolarisContextGetHostTest.java +++ b/spring-cloud-tencent-polaris-context/src/test/java/com/tencent/cloud/polaris/context/PolarisContextGetHostTest.java @@ -43,14 +43,14 @@ import static org.assertj.core.api.Assertions.assertThat; public class PolarisContextGetHostTest { @Autowired - private SDKContext polarisContext; + private PolarisSDKContextManager polarisSDKContextManager; @Autowired private PolarisContextProperties polarisContextProperties; @Test public void testGetConfigHost() { - String bindIP = polarisContext.getConfig().getGlobal().getAPI().getBindIP(); + String bindIP = polarisSDKContextManager.getSDKContext().getConfig().getGlobal().getAPI().getBindIP(); assertThat(StringUtils.isBlank(bindIP)).isFalse(); assertThat(bindIP).isEqualTo("192.168.1.1"); assertThat(polarisContextProperties.getAddress()).isEqualTo("grpc://127.0.0.1:8091"); diff --git a/spring-cloud-tencent-polaris-context/src/test/java/com/tencent/cloud/polaris/context/config/PolarisContextAutoConfigurationTest.java b/spring-cloud-tencent-polaris-context/src/test/java/com/tencent/cloud/polaris/context/config/PolarisContextAutoConfigurationTest.java index 3cbce6ba5..328d7a7e6 100644 --- a/spring-cloud-tencent-polaris-context/src/test/java/com/tencent/cloud/polaris/context/config/PolarisContextAutoConfigurationTest.java +++ b/spring-cloud-tencent-polaris-context/src/test/java/com/tencent/cloud/polaris/context/config/PolarisContextAutoConfigurationTest.java @@ -17,7 +17,7 @@ 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.springframework.boot.autoconfigure.AutoConfigurations; @@ -41,8 +41,8 @@ public class PolarisContextAutoConfigurationTest { @Test public void testProperties() { contextRunner.run(context -> { - final SDKContext sdkContext = context.getBean(SDKContext.class); - assertThat(sdkContext).isNotNull(); + PolarisSDKContextManager polarisSDKContextManager = context.getBean(PolarisSDKContextManager.class); + assertThat(polarisSDKContextManager).isNotNull(); }); } } diff --git a/spring-cloud-tencent-rpc-enhancement/src/main/java/com/tencent/cloud/rpc/enhancement/config/RpcEnhancementAutoConfiguration.java b/spring-cloud-tencent-rpc-enhancement/src/main/java/com/tencent/cloud/rpc/enhancement/config/RpcEnhancementAutoConfiguration.java index b81c67289..704d0b4b8 100644 --- a/spring-cloud-tencent-rpc-enhancement/src/main/java/com/tencent/cloud/rpc/enhancement/config/RpcEnhancementAutoConfiguration.java +++ b/spring-cloud-tencent-rpc-enhancement/src/main/java/com/tencent/cloud/rpc/enhancement/config/RpcEnhancementAutoConfiguration.java @@ -22,6 +22,7 @@ import java.util.List; import com.tencent.cloud.common.pojo.PolarisServiceInstance; 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.rpc.enhancement.feign.EnhancedFeignBeanPostProcessor; import com.tencent.cloud.rpc.enhancement.feign.EnhancedLoadBalancerClientAspect; @@ -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.webclient.EnhancedWebClientExchangeFilterFunction; 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.annotation.Autowired; @@ -101,50 +99,50 @@ public class RpcEnhancementAutoConfiguration { public EnhancedPluginRunner enhancedFeignPluginRunner( @Autowired(required = false) List enhancedPlugins, @Autowired(required = false) Registration registration, - SDKContext sdkContext) { - return new DefaultEnhancedPluginRunner(enhancedPlugins, registration, sdkContext); + PolarisSDKContextManager polarisSDKContextManager) { + return new DefaultEnhancedPluginRunner(enhancedPlugins, registration, polarisSDKContextManager.getSDKContext()); } @Bean public SuccessPolarisReporter successPolarisReporter(RpcEnhancementReporterProperties properties, - ConsumerAPI consumerAPI) { - return new SuccessPolarisReporter(properties, consumerAPI); + PolarisSDKContextManager polarisSDKContextManager) { + return new SuccessPolarisReporter(properties, polarisSDKContextManager.getConsumerAPI()); } @Bean public ExceptionPolarisReporter exceptionPolarisReporter(RpcEnhancementReporterProperties properties, - ConsumerAPI consumerAPI) { - return new ExceptionPolarisReporter(properties, consumerAPI); + PolarisSDKContextManager polarisSDKContextManager) { + return new ExceptionPolarisReporter(properties, polarisSDKContextManager.getConsumerAPI()); } @Bean - public AssemblyClientExceptionHook assemblyClientExceptionHook(AssemblyAPI assemblyAPI, InstanceTransformer instanceTransformer) { - return new AssemblyClientExceptionHook(assemblyAPI, instanceTransformer); + public AssemblyClientExceptionHook assemblyClientExceptionHook(PolarisSDKContextManager polarisSDKContextManager, InstanceTransformer instanceTransformer) { + return new AssemblyClientExceptionHook(polarisSDKContextManager.getAssemblyAPI(), instanceTransformer); } @Bean - public AssemblyClientPostHook assemblyClientPostHook(AssemblyAPI assemblyAPI, InstanceTransformer instanceTransformer) { - return new AssemblyClientPostHook(assemblyAPI, instanceTransformer); + public AssemblyClientPostHook assemblyClientPostHook(PolarisSDKContextManager polarisSDKContextManager, InstanceTransformer instanceTransformer) { + return new AssemblyClientPostHook(polarisSDKContextManager.getAssemblyAPI(), instanceTransformer); } @Bean - public AssemblyClientPreHook assemblyClientPreHook(AssemblyAPI assemblyAPI) { - return new AssemblyClientPreHook(assemblyAPI); + public AssemblyClientPreHook assemblyClientPreHook(PolarisSDKContextManager polarisSDKContextManager) { + return new AssemblyClientPreHook(polarisSDKContextManager.getAssemblyAPI()); } @Bean - public AssemblyServerExceptionHook assemblyServerExceptionHook(AssemblyAPI assemblyAPI) { - return new AssemblyServerExceptionHook(assemblyAPI); + public AssemblyServerExceptionHook assemblyServerExceptionHook(PolarisSDKContextManager polarisSDKContextManager) { + return new AssemblyServerExceptionHook(polarisSDKContextManager.getAssemblyAPI()); } @Bean - public AssemblyServerPostHook assemblyServerPostHook(AssemblyAPI assemblyAPI) { - return new AssemblyServerPostHook(assemblyAPI); + public AssemblyServerPostHook assemblyServerPostHook(PolarisSDKContextManager polarisSDKContextManager) { + return new AssemblyServerPostHook(polarisSDKContextManager.getAssemblyAPI()); } @Bean - public AssemblyServerPreHook assemblyServerPreHook(AssemblyAPI assemblyAPI) { - return new AssemblyServerPreHook(assemblyAPI); + public AssemblyServerPreHook assemblyServerPreHook(PolarisSDKContextManager polarisSDKContextManager) { + return new AssemblyServerPreHook(polarisSDKContextManager.getAssemblyAPI()); } @Configuration(proxyBeanMethods = false) @@ -287,7 +285,5 @@ public class RpcEnhancementAutoConfiguration { public EnhancedGatewayGlobalFilter enhancedPolarisGatewayReporter(@Lazy EnhancedPluginRunner pluginRunner) { return new EnhancedGatewayGlobalFilter(pluginRunner); } - } - } diff --git a/spring-cloud-tencent-rpc-enhancement/src/test/java/com/tencent/cloud/rpc/enhancement/config/RpcEnhancementAutoConfigurationTest.java b/spring-cloud-tencent-rpc-enhancement/src/test/java/com/tencent/cloud/rpc/enhancement/config/RpcEnhancementAutoConfigurationTest.java index fe02ab397..aca9847ca 100644 --- a/spring-cloud-tencent-rpc-enhancement/src/test/java/com/tencent/cloud/rpc/enhancement/config/RpcEnhancementAutoConfigurationTest.java +++ b/spring-cloud-tencent-rpc-enhancement/src/test/java/com/tencent/cloud/rpc/enhancement/config/RpcEnhancementAutoConfigurationTest.java @@ -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.SuccessPolarisReporter; import com.tencent.cloud.rpc.enhancement.resttemplate.EnhancedRestTemplateInterceptor; -import com.tencent.polaris.api.core.ConsumerAPI; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; @@ -55,7 +54,6 @@ public class RpcEnhancementAutoConfigurationTest { @Test public void testDefaultInitialization() { this.contextRunner.run(context -> { - assertThat(context).hasSingleBean(ConsumerAPI.class); assertThat(context).hasSingleBean(EnhancedPluginRunner.class); assertThat(context).hasSingleBean(EnhancedFeignBeanPostProcessor.class); assertThat(context).hasSingleBean(SuccessPolarisReporter.class); diff --git a/spring-cloud-tencent-rpc-enhancement/src/test/java/com/tencent/cloud/rpc/enhancement/feign/EnhancedFeignClientTest.java b/spring-cloud-tencent-rpc-enhancement/src/test/java/com/tencent/cloud/rpc/enhancement/feign/EnhancedFeignClientTest.java index faa02de8a..8edf80b19 100644 --- a/spring-cloud-tencent-rpc-enhancement/src/test/java/com/tencent/cloud/rpc/enhancement/feign/EnhancedFeignClientTest.java +++ b/spring-cloud-tencent-rpc-enhancement/src/test/java/com/tencent/cloud/rpc/enhancement/feign/EnhancedFeignClientTest.java @@ -22,11 +22,11 @@ import java.util.ArrayList; import java.util.Collections; 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.EnhancedPlugin; import com.tencent.cloud.rpc.enhancement.plugin.EnhancedPluginContext; import com.tencent.cloud.rpc.enhancement.plugin.EnhancedPluginType; -import com.tencent.polaris.client.api.SDKContext; import feign.Client; import feign.Request; import feign.RequestTemplate; @@ -58,7 +58,7 @@ import static org.mockito.Mockito.mock; public class EnhancedFeignClientTest { @Autowired - private SDKContext sdkContext; + private PolarisSDKContextManager polarisSDKContextManager; @Test public void testConstructor() { @@ -80,7 +80,8 @@ public class EnhancedFeignClientTest { List enhancedPlugins = getMockEnhancedFeignPlugins(); 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) { fail("Exception encountered.", e); @@ -109,7 +110,8 @@ public class EnhancedFeignClientTest { RequestTemplate requestTemplate = new RequestTemplate(); 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 Response response = polarisFeignClient.execute(Request.create(Request.HttpMethod.GET, "http://localhost:8080/test", diff --git a/spring-cloud-tencent-rpc-enhancement/src/test/java/com/tencent/cloud/rpc/enhancement/stat/config/StatConfigModifierTest.java b/spring-cloud-tencent-rpc-enhancement/src/test/java/com/tencent/cloud/rpc/enhancement/stat/config/StatConfigModifierTest.java index fbfdcc9f2..52c125ebf 100644 --- a/spring-cloud-tencent-rpc-enhancement/src/test/java/com/tencent/cloud/rpc/enhancement/stat/config/StatConfigModifierTest.java +++ b/spring-cloud-tencent-rpc-enhancement/src/test/java/com/tencent/cloud/rpc/enhancement/stat/config/StatConfigModifierTest.java @@ -17,8 +17,9 @@ 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 org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; @@ -62,11 +63,17 @@ public class StatConfigModifierTest { .withPropertyValues("spring.application.name=test") .withPropertyValues("spring.cloud.gateway.enabled=false"); + @BeforeEach + void setUp() { + PolarisSDKContextManager.innerDestroy(); + } + @Test void testPull() { pullContextRunner.run(context -> { - SDKContext sdkContext = context.getBean(SDKContext.class); - PrometheusHandlerConfig prometheusHandlerConfig = sdkContext.getConfig().getGlobal().getStatReporter() + PolarisSDKContextManager polarisSDKContextManager = context.getBean(PolarisSDKContextManager.class); + PrometheusHandlerConfig prometheusHandlerConfig = polarisSDKContextManager.getSDKContext().getConfig() + .getGlobal().getStatReporter() .getPluginConfig(DEFAULT_REPORTER_PROMETHEUS, PrometheusHandlerConfig.class); assertThat(prometheusHandlerConfig.getType()).isEqualTo("pull"); assertThat(prometheusHandlerConfig.getHost()).isEqualTo("127.0.0.1"); @@ -78,8 +85,9 @@ public class StatConfigModifierTest { @Test void testPush() { pushContextRunner.run(context -> { - SDKContext sdkContext = context.getBean(SDKContext.class); - PrometheusHandlerConfig prometheusHandlerConfig = sdkContext.getConfig().getGlobal().getStatReporter() + PolarisSDKContextManager polarisSDKContextManager = context.getBean(PolarisSDKContextManager.class); + PrometheusHandlerConfig prometheusHandlerConfig = polarisSDKContextManager.getSDKContext().getConfig() + .getGlobal().getStatReporter() .getPluginConfig(DEFAULT_REPORTER_PROMETHEUS, PrometheusHandlerConfig.class); assertThat(prometheusHandlerConfig.getType()).isEqualTo("push"); assertThat(prometheusHandlerConfig.getAddress()).isEqualTo("127.0.0.1:9091"); @@ -90,8 +98,9 @@ public class StatConfigModifierTest { @Test void testDisabled() { disabledContextRunner.run(context -> { - SDKContext sdkContext = context.getBean(SDKContext.class); - PrometheusHandlerConfig prometheusHandlerConfig = sdkContext.getConfig().getGlobal().getStatReporter() + PolarisSDKContextManager polarisSDKContextManager = context.getBean(PolarisSDKContextManager.class); + PrometheusHandlerConfig prometheusHandlerConfig = polarisSDKContextManager.getSDKContext().getConfig() + .getGlobal().getStatReporter() .getPluginConfig(DEFAULT_REPORTER_PROMETHEUS, PrometheusHandlerConfig.class); assertThat(prometheusHandlerConfig.getPort()).isEqualTo(-1); });