feat:refactor SDKContext as static.

pull/1080/head
Haotian Zhang 1 year ago
parent 28a0a9fc63
commit 4981835215

@ -6,3 +6,4 @@
- feat:adapt for nacos instance.
- Refactoring: Refactor Circuitbreaker ut.
- refactor:refactor rpc enhancement.
- feat:refactor SDKContext as static.

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

@ -81,7 +81,7 @@ For example:
<groupId>com.tencent.cloud</groupId>
<artifactId>spring-cloud-tencent-dependencies</artifactId>
<!--version number-->
<version>1.11.7-Hoxton.SR12</version>
<version>1.11.8-Hoxton.SR12</version>
<type>pom</type>
<scope>import</scope>
</dependency>

@ -30,12 +30,9 @@ import com.tencent.cloud.polaris.circuitbreaker.resttemplate.PolarisCircuitBreak
import com.tencent.cloud.polaris.circuitbreaker.zuul.PolarisCircuitBreakerPostZuulFilter;
import com.tencent.cloud.polaris.circuitbreaker.zuul.PolarisCircuitBreakerZuulFilter;
import com.tencent.cloud.polaris.circuitbreaker.zuul.PolarisZuulFallbackFactory;
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;
@ -45,11 +42,9 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean
import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory;
import org.springframework.cloud.client.circuitbreaker.Customizer;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.cloud.openfeign.PolarisFeignCircuitBreakerTargeterAutoConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.env.Environment;
@ -61,12 +56,6 @@ import org.springframework.core.env.Environment;
@Configuration(proxyBeanMethods = false)
@ConditionalOnPolarisCircuitBreakerEnabled
@AutoConfigureAfter(RpcEnhancementAutoConfiguration.class)
@Import({
ReactivePolarisCircuitBreakerAutoConfiguration.class,
PolarisFeignCircuitBreakerTargeterAutoConfiguration.class,
PolarisCircuitBreakerFeignClientAutoConfiguration.class,
GatewayPolarisCircuitBreakerAutoConfiguration.class
})
public class PolarisCircuitBreakerAutoConfiguration {
@Autowired(required = false)
@ -85,30 +74,25 @@ public class PolarisCircuitBreakerAutoConfiguration {
return new PolarisCircuitBreakerRestTemplateBeanPostProcessor(applicationContext);
}
@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(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;
}

@ -17,10 +17,7 @@
package com.tencent.cloud.polaris.circuitbreaker.config;
import com.tencent.cloud.polaris.context.ConditionalOnPolarisEnabled;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import com.tencent.cloud.rpc.enhancement.config.RpcEnhancementAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@ -30,8 +27,13 @@ import org.springframework.context.annotation.Import;
* @author lepdou 2022-03-29
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnPolarisEnabled
@Import({PolarisContextAutoConfiguration.class, RpcEnhancementAutoConfiguration.class, PolarisCircuitBreakerAutoConfiguration.class})
@ConditionalOnProperty("spring.cloud.polaris.enabled")
@Import({
PolarisCircuitBreakerAutoConfiguration.class,
ReactivePolarisCircuitBreakerAutoConfiguration.class,
PolarisCircuitBreakerFeignClientAutoConfiguration.class,
GatewayPolarisCircuitBreakerAutoConfiguration.class
})
public class PolarisCircuitBreakerBootstrapConfiguration {
}

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

@ -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()));
@ -99,7 +100,9 @@ public class PolarisCircuitBreakerMockServerTest {
if (null != namingServer) {
namingServer.terminate();
}
mockedApplicationContextAwareUtils.close();
if (null != mockedApplicationContextAwareUtils) {
mockedApplicationContextAwareUtils.close();
}
}
@Test

@ -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;
@ -43,6 +51,8 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
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;
@ -55,7 +65,6 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import static com.tencent.polaris.test.common.Consts.NAMESPACE_TEST;
import static com.tencent.polaris.test.common.Consts.SERVICE_CIRCUIT_BREAKER;
import static com.tencent.polaris.test.common.TestUtils.SERVER_ADDRESS_ENV;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@ -71,8 +80,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
"spring.cloud.gateway.enabled=false",
"feign.circuitbreaker.enabled=true",
"spring.cloud.polaris.namespace=" + NAMESPACE_TEST,
"spring.cloud.polaris.service=" + SERVICE_CIRCUIT_BREAKER,
"spring.cloud.polaris.address=grpc://127.0.0.1:10081"
"spring.cloud.polaris.service=test"
})
public class PolarisCircuitBreakerFeignIntegrationTest {
@ -91,7 +99,7 @@ public class PolarisCircuitBreakerFeignIntegrationTest {
private BazService bazService;
@Test
public void contextLoads() throws Exception {
public void contextLoads() {
assertThat(echoService).isNotNull();
assertThat(fooService).isNotNull();
}
@ -158,6 +166,9 @@ public class PolarisCircuitBreakerFeignIntegrationTest {
@EnableFeignClients
public static class TestConfig {
@Autowired(required = false)
private List<Customizer<PolarisCircuitBreakerFactory>> customizers = new ArrayList<>();
@Bean
public EchoServiceFallback echoServiceFallback() {
return new EchoServiceFallback();
@ -198,6 +209,30 @@ public class PolarisCircuitBreakerFeignIntegrationTest {
return CircuitBreakAPIFactory.createCircuitBreakAPIByConfig(configuration);
}
@Bean
public ConsumerAPI consumerAPI(NamingServer namingServer) {
com.tencent.polaris.api.config.Configuration configuration = TestUtils.configWithEnvAddress();
return DiscoveryAPIFactory.createConsumerAPIByConfig(configuration);
}
@Bean
public SuccessCircuitBreakerReporter successCircuitBreakerReporter(RpcEnhancementReporterProperties properties,
CircuitBreakAPI circuitBreakAPI) {
return new SuccessCircuitBreakerReporter(properties, circuitBreakAPI);
}
@Bean
public ExceptionCircuitBreakerReporter exceptionCircuitBreakerReporter(RpcEnhancementReporterProperties properties,
CircuitBreakAPI circuitBreakAPI) {
return new ExceptionCircuitBreakerReporter(properties, circuitBreakAPI);
}
@Bean
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 {
@ -205,7 +240,7 @@ public class PolarisCircuitBreakerFeignIntegrationTest {
@Override
public String echo(@RequestParam("str") String param) throws InvocationTargetException {
if (param == null) {
throw new InvocationTargetException(new Exception());
throw new InvocationTargetException(new Exception(), "test InvocationTargetException");
}
return "echo fallback";
}

@ -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.gateway.filter.factory.SpringCloudCircuitBreakerFilterFactory;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
@ -150,6 +161,9 @@ public class PolarisCircuitBreakerGatewayIntegrationTest {
@EnableAutoConfiguration
public static class TestApplication {
@Autowired(required = false)
private List<Customizer<PolarisCircuitBreakerFactory>> customizers = new ArrayList<>();
@Bean
public PreDestroy preDestroy(NamingServer namingServer) {
return new PreDestroy(namingServer);
@ -180,6 +194,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<String> codeSets = new HashSet<>();

@ -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;
@ -45,6 +52,8 @@ import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
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;
@ -63,7 +72,6 @@ import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.DefaultUriBuilderFactory;
import static com.tencent.polaris.test.common.Consts.NAMESPACE_TEST;
import static com.tencent.polaris.test.common.Consts.SERVICE_CIRCUIT_BREAKER;
import static com.tencent.polaris.test.common.TestUtils.SERVER_ADDRESS_ENV;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@ -82,7 +90,7 @@ import static org.springframework.test.web.client.response.MockRestResponseCreat
"spring.cloud.gateway.enabled=false",
"feign.circuitbreaker.enabled=true",
"spring.cloud.polaris.namespace=" + NAMESPACE_TEST,
"spring.cloud.polaris.service=" + SERVICE_CIRCUIT_BREAKER
"spring.cloud.polaris.service=test"
})
public class PolarisCircuitBreakerRestTemplateIntegrationTest {
@ -159,6 +167,13 @@ public class PolarisCircuitBreakerRestTemplateIntegrationTest {
@EnableFeignClients
public static class TestConfig {
@Autowired(required = false)
private List<Customizer<PolarisCircuitBreakerFactory>> customizers = new ArrayList<>();
{
PolarisSDKContextManager.innerDestroy();
}
@Bean
@com.tencent.cloud.polaris.circuitbreaker.resttemplate.PolarisCircuitBreaker(fallback = "fallback")
public RestTemplate defaultRestTemplate() {
@ -259,6 +274,27 @@ public class PolarisCircuitBreakerRestTemplateIntegrationTest {
return CircuitBreakAPIFactory.createCircuitBreakAPIByConfig(configuration);
}
@Bean
public SuccessCircuitBreakerReporter successCircuitBreakerReporter(RpcEnhancementReporterProperties properties,
CircuitBreakAPI circuitBreakAPI) {
return new SuccessCircuitBreakerReporter(properties, circuitBreakAPI);
}
@Bean
public ExceptionCircuitBreakerReporter exceptionCircuitBreakerReporter(RpcEnhancementReporterProperties properties,
CircuitBreakAPI circuitBreakAPI) {
return new ExceptionCircuitBreakerReporter(properties, circuitBreakAPI);
}
@Bean
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 {

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

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

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

@ -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;
@ -45,14 +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,
public PolarisRefreshApplicationReadyEventListener(PolarisSDKContextManager polarisSDKContextManager,
PolarisServiceStatusChangeListener polarisServiceStatusChangeListener) {
this.polarisDiscoveryHandler = polarisDiscoveryHandler;
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.

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

@ -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<PolarisRegistration> {
public class PolarisServiceRegistry implements ServiceRegistry<PolarisRegistration>, 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;
@ -115,7 +119,7 @@ public class PolarisServiceRegistry implements ServiceRegistry<PolarisRegistrati
instanceRegisterRequest.setVersion(polarisDiscoveryProperties.getVersion());
instanceRegisterRequest.setInstanceId(polarisDiscoveryProperties.getInstanceId());
try {
ProviderAPI providerClient = polarisDiscoveryHandler.getProviderAPI();
ProviderAPI providerClient = polarisSDKContextManager.getProviderAPI();
InstanceRegisterResponse instanceRegisterResponse;
if (StringUtils.isBlank(polarisDiscoveryProperties.getHealthCheckUrl())) {
instanceRegisterResponse = providerClient.registerInstance(instanceRegisterRequest);
@ -133,10 +137,16 @@ public class PolarisServiceRegistry implements ServiceRegistry<PolarisRegistrati
staticMetadataManager.getMergedStaticMetadata());
if (Objects.nonNull(polarisStatProperties) && polarisStatProperties.isEnabled()) {
try {
StatReporter statReporter = (StatReporter) polarisDiscoveryHandler.getSdkContext().getPlugins()
StatReporter statReporter = (StatReporter) polarisSDKContextManager.getSDKContext().getPlugins()
.getPlugin(PluginTypes.STAT_REPORTER.getBaseType(), StatReporterConfig.DEFAULT_REPORTER_PROMETHEUS);
if (Objects.nonNull(statReporter)) {
LOGGER.info("Stat server started on port: " + statReporter.metaInfo().getPort() + " (http)");
ReporterMetaInfo reporterMetaInfo = statReporter.metaInfo();
if (reporterMetaInfo.getPort() != null) {
LOGGER.info("Stat server started on port: " + reporterMetaInfo.getPort() + " (http)");
}
else {
LOGGER.info("Stat server is set to type of Push gateway");
}
}
else {
LOGGER.warn("Plugin StatReporter not found");
@ -147,10 +157,12 @@ public class PolarisServiceRegistry implements ServiceRegistry<PolarisRegistrati
}
}
ServiceConfigImpl serviceConfig = (ServiceConfigImpl) polarisDiscoveryHandler.getSdkContext().getConfig()
ServiceConfigImpl serviceConfig = (ServiceConfigImpl) polarisSDKContextManager.getSDKContext().getConfig()
.getProvider().getService();
serviceConfig.setNamespace(polarisDiscoveryProperties.getNamespace());
serviceConfig.setName(serviceId);
PolarisSDKContextManager.isRegistered = true;
}
catch (Exception e) {
LOGGER.error("polaris registry, {} register failed...{},", registration.getServiceId(), registration, e);
@ -175,7 +187,7 @@ public class PolarisServiceRegistry implements ServiceRegistry<PolarisRegistrati
deRegisterRequest.setPort(registration.getPort());
try {
ProviderAPI providerClient = polarisDiscoveryHandler.getProviderAPI();
ProviderAPI providerClient = polarisSDKContextManager.getProviderAPI();
providerClient.deRegister(deRegisterRequest);
}
catch (Exception e) {
@ -185,8 +197,9 @@ public class PolarisServiceRegistry implements ServiceRegistry<PolarisRegistrati
if (null != heartbeatExecutor) {
heartbeatExecutor.shutdown();
}
LOGGER.info("De-registration finished.");
PolarisSDKContextManager.isRegistered = false;
}
LOGGER.info("De-registration finished.");
}
@Override
@ -241,7 +254,7 @@ public class PolarisServiceRegistry implements ServiceRegistry<PolarisRegistrati
return;
}
polarisDiscoveryHandler.getProviderAPI().heartbeat(heartbeatRequest);
polarisSDKContextManager.getProviderAPI().heartbeat(heartbeatRequest);
LOGGER.trace("Polaris heartbeat is sent");
}
catch (PolarisException e) {
@ -252,4 +265,11 @@ public class PolarisServiceRegistry implements ServiceRegistry<PolarisRegistrati
}
}, polarisDiscoveryProperties.getHeartbeatInterval(), polarisDiscoveryProperties.getHeartbeatInterval(), SECONDS);
}
@Override
public void destroy() {
if (heartbeatExecutor != null) {
heartbeatExecutor.shutdown();
}
}
}

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

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

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

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

@ -0,0 +1,65 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.tencent.cloud.polaris.discovery;
import com.tencent.cloud.polaris.PolarisDiscoveryProperties;
import com.tencent.cloud.polaris.context.PolarisSDKContextManager;
import com.tencent.polaris.api.core.ConsumerAPI;
import com.tencent.polaris.api.exception.PolarisException;
import com.tencent.polaris.api.rpc.ServicesResponse;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import static com.tencent.polaris.test.common.Consts.NAMESPACE_TEST;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
/**
* Test for {@link PolarisDiscoveryHandler}.
*
* @author Haotian Zhang
*/
@ExtendWith(MockitoExtension.class)
public class PolarisDiscoveryHandlerTest {
private PolarisDiscoveryHandler polarisDiscoveryHandler;
@BeforeEach
void setUp() {
PolarisDiscoveryProperties polarisDiscoveryProperties = mock(PolarisDiscoveryProperties.class);
doReturn(NAMESPACE_TEST).when(polarisDiscoveryProperties).getNamespace();
ConsumerAPI consumerAPI = mock(ConsumerAPI.class);
ServicesResponse servicesResponse = mock(ServicesResponse.class);
doReturn(servicesResponse).when(consumerAPI).getServices(any());
PolarisSDKContextManager polarisSDKContextManager = mock(PolarisSDKContextManager.class);
doReturn(consumerAPI).when(polarisSDKContextManager).getConsumerAPI();
polarisDiscoveryHandler = new PolarisDiscoveryHandler(polarisDiscoveryProperties, polarisSDKContextManager);
}
@Test
public void testGetServices() throws PolarisException {
ServicesResponse servicesResponse = polarisDiscoveryHandler.getServices();
assertThat(servicesResponse).isNotNull();
}
}

@ -17,11 +17,13 @@
package com.tencent.cloud.polaris.discovery.reactive;
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 {
@ -65,6 +67,11 @@ public class PolarisReactiveDiscoveryClientConfigurationTest {
}
}
@BeforeEach
void setUp() {
PolarisSDKContextManager.innerDestroy();
}
@Test
public void testDefaultInitialization() {
this.contextRunner.run(context -> assertThat(context)
@ -76,6 +83,7 @@ public class PolarisReactiveDiscoveryClientConfigurationTest {
contextRunner.run(context -> assertThat(context).hasBean("polarisReactiveDiscoveryClientHealthIndicator"));
}
@Configuration
@EnableAutoConfiguration
static class PolarisReactiveDiscoveryClientConfiguration {

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

@ -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<ServerConnectorConfigImpl> serverConnectorConfigs = configuration.getGlobal().getServerConnectors();
Map<String, String> metadata = null;
for (ServerConnectorConfigImpl serverConnectorConfig : serverConnectorConfigs) {
@ -86,5 +93,8 @@ public class ConsulContextPropertiesTest {
@SpringBootApplication
protected static class TestApplication {
static {
PolarisSDKContextManager.innerDestroy();
}
}
}

@ -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<ServerConnectorConfigImpl> serverConnectorConfigs = configuration.getGlobal().getServerConnectors();
Optional<ServerConnectorConfigImpl> optionalServerConnectorConfig = serverConnectorConfigs.stream().filter(
item -> "nacos".equals(item.getId())
@ -87,5 +88,9 @@ public class NacosContextPropertiesTest {
@SpringBootApplication
protected static class TestApplication {
static {
PolarisSDKContextManager.innerDestroy();
}
}
}

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

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

@ -20,6 +20,8 @@ package com.tencent.cloud.polaris.ribbon;
import com.netflix.client.config.DefaultClientConfigImpl;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.ServerList;
import com.tencent.cloud.polaris.context.PolarisSDKContextManager;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
@ -40,6 +42,11 @@ public class PolarisRibbonServerListConfigurationTest {
private final ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner();
@BeforeAll
static void beforeAll() {
PolarisSDKContextManager.innerDestroy();
}
@Test
public void testDefaultInitialization() {
this.applicationContextRunner

@ -22,6 +22,7 @@ import java.util.List;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.Server;
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;
@ -60,8 +61,7 @@ public class PolarisServerListTest {
PolarisContextAutoConfiguration.class,
PolarisServerListTest.PolarisPropertiesConfiguration.class,
PolarisDiscoveryClientConfiguration.class,
PolarisDiscoveryAutoConfiguration.class,
PolarisContextAutoConfiguration.class))
PolarisDiscoveryAutoConfiguration.class))
.withPropertyValues("spring.application.name=" + SERVICE_PROVIDER)
.withPropertyValues("server.port=" + PORT)
.withPropertyValues("spring.cloud.polaris.address=grpc://127.0.0.1:10081")
@ -78,6 +78,7 @@ public class PolarisServerListTest {
namingServer.getNamingService().addService(new ServiceKey(NAMESPACE_TEST, SERVICE_PROVIDER));
}
@AfterAll
static void afterAll() {
if (null != namingServer) {
@ -91,6 +92,7 @@ public class PolarisServerListTest {
iClientConfig = mock(IClientConfig.class);
when(iClientConfig.getClientName()).thenReturn(SERVICE_PROVIDER);
PolarisSDKContextManager.innerDestroy();
}
@Test

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

@ -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;
@ -144,5 +150,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);
}
}
}

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

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

@ -0,0 +1,39 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.tencent.cloud.tsf.adapter.config;
import com.tencent.polaris.circuitbreak.api.flow.CircuitBreakerFlow;
import com.tencent.polaris.client.api.SDKContext;
/**
* TsfRouterFlow.
*
* @author sean yu
*/
public class TsfCircuitBreakerFlow implements CircuitBreakerFlow {
@Override
public String getName() {
return PolarisTsfFlowConfigModifier.TSF_FLOW_NAME;
}
@Override
public void setSDKContext(SDKContext sdkContext) {
}
}

@ -0,0 +1,39 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.tencent.cloud.tsf.adapter.config;
import com.tencent.polaris.client.api.SDKContext;
import com.tencent.polaris.ratelimit.api.flow.LimitFlow;
/**
* TsfRouterFlow.
*
* @author sean yu
*/
public class TsfLimitFlow implements LimitFlow {
@Override
public String getName() {
return PolarisTsfFlowConfigModifier.TSF_FLOW_NAME;
}
@Override
public void setSDKContext(SDKContext sdkContext) {
}
}

@ -0,0 +1,59 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
*/
package com.tencent.cloud.plugin.featureenv;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Test for {@link FeatureEnvAutoConfiguration}.
*
* @author Hoatian Zhang
*/
@ExtendWith(MockitoExtension.class)
public class FeatureEnvAutoConfigurationTest {
private final ApplicationContextRunner enabledApplicationContextRunner = new ApplicationContextRunner();
private final ApplicationContextRunner disabledApplicationContextRunner = new ApplicationContextRunner();
@Test
public void testEnabled() {
this.enabledApplicationContextRunner.withConfiguration(AutoConfigurations.of(FeatureEnvAutoConfiguration.class))
.run(context -> {
assertThat(context).hasSingleBean(FeatureEnvProperties.class);
assertThat(context).hasSingleBean(FeatureEnvRouterRequestInterceptor.class);
});
}
@Test
public void testDisabled() {
this.disabledApplicationContextRunner.withConfiguration(AutoConfigurations.of(FeatureEnvAutoConfiguration.class))
.withPropertyValues("spring.cloud.tencent.plugin.router.feature-env.enabled=false")
.run(context -> {
assertThat(context).doesNotHaveBean(FeatureEnvProperties.class);
assertThat(context).doesNotHaveBean(FeatureEnvRouterRequestInterceptor.class);
});
}
}

@ -23,7 +23,7 @@ import com.tencent.cloud.plugin.gateway.staining.rule.RuleStainingExecutor;
import com.tencent.cloud.plugin.gateway.staining.rule.RuleStainingProperties;
import com.tencent.cloud.plugin.gateway.staining.rule.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());
}
}
}

@ -94,7 +94,7 @@
<groupId>com.tencent.polaris</groupId>
<artifactId>flow-cache-expired</artifactId>
</dependency>
<dependency>
<groupId>com.tencent.polaris</groupId>
<artifactId>polaris-router-factory</artifactId>

@ -0,0 +1,207 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.tencent.cloud.polaris.context;
import java.util.List;
import java.util.Objects;
import com.tencent.cloud.polaris.context.config.PolarisContextProperties;
import com.tencent.polaris.api.control.Destroyable;
import com.tencent.polaris.api.core.ConsumerAPI;
import com.tencent.polaris.api.core.ProviderAPI;
import com.tencent.polaris.assembly.api.AssemblyAPI;
import com.tencent.polaris.assembly.factory.AssemblyAPIFactory;
import com.tencent.polaris.circuitbreak.api.CircuitBreakAPI;
import com.tencent.polaris.circuitbreak.factory.CircuitBreakAPIFactory;
import com.tencent.polaris.client.api.SDKContext;
import com.tencent.polaris.factory.api.DiscoveryAPIFactory;
import com.tencent.polaris.factory.api.RouterAPIFactory;
import com.tencent.polaris.ratelimit.api.core.LimitAPI;
import com.tencent.polaris.ratelimit.factory.LimitAPIFactory;
import com.tencent.polaris.router.api.core.RouterAPI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;
/**
* Manager for static Polaris SDK context.
*
* @author Haotian Zhang
*/
public class PolarisSDKContextManager {
private static final Logger LOG = LoggerFactory.getLogger(PolarisSDKContextManager.class);
/**
* Constant for checking before destroy SDK context.
*/
public volatile static boolean isRegistered = false;
private volatile static SDKContext sdkContext;
private volatile static ProviderAPI providerAPI;
private volatile static ConsumerAPI consumerAPI;
private volatile static RouterAPI routerAPI;
private volatile static CircuitBreakAPI circuitBreakAPI;
private volatile static LimitAPI limitAPI;
private volatile static AssemblyAPI assemblyAPI;
private final PolarisContextProperties properties;
private final Environment environment;
private final List<PolarisConfigModifier> modifierList;
public PolarisSDKContextManager(PolarisContextProperties properties, Environment environment, List<PolarisConfigModifier> modifierList) {
this.properties = properties;
this.environment = environment;
this.modifierList = modifierList;
}
/**
* Don't call this method directly.
*/
public static void innerDestroy() {
if (Objects.nonNull(sdkContext)) {
try {
// destroy ProviderAPI
if (Objects.nonNull(providerAPI)) {
((AutoCloseable) providerAPI).close();
providerAPI = null;
}
// destroy ConsumerAPI
if (Objects.nonNull(consumerAPI)) {
((AutoCloseable) consumerAPI).close();
consumerAPI = null;
}
// destroy RouterAPI
if (Objects.nonNull(routerAPI)) {
((Destroyable) routerAPI).destroy();
routerAPI = null;
}
// destroy CircuitBreakAPI
if (Objects.nonNull(circuitBreakAPI)) {
((Destroyable) circuitBreakAPI).destroy();
circuitBreakAPI = null;
}
// destroy LimitAPI
if (Objects.nonNull(limitAPI)) {
((AutoCloseable) limitAPI).close();
limitAPI = null;
}
// destroy AssemblyAPI
if (Objects.nonNull(assemblyAPI)) {
((Destroyable) assemblyAPI).destroy();
assemblyAPI = null;
}
sdkContext.destroy();
sdkContext = null;
LOG.info("Polaris SDK context is destroyed.");
}
catch (Throwable throwable) {
LOG.error("destroy Polaris SDK context failed.", throwable);
}
}
}
public void init() {
if (null == sdkContext) {
try {
// init SDKContext
sdkContext = SDKContext.initContextByConfig(properties.configuration(modifierList,
() -> environment.getProperty("spring.cloud.client.ip-address"),
() -> environment.getProperty("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;
}
}

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

@ -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;
@ -31,13 +31,13 @@ import org.springframework.context.annotation.Configuration;
*
* @author lepdou 2022-06-28
*/
@Configuration
@Configuration(proxyBeanMethods = false)
@ConditionalOnPolarisEnabled
public class PolarisContextPostConfiguration {
@Bean
public PostInitPolarisSDKContext postInitPolarisSDKContext(
SDKContext sdkContext, StaticMetadataManager staticMetadataManager) {
return new PostInitPolarisSDKContext(sdkContext, staticMetadataManager);
PolarisSDKContextManager polarisSDKContextManager, StaticMetadataManager staticMetadataManager) {
return new PostInitPolarisSDKContext(polarisSDKContextManager.getSDKContext(), staticMetadataManager);
}
}

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

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

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

@ -26,12 +26,11 @@ import com.netflix.loadbalancer.RandomRule;
import com.netflix.loadbalancer.RoundRobinRule;
import com.netflix.loadbalancer.Server;
import com.netflix.loadbalancer.ServerList;
import com.tencent.cloud.polaris.context.PolarisSDKContextManager;
import com.tencent.cloud.polaris.loadbalancer.PolarisLoadBalancer;
import com.tencent.cloud.polaris.loadbalancer.PolarisRingHashRule;
import com.tencent.cloud.polaris.loadbalancer.PolarisWeightedRandomRule;
import com.tencent.cloud.polaris.loadbalancer.transformer.InstanceTransformer;
import com.tencent.polaris.api.core.ConsumerAPI;
import com.tencent.polaris.router.api.core.RouterAPI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
@ -48,10 +47,10 @@ public class PolarisRibbonClientConfiguration {
@Bean
public ILoadBalancer polarisLoadBalancer(IClientConfig iClientConfig, IRule iRule,
IPing iPing, ServerList<Server> serverList,
ConsumerAPI consumerAPI, PolarisLoadBalancerProperties polarisLoadBalancerProperties,
PolarisSDKContextManager polarisSDKContextManager, PolarisLoadBalancerProperties polarisLoadBalancerProperties,
@Autowired(required = false) InstanceTransformer instanceTransformer) {
return new PolarisLoadBalancer(iClientConfig, iRule, iPing, serverList,
consumerAPI, polarisLoadBalancerProperties, instanceTransformer);
polarisSDKContextManager.getConsumerAPI(), polarisLoadBalancerProperties, instanceTransformer);
}
@Bean
@ -71,14 +70,14 @@ public class PolarisRibbonClientConfiguration {
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(value = "spring.cloud.polaris.loadbalancer.strategy", havingValue = "polarisWeightedRandom")
public IRule polarisWeightedRandomRule(RouterAPI routerAPI) {
return new PolarisWeightedRandomRule(routerAPI);
public IRule polarisWeightedRandomRule(PolarisSDKContextManager polarisSDKContextManager) {
return new PolarisWeightedRandomRule(polarisSDKContextManager.getRouterAPI());
}
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(value = "spring.cloud.polaris.loadbalancer.strategy", havingValue = "polarisRingHash")
public IRule polarisRingHashRule(RouterAPI routerAPI) {
return new PolarisRingHashRule(routerAPI);
public IRule polarisRingHashRule(PolarisSDKContextManager polarisSDKContextManager) {
return new PolarisRingHashRule(polarisSDKContextManager.getRouterAPI());
}
}

@ -22,6 +22,7 @@ import java.util.LinkedList;
import java.util.List;
import com.netflix.loadbalancer.Server;
import com.tencent.cloud.common.metadata.MetadataContext;
import com.tencent.cloud.common.pojo.PolarisServer;
import com.tencent.polaris.api.pojo.DefaultInstance;
import com.tencent.polaris.api.pojo.DefaultServiceInstances;
@ -29,6 +30,7 @@ import com.tencent.polaris.api.pojo.Instance;
import com.tencent.polaris.api.pojo.ServiceInstances;
import com.tencent.polaris.api.pojo.ServiceKey;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@ -52,6 +54,12 @@ public class LoadBalancerUtilsTest {
private static final String TEST_NAMESPACE = "testNamespace";
private static final String TEST_SERVICE = "testService";
@BeforeEach
void setUp() {
MetadataContext.LOCAL_NAMESPACE = TEST_NAMESPACE;
MetadataContext.LOCAL_SERVICE = TEST_SERVICE;
}
@Test
public void testTransferServersToServiceInstances() {
ServiceInstances serviceInstances = LoadBalancerUtils.transferServersToServiceInstances(assembleServers());

@ -26,12 +26,9 @@ import com.netflix.loadbalancer.NoOpPing;
import com.netflix.loadbalancer.RandomRule;
import com.netflix.loadbalancer.Server;
import com.netflix.loadbalancer.ServerList;
import com.tencent.cloud.polaris.context.PolarisSDKContextManager;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import com.tencent.cloud.polaris.loadbalancer.PolarisLoadBalancer;
import com.tencent.polaris.api.core.ConsumerAPI;
import com.tencent.polaris.client.api.SDKContext;
import com.tencent.polaris.discovery.client.api.DefaultConsumerAPI;
import com.tencent.polaris.router.api.core.RouterAPI;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.BeanFactory;
@ -68,7 +65,6 @@ public class PolarisLoadBalancerAutoConfigurationTest {
@Test
public void testDefaultInitialization() {
this.contextRunner.run(context -> {
assertThat(context).hasSingleBean(RouterAPI.class);
assertThat(context).hasSingleBean(PolarisLoadBalancerProperties.class);
assertThat(hasSinglePolarisLoadBalancer(context)).isTrue();
});
@ -85,7 +81,7 @@ public class PolarisLoadBalancerAutoConfigurationTest {
static class PolarisRibbonTest {
@Autowired
private SDKContext sdkContext;
private PolarisSDKContextManager polarisSDKContextManager;
@Bean
public IClientConfig iClientConfig() {
@ -108,10 +104,5 @@ public class PolarisLoadBalancerAutoConfigurationTest {
public ServerList<Server> serverList() {
return new StaticServerList<>();
}
@Bean
public ConsumerAPI consumerAPI() {
return new DefaultConsumerAPI(sdkContext);
}
}
}

@ -22,6 +22,7 @@ import java.util.List;
import com.netflix.zuul.ZuulFilter;
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.filter.EnhancedReactiveFilter;
@ -40,8 +41,6 @@ import com.tencent.cloud.rpc.enhancement.webclient.RibbonLoadBalancerClientAspec
import com.tencent.cloud.rpc.enhancement.zuul.EnhancedErrorZuulFilter;
import com.tencent.cloud.rpc.enhancement.zuul.EnhancedPostZuulFilter;
import com.tencent.cloud.rpc.enhancement.zuul.EnhancedRouteZuulFilter;
import com.tencent.polaris.api.core.ConsumerAPI;
import com.tencent.polaris.client.api.SDKContext;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.annotation.Autowired;
@ -89,20 +88,20 @@ public class RpcEnhancementAutoConfiguration {
public EnhancedPluginRunner enhancedFeignPluginRunner(
@Autowired(required = false) List<EnhancedPlugin> 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());
}
@Configuration(proxyBeanMethods = false)
@ -243,7 +242,6 @@ public class RpcEnhancementAutoConfiguration {
public EnhancedGatewayGlobalFilter enhancedPolarisGatewayReporter(@Lazy EnhancedPluginRunner pluginRunner) {
return new EnhancedGatewayGlobalFilter(pluginRunner);
}
}
/**

@ -23,7 +23,6 @@ import com.tencent.cloud.rpc.enhancement.plugin.EnhancedPluginRunner;
import com.tencent.cloud.rpc.enhancement.plugin.reporter.ExceptionPolarisReporter;
import com.tencent.cloud.rpc.enhancement.plugin.reporter.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);

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

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

Loading…
Cancel
Save