fix: adapt for nacos instance (#933)

pull/945/head
Shanyou Yu (Sean Yu) 2 years ago committed by GitHub
parent 1f4a3bcb4f
commit 38f25689dc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -10,3 +10,4 @@
- [fix:fix nacos and consul registration.](https://github.com/Tencent/spring-cloud-tencent/pull/919) - [fix:fix nacos and consul registration.](https://github.com/Tencent/spring-cloud-tencent/pull/919)
- [Documentation content changes: add circuitbreaker readme.](https://github.com/Tencent/spring-cloud-tencent/pull/929) - [Documentation content changes: add circuitbreaker readme.](https://github.com/Tencent/spring-cloud-tencent/pull/929)
- [fix: fix PolarisRouterServiceInstanceListSupplier npe with reactive feign.](https://github.com/Tencent/spring-cloud-tencent/pull/925) - [fix: fix PolarisRouterServiceInstanceListSupplier npe with reactive feign.](https://github.com/Tencent/spring-cloud-tencent/pull/925)
- [fix: adapt for nacos instance.](https://github.com/Tencent/spring-cloud-tencent/pull/933)

@ -88,7 +88,7 @@
<properties> <properties>
<!-- Project revision --> <!-- Project revision -->
<revision>1.11.0-2020.0.6-SNAPSHOT</revision> <revision>1.10.3-2020.0.6</revision>
<!-- Spring Framework --> <!-- Spring Framework -->
<spring.framework.version>5.3.25</spring.framework.version> <spring.framework.version>5.3.25</spring.framework.version>

@ -81,7 +81,7 @@ import static org.assertj.core.api.Assertions.assertThat;
) )
@AutoConfigureWireMock(port = 0) @AutoConfigureWireMock(port = 0)
@ActiveProfiles("test-gateway") @ActiveProfiles("test-gateway")
@AutoConfigureWebTestClient(timeout = "10000") @AutoConfigureWebTestClient(timeout = "1000000")
public class PolarisCircuitBreakerGatewayIntegrationTest { public class PolarisCircuitBreakerGatewayIntegrationTest {
private static final String TEST_SERVICE_NAME = "test-service-callee"; private static final String TEST_SERVICE_NAME = "test-service-callee";

@ -16,6 +16,7 @@
*/ */
package com.tencent.cloud.polaris.endpoint; package com.tencent.cloud.polaris.endpoint;
import java.util.Collections;
import java.util.Map; import java.util.Map;
import com.tencent.cloud.polaris.PolarisDiscoveryProperties; import com.tencent.cloud.polaris.PolarisDiscoveryProperties;
@ -38,6 +39,8 @@ import static com.tencent.polaris.test.common.Consts.NAMESPACE_TEST;
import static com.tencent.polaris.test.common.Consts.PORT; import static com.tencent.polaris.test.common.Consts.PORT;
import static com.tencent.polaris.test.common.Consts.SERVICE_PROVIDER; import static com.tencent.polaris.test.common.Consts.SERVICE_PROVIDER;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
/** /**
* Test for polaris discovery endpoint. * Test for polaris discovery endpoint.
@ -79,12 +82,17 @@ public class PolarisDiscoveryEndpointTest {
.getBean(PolarisDiscoveryProperties.class); .getBean(PolarisDiscoveryProperties.class);
DiscoveryClient discoveryClient = context DiscoveryClient discoveryClient = context
.getBean(PolarisDiscoveryClient.class); .getBean(PolarisDiscoveryClient.class);
PolarisDiscoveryHandler polarisDiscoveryHandler = context.getBean(PolarisDiscoveryHandler.class); PolarisDiscoveryHandler polarisDiscoveryHandler = context.getBean(PolarisDiscoveryHandler.class);
PolarisDiscoveryEndpoint polarisDiscoveryEndpoint = new PolarisDiscoveryEndpoint(polarisDiscoveryProperties, discoveryClient, polarisDiscoveryHandler); PolarisDiscoveryEndpoint polarisDiscoveryEndpoint = new PolarisDiscoveryEndpoint(polarisDiscoveryProperties, discoveryClient, polarisDiscoveryHandler);
Map<String, Object> mapInfo = polarisDiscoveryEndpoint.polarisDiscovery("java_provider_test"); Map<String, Object> mapInfo = polarisDiscoveryEndpoint.polarisDiscovery("java_provider_test");
assertThat(polarisDiscoveryProperties).isEqualTo(mapInfo.get("PolarisDiscoveryProperties")); assertThat(polarisDiscoveryProperties).isEqualTo(mapInfo.get("PolarisDiscoveryProperties"));
DiscoveryClient discoveryClient1 = mock(DiscoveryClient.class);
doReturn(Collections.singletonList("xx")).when(discoveryClient1).getServices();
PolarisDiscoveryEndpoint polarisDiscoveryEndpoint1 = new PolarisDiscoveryEndpoint(polarisDiscoveryProperties, discoveryClient1, polarisDiscoveryHandler);
Map<String, Object> mapInfo2 = polarisDiscoveryEndpoint1.polarisDiscovery(null);
assertThat(polarisDiscoveryProperties).isEqualTo(mapInfo2.get("PolarisDiscoveryProperties"));
}); });
} }

@ -76,9 +76,17 @@ public class PolarisRegistrationTest {
doReturn(true).when(consulContextProperties).isRegister(); doReturn(true).when(consulContextProperties).isRegister();
// mock NacosContextProperties // mock NacosContextProperties
nacosContextProperties = mock(NacosContextProperties.class); nacosContextProperties = new NacosContextProperties();
doReturn(true).when(nacosContextProperties).isEnabled(); nacosContextProperties.setEnabled(true);
doReturn(true).when(nacosContextProperties).isRegisterEnabled(); nacosContextProperties.setRegisterEnabled(true);
nacosContextProperties.setContextPath("/");
nacosContextProperties.setClusterName("cluster");
nacosContextProperties.setGroup("");
nacosContextProperties.setDiscoveryEnabled(true);
nacosContextProperties.setPassword("");
nacosContextProperties.setUsername("");
nacosContextProperties.setServerAddr("");
nacosContextProperties.toString();
// mock SDKContext // mock SDKContext
APIConfig apiConfig = mock(APIConfig.class); APIConfig apiConfig = mock(APIConfig.class);
@ -162,7 +170,7 @@ public class PolarisRegistrationTest {
Map<String, String> metadata = polarisRegistration1.getMetadata(); Map<String, String> metadata = polarisRegistration1.getMetadata();
assertThat(metadata).isNotNull(); assertThat(metadata).isNotNull();
assertThat(metadata).isNotEmpty(); assertThat(metadata).isNotEmpty();
assertThat(metadata.size()).isEqualTo(3); assertThat(metadata.size()).isEqualTo(4);
assertThat(metadata.get("key1")).isEqualTo("value1"); assertThat(metadata.get("key1")).isEqualTo("value1");
} }

@ -33,6 +33,7 @@ import com.tencent.cloud.common.metadata.MetadataContextHolder;
import com.tencent.cloud.common.pojo.PolarisServiceInstance; import com.tencent.cloud.common.pojo.PolarisServiceInstance;
import com.tencent.cloud.common.util.JacksonUtils; import com.tencent.cloud.common.util.JacksonUtils;
import com.tencent.cloud.polaris.router.resttemplate.PolarisLoadBalancerRequest; import com.tencent.cloud.polaris.router.resttemplate.PolarisLoadBalancerRequest;
import com.tencent.cloud.polaris.router.spi.InstanceTransformer;
import com.tencent.cloud.polaris.router.spi.RouterRequestInterceptor; import com.tencent.cloud.polaris.router.spi.RouterRequestInterceptor;
import com.tencent.cloud.polaris.router.spi.RouterResponseInterceptor; import com.tencent.cloud.polaris.router.spi.RouterResponseInterceptor;
import com.tencent.polaris.api.exception.ErrorCode; import com.tencent.polaris.api.exception.ErrorCode;
@ -73,14 +74,16 @@ public class PolarisRouterServiceInstanceListSupplier extends DelegatingServiceI
private final RouterAPI routerAPI; private final RouterAPI routerAPI;
private final List<RouterRequestInterceptor> requestInterceptors; private final List<RouterRequestInterceptor> requestInterceptors;
private final List<RouterResponseInterceptor> responseInterceptors; private final List<RouterResponseInterceptor> responseInterceptors;
private final InstanceTransformer instanceTransformer;
public PolarisRouterServiceInstanceListSupplier(ServiceInstanceListSupplier delegate, public PolarisRouterServiceInstanceListSupplier(ServiceInstanceListSupplier delegate,
RouterAPI routerAPI, List<RouterRequestInterceptor> requestInterceptors, RouterAPI routerAPI, List<RouterRequestInterceptor> requestInterceptors,
List<RouterResponseInterceptor> responseInterceptors) { List<RouterResponseInterceptor> responseInterceptors, InstanceTransformer instanceTransformer) {
super(delegate); super(delegate);
this.routerAPI = routerAPI; this.routerAPI = routerAPI;
this.requestInterceptors = requestInterceptors; this.requestInterceptors = requestInterceptors;
this.responseInterceptors = responseInterceptors; this.responseInterceptors = responseInterceptors;
this.instanceTransformer = instanceTransformer;
} }
@Override @Override
@ -143,7 +146,7 @@ public class PolarisRouterServiceInstanceListSupplier extends DelegatingServiceI
} }
Flux<List<ServiceInstance>> doRouter(Flux<List<ServiceInstance>> allServers, PolarisRouterContext routerContext) { Flux<List<ServiceInstance>> doRouter(Flux<List<ServiceInstance>> allServers, PolarisRouterContext routerContext) {
ServiceInstances serviceInstances = RouterUtils.transferServersToServiceInstances(allServers); ServiceInstances serviceInstances = RouterUtils.transferServersToServiceInstances(allServers, instanceTransformer);
List<ServiceInstance> filteredInstances = new ArrayList<>(); List<ServiceInstance> filteredInstances = new ArrayList<>();
if (serviceInstances.getInstances().size() > 0) { if (serviceInstances.getInstances().size() > 0) {

@ -25,8 +25,7 @@ import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import com.tencent.cloud.common.metadata.MetadataContext; import com.tencent.cloud.common.metadata.MetadataContext;
import com.tencent.cloud.common.pojo.PolarisServiceInstance; import com.tencent.cloud.polaris.router.spi.InstanceTransformer;
import com.tencent.polaris.api.pojo.DefaultInstance;
import com.tencent.polaris.api.pojo.DefaultServiceInstances; import com.tencent.polaris.api.pojo.DefaultServiceInstances;
import com.tencent.polaris.api.pojo.Instance; import com.tencent.polaris.api.pojo.Instance;
import com.tencent.polaris.api.pojo.ServiceInstances; import com.tencent.polaris.api.pojo.ServiceInstances;
@ -57,14 +56,14 @@ public final class RouterUtils {
* @param servers servers * @param servers servers
* @return ServiceInstances * @return ServiceInstances
*/ */
public static ServiceInstances transferServersToServiceInstances(Flux<List<ServiceInstance>> servers) { public static ServiceInstances transferServersToServiceInstances(Flux<List<ServiceInstance>> servers, InstanceTransformer instanceTransformer) {
CountDownLatch latch = new CountDownLatch(1); CountDownLatch latch = new CountDownLatch(1);
AtomicReference<List<Instance>> instancesRef = new AtomicReference<>(); AtomicReference<List<Instance>> instancesRef = new AtomicReference<>();
servers.subscribe(serviceInstances -> { servers.subscribe(serviceInstances -> {
instancesRef.set(serviceInstances instancesRef.set(serviceInstances
.stream() .stream()
.map(RouterUtils::transferServerToServiceInstance) .map(instanceTransformer::transform)
.collect(Collectors.toList())); .collect(Collectors.toList()));
latch.countDown(); latch.countDown();
@ -87,31 +86,4 @@ public final class RouterUtils {
return new DefaultServiceInstances(serviceKey, instances); return new DefaultServiceInstances(serviceKey, instances);
} }
/**
* transfer ServiceInstance to DefaultInstance.
*
* @param serviceInstance serviceInstance
* @return defaultInstance
*/
public static DefaultInstance transferServerToServiceInstance(ServiceInstance serviceInstance) {
DefaultInstance instance = new DefaultInstance();
instance.setNamespace(MetadataContext.LOCAL_NAMESPACE);
instance.setService(serviceInstance.getServiceId());
instance.setProtocol(serviceInstance.getScheme());
instance.setId(serviceInstance.getInstanceId());
instance.setHost(serviceInstance.getHost());
instance.setPort(serviceInstance.getPort());
instance.setMetadata(serviceInstance.getMetadata());
if (serviceInstance instanceof PolarisServiceInstance) {
PolarisServiceInstance polarisServiceInstance = (PolarisServiceInstance) serviceInstance;
instance.setRegion(polarisServiceInstance.getPolarisInstance().getRegion());
instance.setZone(polarisServiceInstance.getPolarisInstance().getZone());
instance.setCampus(polarisServiceInstance.getPolarisInstance().getCampus());
instance.setWeight(polarisServiceInstance.getPolarisInstance().getWeight());
}
return instance;
}
} }

@ -20,12 +20,17 @@ package com.tencent.cloud.polaris.router.config;
import java.util.List; import java.util.List;
import com.tencent.cloud.common.pojo.PolarisServiceInstance;
import com.tencent.cloud.polaris.router.PolarisRouterServiceInstanceListSupplier; import com.tencent.cloud.polaris.router.PolarisRouterServiceInstanceListSupplier;
import com.tencent.cloud.polaris.router.spi.InstanceTransformer;
import com.tencent.cloud.polaris.router.spi.RouterRequestInterceptor; import com.tencent.cloud.polaris.router.spi.RouterRequestInterceptor;
import com.tencent.cloud.polaris.router.spi.RouterResponseInterceptor; import com.tencent.cloud.polaris.router.spi.RouterResponseInterceptor;
import com.tencent.cloud.polaris.router.transformer.PolarisInstanceTransformer;
import com.tencent.polaris.router.api.core.RouterAPI; import com.tencent.polaris.router.api.core.RouterAPI;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.cloud.client.ConditionalOnBlockingDiscoveryEnabled; import org.springframework.cloud.client.ConditionalOnBlockingDiscoveryEnabled;
import org.springframework.cloud.client.ConditionalOnDiscoveryEnabled; import org.springframework.cloud.client.ConditionalOnDiscoveryEnabled;
import org.springframework.cloud.client.ConditionalOnReactiveDiscoveryEnabled; import org.springframework.cloud.client.ConditionalOnReactiveDiscoveryEnabled;
@ -52,6 +57,13 @@ public class LoadBalancerConfiguration {
*/ */
private static final int REACTIVE_SERVICE_INSTANCE_SUPPLIER_ORDER = 193827465; private static final int REACTIVE_SERVICE_INSTANCE_SUPPLIER_ORDER = 193827465;
@Bean
@ConditionalOnMissingBean
@ConditionalOnClass(PolarisServiceInstance.class)
public InstanceTransformer instanceTransformer() {
return new PolarisInstanceTransformer();
}
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
@ConditionalOnReactiveDiscoveryEnabled @ConditionalOnReactiveDiscoveryEnabled
@Order(REACTIVE_SERVICE_INSTANCE_SUPPLIER_ORDER) @Order(REACTIVE_SERVICE_INSTANCE_SUPPLIER_ORDER)
@ -62,12 +74,13 @@ public class LoadBalancerConfiguration {
public ServiceInstanceListSupplier polarisRouterDiscoveryClientServiceInstanceListSupplier( public ServiceInstanceListSupplier polarisRouterDiscoveryClientServiceInstanceListSupplier(
ConfigurableApplicationContext context, ConfigurableApplicationContext context,
RouterAPI routerAPI, List<RouterRequestInterceptor> requestInterceptors, RouterAPI routerAPI, List<RouterRequestInterceptor> requestInterceptors,
List<RouterResponseInterceptor> responseInterceptors) { List<RouterResponseInterceptor> responseInterceptors, InstanceTransformer instanceTransformer) {
return new PolarisRouterServiceInstanceListSupplier( return new PolarisRouterServiceInstanceListSupplier(
ServiceInstanceListSupplier.builder().withDiscoveryClient().build(context), ServiceInstanceListSupplier.builder().withDiscoveryClient().build(context),
routerAPI, routerAPI,
requestInterceptors, requestInterceptors,
responseInterceptors); responseInterceptors,
instanceTransformer);
} }
} }
@ -82,12 +95,13 @@ public class LoadBalancerConfiguration {
public ServiceInstanceListSupplier polarisRouterDiscoveryClientServiceInstanceListSupplier( public ServiceInstanceListSupplier polarisRouterDiscoveryClientServiceInstanceListSupplier(
ConfigurableApplicationContext context, ConfigurableApplicationContext context,
RouterAPI routerAPI, List<RouterRequestInterceptor> requestInterceptors, RouterAPI routerAPI, List<RouterRequestInterceptor> requestInterceptors,
List<RouterResponseInterceptor> responseInterceptors) { List<RouterResponseInterceptor> responseInterceptors, InstanceTransformer instanceTransformer) {
return new PolarisRouterServiceInstanceListSupplier( return new PolarisRouterServiceInstanceListSupplier(
ServiceInstanceListSupplier.builder().withBlockingDiscoveryClient().build(context), ServiceInstanceListSupplier.builder().withBlockingDiscoveryClient().build(context),
routerAPI, routerAPI,
requestInterceptors, requestInterceptors,
responseInterceptors); responseInterceptors,
instanceTransformer);
} }
} }
} }

@ -0,0 +1,53 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
*/
package com.tencent.cloud.polaris.router.spi;
import com.tencent.cloud.common.metadata.MetadataContext;
import com.tencent.polaris.api.pojo.DefaultInstance;
import com.tencent.polaris.api.pojo.Instance;
import org.springframework.cloud.client.ServiceInstance;
/**
* InstanceTransformer.
*
* @author sean yu
*/
public interface InstanceTransformer {
default Instance transform(ServiceInstance serviceInstance) {
DefaultInstance instance = new DefaultInstance();
transformDefault(instance, serviceInstance);
transformCustom(instance, serviceInstance);
return instance;
}
default void transformDefault(DefaultInstance instance, ServiceInstance serviceInstance) {
instance.setNamespace(MetadataContext.LOCAL_NAMESPACE);
instance.setService(serviceInstance.getServiceId());
instance.setProtocol(serviceInstance.getScheme());
instance.setId(serviceInstance.getInstanceId());
instance.setHost(serviceInstance.getHost());
instance.setPort(serviceInstance.getPort());
instance.setMetadata(serviceInstance.getMetadata());
}
void transformCustom(DefaultInstance instance, ServiceInstance serviceInstance);
}

@ -0,0 +1,45 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
*/
package com.tencent.cloud.polaris.router.transformer;
import com.tencent.cloud.common.pojo.PolarisServiceInstance;
import com.tencent.cloud.polaris.router.spi.InstanceTransformer;
import com.tencent.polaris.api.pojo.DefaultInstance;
import org.springframework.cloud.client.ServiceInstance;
/**
* PolarisInstanceTransformer.
*
* @author sean yu
*/
public class PolarisInstanceTransformer implements InstanceTransformer {
@Override
public void transformCustom(DefaultInstance instance, ServiceInstance serviceInstance) {
if (serviceInstance instanceof PolarisServiceInstance) {
PolarisServiceInstance polarisServiceInstance = (PolarisServiceInstance) serviceInstance;
instance.setRegion(polarisServiceInstance.getPolarisInstance().getRegion());
instance.setZone(polarisServiceInstance.getPolarisInstance().getZone());
instance.setCampus(polarisServiceInstance.getPolarisInstance().getCampus());
instance.setWeight(polarisServiceInstance.getPolarisInstance().getWeight());
}
}
}

@ -41,6 +41,7 @@ import com.tencent.cloud.polaris.router.interceptor.RuleBasedRouterRequestInterc
import com.tencent.cloud.polaris.router.resttemplate.PolarisLoadBalancerRequest; import com.tencent.cloud.polaris.router.resttemplate.PolarisLoadBalancerRequest;
import com.tencent.cloud.polaris.router.spi.RouterRequestInterceptor; import com.tencent.cloud.polaris.router.spi.RouterRequestInterceptor;
import com.tencent.cloud.polaris.router.spi.RouterResponseInterceptor; import com.tencent.cloud.polaris.router.spi.RouterResponseInterceptor;
import com.tencent.cloud.polaris.router.transformer.PolarisInstanceTransformer;
import com.tencent.polaris.api.exception.PolarisException; import com.tencent.polaris.api.exception.PolarisException;
import com.tencent.polaris.api.pojo.DefaultInstance; import com.tencent.polaris.api.pojo.DefaultInstance;
import com.tencent.polaris.api.pojo.DefaultServiceInstances; import com.tencent.polaris.api.pojo.DefaultServiceInstances;
@ -120,7 +121,7 @@ public class PolarisRouterServiceInstanceListSupplierTest {
setTransitiveMetadata(); setTransitiveMetadata();
PolarisRouterServiceInstanceListSupplier polarisSupplier = new PolarisRouterServiceInstanceListSupplier( PolarisRouterServiceInstanceListSupplier polarisSupplier = new PolarisRouterServiceInstanceListSupplier(
delegate, routerAPI, requestInterceptors, null); delegate, routerAPI, requestInterceptors, null, new PolarisInstanceTransformer());
ServiceInstances serviceInstances = assembleServiceInstances(); ServiceInstances serviceInstances = assembleServiceInstances();
PolarisRouterContext routerContext = assembleRouterContext(); PolarisRouterContext routerContext = assembleRouterContext();
@ -157,7 +158,7 @@ public class PolarisRouterServiceInstanceListSupplierTest {
setTransitiveMetadata(); setTransitiveMetadata();
PolarisRouterServiceInstanceListSupplier polarisSupplier = new PolarisRouterServiceInstanceListSupplier( PolarisRouterServiceInstanceListSupplier polarisSupplier = new PolarisRouterServiceInstanceListSupplier(
delegate, routerAPI, requestInterceptors, null); delegate, routerAPI, requestInterceptors, null, new PolarisInstanceTransformer());
ServiceInstances serviceInstances = assembleServiceInstances(); ServiceInstances serviceInstances = assembleServiceInstances();
PolarisRouterContext routerContext = assembleRouterContext(); PolarisRouterContext routerContext = assembleRouterContext();
@ -195,7 +196,7 @@ public class PolarisRouterServiceInstanceListSupplierTest {
setTransitiveMetadata(); setTransitiveMetadata();
PolarisRouterServiceInstanceListSupplier polarisSupplier = new PolarisRouterServiceInstanceListSupplier( PolarisRouterServiceInstanceListSupplier polarisSupplier = new PolarisRouterServiceInstanceListSupplier(
delegate, routerAPI, requestInterceptors, null); delegate, routerAPI, requestInterceptors, null, new PolarisInstanceTransformer());
ServiceInstances serviceInstances = assembleServiceInstances(); ServiceInstances serviceInstances = assembleServiceInstances();
PolarisRouterContext routerContext = assembleRouterContext(); PolarisRouterContext routerContext = assembleRouterContext();
@ -222,7 +223,7 @@ public class PolarisRouterServiceInstanceListSupplierTest {
setTransitiveMetadata(); setTransitiveMetadata();
PolarisRouterServiceInstanceListSupplier polarisSupplier = new PolarisRouterServiceInstanceListSupplier( PolarisRouterServiceInstanceListSupplier polarisSupplier = new PolarisRouterServiceInstanceListSupplier(
delegate, routerAPI, requestInterceptors, Collections.singletonList(new TestRouterResponseInterceptor())); delegate, routerAPI, requestInterceptors, Collections.singletonList(new TestRouterResponseInterceptor()), new PolarisInstanceTransformer());
ProcessRoutersResponse assembleResponse = assembleProcessRoutersResponse(); ProcessRoutersResponse assembleResponse = assembleProcessRoutersResponse();
when(routerAPI.processRouters(any())).thenReturn(assembleResponse); when(routerAPI.processRouters(any())).thenReturn(assembleResponse);
@ -237,7 +238,7 @@ public class PolarisRouterServiceInstanceListSupplierTest {
@Test @Test
public void buildRouterContext() { public void buildRouterContext() {
PolarisRouterServiceInstanceListSupplier polarisSupplier = new PolarisRouterServiceInstanceListSupplier( PolarisRouterServiceInstanceListSupplier polarisSupplier = new PolarisRouterServiceInstanceListSupplier(
delegate, routerAPI, requestInterceptors, null); delegate, routerAPI, requestInterceptors, null, new PolarisInstanceTransformer());
HttpHeaders headers = new HttpHeaders(); HttpHeaders headers = new HttpHeaders();
PolarisRouterContext context = polarisSupplier.buildRouterContext(headers); PolarisRouterContext context = polarisSupplier.buildRouterContext(headers);
@ -259,7 +260,7 @@ public class PolarisRouterServiceInstanceListSupplierTest {
@Test @Test
public void testGet01() { public void testGet01() {
PolarisRouterServiceInstanceListSupplier polarisSupplier = new PolarisRouterServiceInstanceListSupplier( PolarisRouterServiceInstanceListSupplier polarisSupplier = new PolarisRouterServiceInstanceListSupplier(
delegate, routerAPI, requestInterceptors, null); delegate, routerAPI, requestInterceptors, null, new PolarisInstanceTransformer());
assertThatThrownBy(() -> polarisSupplier.get()).isInstanceOf(PolarisException.class); assertThatThrownBy(() -> polarisSupplier.get()).isInstanceOf(PolarisException.class);
} }
@ -270,7 +271,7 @@ public class PolarisRouterServiceInstanceListSupplierTest {
.thenReturn(testCallerService); .thenReturn(testCallerService);
PolarisRouterServiceInstanceListSupplier polarisSupplier = new PolarisRouterServiceInstanceListSupplier( PolarisRouterServiceInstanceListSupplier polarisSupplier = new PolarisRouterServiceInstanceListSupplier(
delegate, routerAPI, requestInterceptors, null); delegate, routerAPI, requestInterceptors, null, new PolarisInstanceTransformer());
MockServerHttpRequest httpRequest = MockServerHttpRequest.get("/" + testCalleeService + "/users") MockServerHttpRequest httpRequest = MockServerHttpRequest.get("/" + testCalleeService + "/users")
.header("k1", "v1") .header("k1", "v1")
@ -294,7 +295,7 @@ public class PolarisRouterServiceInstanceListSupplierTest {
.thenReturn(new ProcessRoutersResponse(new DefaultServiceInstances(null, new ArrayList<>()))); .thenReturn(new ProcessRoutersResponse(new DefaultServiceInstances(null, new ArrayList<>())));
PolarisRouterServiceInstanceListSupplier polarisSupplier = new PolarisRouterServiceInstanceListSupplier( PolarisRouterServiceInstanceListSupplier polarisSupplier = new PolarisRouterServiceInstanceListSupplier(
delegate, routerAPI, requestInterceptors, null); delegate, routerAPI, requestInterceptors, null, new PolarisInstanceTransformer());
MockServerHttpRequest httpRequest = MockServerHttpRequest.get("/" + testCalleeService + "/users") MockServerHttpRequest httpRequest = MockServerHttpRequest.get("/" + testCalleeService + "/users")
.header("k1", "v1") .header("k1", "v1")

@ -24,6 +24,7 @@ import com.tencent.cloud.common.metadata.MetadataContext;
import com.tencent.cloud.common.metadata.MetadataContextHolder; import com.tencent.cloud.common.metadata.MetadataContextHolder;
import com.tencent.cloud.common.pojo.PolarisServiceInstance; import com.tencent.cloud.common.pojo.PolarisServiceInstance;
import com.tencent.cloud.common.util.ApplicationContextAwareUtils; import com.tencent.cloud.common.util.ApplicationContextAwareUtils;
import com.tencent.cloud.polaris.router.transformer.PolarisInstanceTransformer;
import com.tencent.polaris.api.pojo.DefaultInstance; import com.tencent.polaris.api.pojo.DefaultInstance;
import com.tencent.polaris.api.pojo.Instance; import com.tencent.polaris.api.pojo.Instance;
import com.tencent.polaris.api.pojo.ServiceInstances; import com.tencent.polaris.api.pojo.ServiceInstances;
@ -52,7 +53,7 @@ public class RouterUtilsTest {
@Test @Test
public void testTransferEmptyInstances() { public void testTransferEmptyInstances() {
ServiceInstances serviceInstances = RouterUtils.transferServersToServiceInstances(Flux.empty()); ServiceInstances serviceInstances = RouterUtils.transferServersToServiceInstances(Flux.empty(), new PolarisInstanceTransformer());
assertThat(serviceInstances.getInstances()).isNotNull(); assertThat(serviceInstances.getInstances()).isNotNull();
assertThat(serviceInstances.getInstances()).isEmpty(); assertThat(serviceInstances.getInstances()).isEmpty();
} }
@ -82,7 +83,7 @@ public class RouterUtilsTest {
instances.add(new PolarisServiceInstance(instance)); instances.add(new PolarisServiceInstance(instance));
} }
ServiceInstances serviceInstances = RouterUtils.transferServersToServiceInstances(Flux.just(instances)); ServiceInstances serviceInstances = RouterUtils.transferServersToServiceInstances(Flux.just(instances), new PolarisInstanceTransformer());
assertThat(serviceInstances.getInstances()).isNotNull(); assertThat(serviceInstances.getInstances()).isNotNull();
assertThat(serviceInstances.getInstances().size()).isEqualTo(instanceSize); assertThat(serviceInstances.getInstances().size()).isEqualTo(instanceSize);

@ -20,6 +20,7 @@ package com.tencent.cloud.polaris.router.config;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration; import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import com.tencent.cloud.polaris.router.PolarisRouterServiceInstanceListSupplier; import com.tencent.cloud.polaris.router.PolarisRouterServiceInstanceListSupplier;
import com.tencent.cloud.polaris.router.transformer.PolarisInstanceTransformer;
import com.tencent.polaris.router.api.core.RouterAPI; import com.tencent.polaris.router.api.core.RouterAPI;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@ -59,6 +60,7 @@ public class LoadBalancerConfigurationTest {
PolarisContextAutoConfiguration.class)) PolarisContextAutoConfiguration.class))
.withBean(SimpleReactiveDiscoveryProperties.class) .withBean(SimpleReactiveDiscoveryProperties.class)
.withBean(SimpleReactiveDiscoveryClient.class) .withBean(SimpleReactiveDiscoveryClient.class)
.withBean(PolarisInstanceTransformer.class)
.run(context -> { .run(context -> {
assertThat(context).hasSingleBean(LoadBalancerConfiguration.PolarisReactiveSupportConfiguration.class); assertThat(context).hasSingleBean(LoadBalancerConfiguration.PolarisReactiveSupportConfiguration.class);
assertThat(context).hasSingleBean(RouterAPI.class); assertThat(context).hasSingleBean(RouterAPI.class);
@ -75,6 +77,7 @@ public class LoadBalancerConfigurationTest {
)) ))
.withBean(SimpleDiscoveryProperties.class) .withBean(SimpleDiscoveryProperties.class)
.withBean(SimpleDiscoveryClient.class) .withBean(SimpleDiscoveryClient.class)
.withBean(PolarisInstanceTransformer.class)
.run(context -> { .run(context -> {
assertThat(context).hasSingleBean(LoadBalancerConfiguration.PolarisBlockingSupportConfiguration.class); assertThat(context).hasSingleBean(LoadBalancerConfiguration.PolarisBlockingSupportConfiguration.class);
assertThat(context).hasSingleBean(DiscoveryClient.class); assertThat(context).hasSingleBean(DiscoveryClient.class);

@ -0,0 +1,60 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
*/
package com.tencent.cloud.polaris.router.transformer;
import com.tencent.cloud.common.pojo.PolarisServiceInstance;
import com.tencent.cloud.common.util.ApplicationContextAwareUtils;
import com.tencent.polaris.api.pojo.DefaultInstance;
import com.tencent.polaris.api.pojo.Instance;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import static org.assertj.core.api.Assertions.assertThat;
/**
* PolarisInstanceTransformerTest.
*
* @author sean yu
*/
public class PolarisInstanceTransformerTest {
private static MockedStatic<ApplicationContextAwareUtils> mockedApplicationContextAwareUtils;
@BeforeAll
public static void beforeAll() {
mockedApplicationContextAwareUtils = Mockito.mockStatic(ApplicationContextAwareUtils.class);
mockedApplicationContextAwareUtils.when(() -> ApplicationContextAwareUtils.getProperties("spring.cloud.polaris.namespace"))
.thenReturn("default");
mockedApplicationContextAwareUtils.when(() -> ApplicationContextAwareUtils.getProperties("spring.cloud.polaris.service"))
.thenReturn("test");
}
@Test
public void test() {
PolarisInstanceTransformer polarisInstanceTransformer = new PolarisInstanceTransformer();
DefaultInstance instance = new DefaultInstance();
instance.setZone("zone");
PolarisServiceInstance polarisServiceInstance = new PolarisServiceInstance(instance);
Instance instance1 = polarisInstanceTransformer.transform(polarisServiceInstance);
assertThat(instance1.getZone()).isEqualTo("zone");
}
}

@ -64,6 +64,12 @@
<artifactId>spring-cloud-starter-tencent-polaris-config</artifactId> <artifactId>spring-cloud-starter-tencent-polaris-config</artifactId>
</dependency> </dependency>
<dependency>
<groupId>com.tencent.cloud</groupId>
<artifactId>spring-cloud-starter-tencent-discovery-adapter-plugin</artifactId>
<version>${revision}</version>
</dependency>
<dependency> <dependency>
<groupId>com.tencent.cloud</groupId> <groupId>com.tencent.cloud</groupId>
<artifactId>spring-cloud-tencent-featureenv-plugin</artifactId> <artifactId>spring-cloud-tencent-featureenv-plugin</artifactId>

@ -70,10 +70,10 @@
</developers> </developers>
<properties> <properties>
<revision>1.11.0-2020.0.6-SNAPSHOT</revision> <revision>1.10.3-2020.0.6</revision>
<!-- Dependencies --> <!-- Dependencies -->
<polaris.version>1.11.3-SNAPSHOT</polaris.version> <polaris.version>1.11.3</polaris.version>
<guava.version>31.0.1-jre</guava.version> <guava.version>31.0.1-jre</guava.version>
<logback.version>1.2.11</logback.version> <logback.version>1.2.11</logback.version>
<mocktio.version>4.5.1</mocktio.version> <mocktio.version>4.5.1</mocktio.version>
@ -162,6 +162,12 @@
</dependency> </dependency>
<!-- spring cloud tencent plugins --> <!-- spring cloud tencent plugins -->
<dependency>
<groupId>com.tencent.cloud</groupId>
<artifactId>spring-cloud-starter-tencent-discovery-adapter-plugin</artifactId>
<version>${revision}</version>
</dependency>
<dependency> <dependency>
<groupId>com.tencent.cloud</groupId> <groupId>com.tencent.cloud</groupId>
<artifactId>spring-cloud-tencent-featureenv-plugin</artifactId> <artifactId>spring-cloud-tencent-featureenv-plugin</artifactId>
@ -263,6 +269,7 @@
<version>${system-stubs-jupiter.version}</version> <version>${system-stubs-jupiter.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
</dependencies> </dependencies>
</dependencyManagement> </dependencyManagement>

@ -0,0 +1,61 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>multiple-discovery-nacos-example</artifactId>
<groupId>com.tencent.cloud</groupId>
<version>${revision}</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>nacos-callee-service-a</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
<version>2021.1</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,34 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.tencent.cloud.multiple.discovery.nacos;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Circuit breaker example callee application.
*
* @author Haotian Zhang
*/
@SpringBootApplication
public class NacosCalleeServiceA {
public static void main(String[] args) {
SpringApplication.run(NacosCalleeServiceA.class, args);
}
}

@ -0,0 +1,50 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
*/
package com.tencent.cloud.multiple.discovery.nacos;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Service B Controller.
*
* @author Haotian Zhang
*/
@RestController
@RequestMapping("/example/service/b")
public class NacosCalleeServiceAController {
/**
* Get service information.
*
* @return service information
*/
@GetMapping("/info")
public String info() {
return "hello world ! I'm a service B1";
}
@GetMapping("/health")
public String health() {
System.out.println("health check: 200 instance");
return "hello world ! I'm a service B1";
}
}

@ -0,0 +1,16 @@
server:
port: 48082
spring:
application:
name: NacosCalleeService
cloud:
polaris:
address: grpc://183.47.111.80:8091
namespace: default
enabled: true
stat:
enabled: true
port: 28083
nacos:
discovery:
server-addr: 127.0.0.1:8848

@ -0,0 +1,62 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>multiple-discovery-nacos-example</artifactId>
<groupId>com.tencent.cloud</groupId>
<version>${revision}</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>nacos-callee-service-b</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
<version>2021.1</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,34 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.tencent.cloud.multiple.discovery.nacos;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Circuit breaker example callee application.
*
* @author Haotian Zhang
*/
@SpringBootApplication
public class NacosCalleeServiceB {
public static void main(String[] args) {
SpringApplication.run(NacosCalleeServiceB.class, args);
}
}

@ -0,0 +1,54 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
*/
package com.tencent.cloud.multiple.discovery.nacos;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
/**
* Service B Controller.
*
* @author Haotian Zhang
*/
@RestController
@RequestMapping("/example/service/b")
public class NacosCalleeServiceBController {
/**
* Get service information.
*
* @return service information
*/
@GetMapping("/info")
@ResponseStatus(code = HttpStatus.BAD_GATEWAY)
public String info() {
return "BAD_GATEWAY ! from service B2";
}
@GetMapping("/health")
@ResponseStatus(value = HttpStatus.BAD_GATEWAY, reason = "failed for call my service")
public String health() {
System.out.println("health check: 502 instance");
return "hello world ! I'm a service B1";
}
}

@ -0,0 +1,17 @@
server:
port: 48081
spring:
application:
name: NacosCalleeService
cloud:
polaris:
address: grpc://183.47.111.80:8091
namespace: default
enabled: true
stat:
enabled: true
port: 28083
nacos:
discovery:
server-addr: 127.0.0.1:8848

@ -0,0 +1,86 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>multiple-discovery-nacos-example</artifactId>
<groupId>com.tencent.cloud</groupId>
<version>${revision}</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>nacos-discovery-caller</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
<version>2021.1</version>
</dependency>
<dependency>
<groupId>com.tencent.cloud</groupId>
<artifactId>spring-cloud-starter-tencent-polaris-router</artifactId>
</dependency>
<dependency>
<groupId>com.tencent.cloud</groupId>
<artifactId>spring-cloud-starter-tencent-discovery-adapter-plugin</artifactId>
</dependency>
<dependency>
<groupId>com.tencent.cloud</groupId>
<artifactId>spring-cloud-starter-tencent-polaris-circuitbreaker</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,36 @@
/*
* 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.multiple.discovery.nacos;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
/**
* Circuit breaker example callee application.
*
* @author Haotian Zhang
*/
@SpringBootApplication
@EnableFeignClients
public class NacosCallerService {
public static void main(String[] args) {
SpringApplication.run(NacosCallerService.class, args);
}
}

@ -0,0 +1,42 @@
/*
* 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.multiple.discovery.nacos;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* NacosCallerServiceController.
*
* @author sean yu
*/
@RestController
@RequestMapping("/example/service/a")
public class NacosCallerServiceController {
@Autowired
private ProviderB polarisServiceB;
@GetMapping("/getBServiceInfo")
public String getBServiceInfoFallbackFromCode() {
return polarisServiceB.info();
}
}

@ -0,0 +1,38 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.tencent.cloud.multiple.discovery.nacos;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
/**
* Circuit breaker example callee provider.
*
* @author sean yu
*/
@FeignClient(name = "NacosCalleeService")
public interface ProviderB {
/**
* Get info of service B.
*
* @return info of service B
*/
@GetMapping("/example/service/b/info")
String info();
}

@ -0,0 +1,26 @@
server:
port: 48080
spring:
application:
name: NacosCallerService
cloud:
polaris:
address: grpc://183.47.111.80:8091
namespace: default
enabled: true
loadbalancer:
enabled: true
circuitbreaker:
enabled: true
nacos:
discovery:
server-addr: 127.0.0.1:8848
feign:
circuitbreaker:
enabled: true
logging:
level:
root: info
com.tencent.cloud: debug

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>multiple-discovery-example</artifactId>
<groupId>com.tencent.cloud</groupId>
<version>${revision}</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>multiple-discovery-nacos-example</artifactId>
<packaging>pom</packaging>
<modules>
<module>nacos-callee-service-a</module>
<module>nacos-callee-service-b</module>
<module>nacos-discovery-caller</module>
</modules>
</project>

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>spring-cloud-tencent-examples</artifactId>
<groupId>com.tencent.cloud</groupId>
<version>${revision}</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>multiple-discovery-example</artifactId>
<name>Spring Cloud Starter Tencent Multiple Discovery Example</name>
<packaging>pom</packaging>
<modules>
<module>multiple-discovery-nacos-example</module>
</modules>
</project>

@ -12,25 +12,10 @@ spring:
enabled: true enabled: true
circuitbreaker: circuitbreaker:
enabled: true enabled: true
# stat:
# enabled: true
# port: 28081
# tencent:
# rpc-enhancement:
# enabled: true
# reporter:
# ignore-internal-server-error: true
# series: server_error
# statuses: gateway_timeout, bad_gateway, service_unavailable
feign: feign:
circuitbreaker: circuitbreaker:
enabled: true enabled: true
# compression:
# request:
# enabled: false
# mime-types: text/xml,application/xml,application/json
# min-request-size: 2048
logging: logging:
level: level:

@ -12,16 +12,6 @@ spring:
enabled: true enabled: true
circuitbreaker: circuitbreaker:
enabled: true enabled: true
# stat:
# enabled: true
# port: 28081
# tencent:
# rpc-enhancement:
# enabled: true
# reporter:
# ignore-internal-server-error: true
# series: server_error
# statuses: gateway_timeout, bad_gateway, service_unavailable
logging: logging:
level: level:

@ -12,16 +12,6 @@ spring:
enabled: true enabled: true
circuitbreaker: circuitbreaker:
enabled: true enabled: true
# stat:
# enabled: true
# port: 28081
# tencent:
# rpc-enhancement:
# enabled: true
# reporter:
# ignore-internal-server-error: true
# series: server_error
# statuses: gateway_timeout, bad_gateway, service_unavailable
logging: logging:
level: level:

@ -16,6 +16,7 @@
<description>Examples of Spring Cloud Tencent</description> <description>Examples of Spring Cloud Tencent</description>
<modules> <modules>
<module>multiple-discovery-example</module>
<module>polaris-discovery-example</module> <module>polaris-discovery-example</module>
<module>polaris-ratelimit-example</module> <module>polaris-ratelimit-example</module>
<module>polaris-circuitbreaker-example</module> <module>polaris-circuitbreaker-example</module>

@ -17,6 +17,7 @@
<modules> <modules>
<module>spring-cloud-tencent-featureenv-plugin</module> <module>spring-cloud-tencent-featureenv-plugin</module>
<module>spring-cloud-tencent-gateway-plugin</module> <module>spring-cloud-tencent-gateway-plugin</module>
<module>spring-cloud-starter-tencent-discovery-adapter-plugin</module>
</modules> </modules>
</project> </project>

@ -0,0 +1,42 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>spring-cloud-tencent-plugin-starters</artifactId>
<groupId>com.tencent.cloud</groupId>
<version>${revision}</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-cloud-starter-tencent-discovery-adapter-plugin</artifactId>
<name>Spring Cloud Starter Tencent Discovery Adapter Plugin</name>
<dependencies>
<dependency>
<groupId>com.tencent.cloud</groupId>
<artifactId>spring-cloud-starter-tencent-polaris-router</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
<version>2021.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-inline</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

@ -0,0 +1,52 @@
/*
* 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.discovery.adapter.config;
import com.tencent.cloud.plugin.discovery.adapter.transformer.NacosInstanceTransformer;
import com.tencent.cloud.polaris.router.config.ConditionalOnPolarisRouterEnabled;
import com.tencent.cloud.polaris.router.config.LoadBalancerConfiguration;
import com.tencent.cloud.polaris.router.spi.InstanceTransformer;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.cloud.client.ConditionalOnDiscoveryEnabled;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* NacosDiscoveryAdapterAutoConfiguration.
*
* @author sean yu
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnDiscoveryEnabled
@AutoConfigureBefore(LoadBalancerConfiguration.class)
public class NacosDiscoveryAdapterAutoConfiguration {
@Bean
@ConditionalOnMissingBean
@ConditionalOnPolarisRouterEnabled
@ConditionalOnClass(name = "com.alibaba.cloud.nacos.NacosServiceInstance")
public InstanceTransformer instanceTransformer() {
return new NacosInstanceTransformer();
}
}

@ -0,0 +1,50 @@
/*
* Tencent is pleased to support the open source community by making Spring Cloud Tencent available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
*/
package com.tencent.cloud.plugin.discovery.adapter.transformer;
import com.tencent.cloud.polaris.router.spi.InstanceTransformer;
import com.tencent.polaris.api.pojo.DefaultInstance;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.client.ServiceInstance;
/**
* NacosInstanceTransformer.
*
* @author sean yu
*/
public class NacosInstanceTransformer implements InstanceTransformer {
@Override
public void transformCustom(DefaultInstance instance, ServiceInstance serviceInstance) {
if ("com.alibaba.cloud.nacos.NacosServiceInstance".equals(serviceInstance.getClass().getName())) {
String nacosWeight = serviceInstance.getMetadata().get("nacos.weight");
instance.setWeight(
StringUtils.isBlank(nacosWeight) ? 100 : (int) Double.parseDouble(nacosWeight) * 100
);
String nacosHealthy = serviceInstance.getMetadata().get("nacos.healthy");
instance.setHealthy(
!StringUtils.isBlank(nacosHealthy) && Boolean.parseBoolean(nacosHealthy)
);
String nacosInstanceId = serviceInstance.getMetadata().get("nacos.instanceId");
instance.setId(nacosInstanceId);
}
}
}

@ -0,0 +1,2 @@
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.tencent.cloud.plugin.discovery.adapter.config.NacosDiscoveryAdapterAutoConfiguration

@ -0,0 +1,51 @@
/*
* 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.discovery.adapter.config;
import com.tencent.cloud.plugin.discovery.adapter.transformer.NacosInstanceTransformer;
import com.tencent.cloud.polaris.router.transformer.PolarisInstanceTransformer;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.cloud.client.loadbalancer.LoadBalancerAutoConfiguration;
import static org.assertj.core.api.Assertions.assertThat;
/**
* NacosDiscoveryAdapterAutoConfigurationTest.
*
* @author sean yu
*/
public class NacosDiscoveryAdapterAutoConfigurationTest {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(
NacosDiscoveryAdapterAutoConfiguration.class,
LoadBalancerAutoConfiguration.class
));
@Test
public void testDefaultInitialization() {
this.contextRunner.run(context -> {
assertThat(context).hasSingleBean(NacosInstanceTransformer.class);
assertThat(context).doesNotHaveBean(PolarisInstanceTransformer.class);
});
}
}

@ -0,0 +1,66 @@
/*
* 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.discovery.adapter.config;
import java.util.HashMap;
import com.alibaba.cloud.nacos.NacosServiceInstance;
import com.tencent.cloud.common.util.ApplicationContextAwareUtils;
import com.tencent.cloud.plugin.discovery.adapter.transformer.NacosInstanceTransformer;
import com.tencent.polaris.api.pojo.Instance;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import static org.assertj.core.api.Assertions.assertThat;
/**
* NacosInstanceTransformerTest.
*
* @author sean yu
*/
public class NacosInstanceTransformerTest {
private static MockedStatic<ApplicationContextAwareUtils> mockedApplicationContextAwareUtils;
@BeforeAll
public static void beforeAll() {
mockedApplicationContextAwareUtils = Mockito.mockStatic(ApplicationContextAwareUtils.class);
mockedApplicationContextAwareUtils.when(() -> ApplicationContextAwareUtils.getProperties("spring.cloud.polaris.namespace"))
.thenReturn("default");
mockedApplicationContextAwareUtils.when(() -> ApplicationContextAwareUtils.getProperties("spring.cloud.polaris.service"))
.thenReturn("test");
}
@Test
public void test() {
NacosInstanceTransformer nacosInstanceTransformer = new NacosInstanceTransformer();
NacosServiceInstance nacosServiceInstance = new NacosServiceInstance();
nacosServiceInstance.setMetadata(new HashMap<String, String>() {{
put("nacos.weight", "0.01");
put("nacos.healthy", "true");
put("nacos.instanceId", "xxx");
}});
Instance instance = nacosInstanceTransformer.transform(nacosServiceInstance);
assertThat(instance.isHealthy()).isEqualTo(true);
}
}

@ -72,6 +72,11 @@ public final class ReporterUtils {
resultRequest.setRetCode(response.status()); resultRequest.setRetCode(response.status());
resultRequest.setRetStatus(retStatus); resultRequest.setRetStatus(retStatus);
resultRequest.setDelay(delay); resultRequest.setDelay(delay);
String scheme = uri.getScheme();
if (StringUtils.isBlank(scheme)) {
scheme = "http";
}
resultRequest.setProtocol(scheme);
String sourceNamespace = MetadataContext.LOCAL_NAMESPACE; String sourceNamespace = MetadataContext.LOCAL_NAMESPACE;
String sourceService = MetadataContext.LOCAL_SERVICE; String sourceService = MetadataContext.LOCAL_SERVICE;
if (StringUtils.isNotBlank(sourceNamespace) && StringUtils.isNotBlank(sourceService)) { if (StringUtils.isNotBlank(sourceNamespace) && StringUtils.isNotBlank(sourceService)) {

Loading…
Cancel
Save