feat: support service registry and discovery with Polaris and Nacos (#1724)

pull/1727/head
Fishtail 2 days ago committed by GitHub
parent fa5d3ac2b5
commit 7808ebb62e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -24,4 +24,5 @@
- [feat: support config ratelimit addresses and remote task interval.](https://github.com/Tencent/spring-cloud-tencent/pull/1695)
- [docs:optimize tsf example.](https://github.com/Tencent/spring-cloud-tencent/pull/1711)
- [feat:support TSF certificate manager.](https://github.com/Tencent/spring-cloud-tencent/pull/1716)
- [feat:support tsf unit.](https://github.com/Tencent/spring-cloud-tencent/pull/1722)
- [feat:support tsf unit.](https://github.com/Tencent/spring-cloud-tencent/pull/1722)
- [feat: support service registry and discovery with Polaris and Nacos](https://github.com/Tencent/spring-cloud-tencent/pull/1724)

@ -26,13 +26,6 @@
</dependency>
<!-- Spring Cloud Tencent dependencies end -->
<!-- Polaris dependencies start -->
<dependency>
<groupId>com.tencent.polaris</groupId>
<artifactId>connector-nacos</artifactId>
<scope>test</scope>
</dependency>
<!-- Polaris dependencies end -->
<dependency>
<groupId>org.springframework.cloud</groupId>

@ -23,7 +23,6 @@ import java.util.List;
import java.util.stream.Collectors;
import com.tencent.cloud.common.pojo.PolarisServiceInstance;
import com.tencent.cloud.common.util.DiscoveryUtil;
import com.tencent.polaris.api.exception.PolarisException;
import com.tencent.polaris.api.pojo.Instance;
import com.tencent.polaris.api.pojo.ServiceInfo;
@ -51,7 +50,6 @@ public class PolarisServiceDiscovery {
* @throws PolarisException polarisException
*/
public List<ServiceInstance> getInstances(String serviceId) throws PolarisException {
serviceId = DiscoveryUtil.rewriteServiceId(serviceId);
List<ServiceInstance> instances = new ArrayList<>();
InstancesResponse filteredInstances = polarisDiscoveryHandler.getHealthyInstances(serviceId);
ServiceInstances serviceInstances = filteredInstances.toServiceInstances();

@ -34,6 +34,15 @@ import com.tencent.polaris.factory.config.provider.RegisterConfigImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.tencent.polaris.plugins.connector.common.constant.NacosConstant.MetadataMapKey.NACOS_CLUSTER_KEY;
import static com.tencent.polaris.plugins.connector.common.constant.NacosConstant.MetadataMapKey.NACOS_EPHEMERAL_KEY;
import static com.tencent.polaris.plugins.connector.common.constant.NacosConstant.MetadataMapKey.NACOS_GROUP_KEY;
import static com.tencent.polaris.plugins.connector.common.constant.NacosConstant.MetadataMapKey.NACOS_SERVICE_KEY;
import static com.tencent.polaris.plugins.connector.common.constant.NacosConstant.MetadataMapKey.NACOS_WEIGHT_KEY;
import static shade.polaris.com.alibaba.nacos.api.PropertyKeyConst.CONTEXT_PATH;
import static shade.polaris.com.alibaba.nacos.api.PropertyKeyConst.NAMESPACE;
import static shade.polaris.com.alibaba.nacos.api.PropertyKeyConst.PASSWORD;
import static shade.polaris.com.alibaba.nacos.api.PropertyKeyConst.USERNAME;
/**
* {@link PolarisConfigModifier} impl of Nacos.
@ -42,26 +51,7 @@ import org.slf4j.LoggerFactory;
*/
public class NacosConfigModifier implements PolarisConfigModifier {
/**
* nacos username.
*/
public static final String USERNAME = "username";
/**
* nacos password.
*/
public static final String PASSWORD = "password";
/**
* nacos contextPath.
*/
public static final String CONTEXT_PATH = "contextPath";
/**
* nacos namespace.
*/
public static final String NAMESPACE = "namespace";
/**
* nacos group.
*/
public static final String GROUP = "group";
private static final Logger LOGGER = LoggerFactory.getLogger(NacosConfigModifier.class);
private static final String ID = "nacos";
private final NacosContextProperties nacosContextProperties;
@ -72,26 +62,9 @@ public class NacosConfigModifier implements PolarisConfigModifier {
@Override
public void modify(ConfigurationImpl configuration) {
if (Objects.isNull(nacosContextProperties) || !nacosContextProperties.isEnabled()) {
if (Objects.isNull(nacosContextProperties) || !nacosContextProperties.isDiscoveryEnabled()) {
return;
}
// Check if Nacos Available
boolean nacosAvailable = false;
try {
nacosAvailable = null != Class.forName("com.alibaba.nacos.api.naming.NamingService");
}
catch (Throwable ignored) {
}
if (!nacosAvailable) {
LOGGER.error("Please import \"connector-nacos\" dependency when enabling nacos service registration and discovery.\n"
+ "Add dependency configuration below to pom.xml:\n"
+ "<dependency>\n"
+ "\t<groupId>com.tencent.polaris</groupId>\n"
+ "\t<artifactId>connector-nacos</artifactId>\n"
+ "</dependency>");
throw new RuntimeException("Dependency \"connector-nacos\" not found.");
}
if (CollectionUtils.isEmpty(configuration.getGlobal().getServerConnectors())) {
configuration.getGlobal().setServerConnectors(new ArrayList<>());
}
@ -127,9 +100,16 @@ public class NacosConfigModifier implements PolarisConfigModifier {
}
if (StringUtils.isNotBlank(nacosContextProperties.getGroup())) {
metadata.put(GROUP, nacosContextProperties.getGroup());
metadata.put(NACOS_GROUP_KEY, nacosContextProperties.getGroup());
}
if (StringUtils.isNotBlank(nacosContextProperties.getClusterName())) {
metadata.put(NACOS_CLUSTER_KEY, nacosContextProperties.getClusterName());
}
if (StringUtils.isNotBlank(nacosContextProperties.getServiceName())) {
metadata.put(NACOS_SERVICE_KEY, nacosContextProperties.getServiceName());
}
metadata.put(NACOS_EPHEMERAL_KEY, String.valueOf(nacosContextProperties.isEphemeral()));
metadata.put(NACOS_WEIGHT_KEY, String.valueOf(nacosContextProperties.getWeight()));
configuration.getGlobal().getServerConnectors().add(serverConnectorConfig);
DiscoveryConfigImpl discoveryConfig = new DiscoveryConfigImpl();
discoveryConfig.setServerConnectorId(ID);

@ -20,6 +20,10 @@ package com.tencent.cloud.polaris.extend.nacos;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import static shade.polaris.com.alibaba.nacos.api.common.Constants.DEFAULT_CLUSTER_NAME;
import static shade.polaris.com.alibaba.nacos.api.common.Constants.DEFAULT_GROUP;
import static shade.polaris.com.alibaba.nacos.api.common.Constants.DEFAULT_NAMESPACE_ID;
/**
* Discovery configuration of Nacos.
*
@ -28,24 +32,7 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties("spring.cloud.nacos")
public class NacosContextProperties {
/**
* Nacos default group name.
*/
public static final String DEFAULT_GROUP = "DEFAULT_GROUP";
/**
* Nacos default cluster name.
*/
public static final String DEFAULT_CLUSTER = "DEFAULT";
/**
* Nacos default namespace name.
*/
public static final String DEFAULT_NAMESPACE = "public";
private boolean enabled = false;
@Value("${spring.cloud.nacos.discovery.enabled:#{'true'}}")
@Value("${spring.cloud.nacos.discovery.enabled:#{'false'}}")
private boolean discoveryEnabled;
/**
@ -60,6 +47,11 @@ public class NacosContextProperties {
*/
@Value("${spring.cloud.nacos.discovery.server-addr:}")
private String serverAddr;
/**
* nacos discovery server address.
*/
@Value("${spring.cloud.nacos.discovery.ephemeral:true}")
private boolean ephemeral;
/**
* the nacos authentication username.
@ -67,6 +59,13 @@ public class NacosContextProperties {
@Value("${spring.cloud.nacos.discovery.username:}")
private String username;
/**
* service name to registry.
*/
@Value("${spring.cloud.nacos.discovery.service:${spring.application.name:}}")
private String serviceName;
/**
* the nacos authentication password.
*/
@ -77,7 +76,7 @@ public class NacosContextProperties {
* cluster name for nacos .
*/
@Value("${spring.cloud.nacos.discovery.cluster-name:DEFAULT}")
private String clusterName = DEFAULT_CLUSTER;
private String clusterName = DEFAULT_CLUSTER_NAME;
/**
* group name for nacos.
@ -86,17 +85,13 @@ public class NacosContextProperties {
private String group = DEFAULT_GROUP;
@Value("${spring.cloud.nacos.discovery.namespace:public}")
private String namespace = DEFAULT_NAMESPACE;
private String namespace = DEFAULT_NAMESPACE_ID;
@Value("${spring.cloud.nacos.discovery.weight:1.0}")
private double weight = 1.0;
private String contextPath;
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public boolean isRegisterEnabled() {
return registerEnabled;
@ -170,19 +165,44 @@ public class NacosContextProperties {
this.namespace = namespace;
}
public boolean isEphemeral() {
return ephemeral;
}
public void setEphemeral(boolean ephemeral) {
this.ephemeral = ephemeral;
}
String getServiceName() {
return serviceName;
}
void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
double getWeight() {
return weight;
}
void setWeight(double weight) {
this.weight = weight;
}
@Override
public String toString() {
return "NacosContextProperties{" +
"enabled=" + enabled +
", discoveryEnabled=" + discoveryEnabled +
"discoveryEnabled=" + discoveryEnabled +
", registerEnabled=" + registerEnabled +
", serverAddr='" + serverAddr + '\'' +
", ephemeral=" + ephemeral +
", username='" + username + '\'' +
", serviceName='" + serviceName + '\'' +
", password='" + password + '\'' +
", clusterName='" + clusterName + '\'' +
", group='" + group + '\'' +
", contextPath='" + contextPath + '\'' +
", namespace='" + namespace + '\'' +
", weight=" + weight +
", contextPath='" + contextPath + '\'' +
'}';
}
}

@ -21,7 +21,6 @@ import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import com.tencent.cloud.common.metadata.StaticMetadataManager;
import com.tencent.cloud.polaris.PolarisDiscoveryProperties;
@ -37,10 +36,6 @@ import org.springframework.boot.web.servlet.context.ServletWebServerApplicationC
import org.springframework.cloud.client.DefaultServiceInstance;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.lang.Nullable;
import static com.tencent.cloud.polaris.extend.nacos.NacosContextProperties.DEFAULT_CLUSTER;
import static com.tencent.cloud.polaris.extend.nacos.NacosContextProperties.DEFAULT_GROUP;
/**
* Registration object of Polaris.
*
@ -48,9 +43,6 @@ import static com.tencent.cloud.polaris.extend.nacos.NacosContextProperties.DEFA
*/
public class PolarisRegistration implements Registration {
private static final String GROUP_SERVER_ID_FORMAT = "%s__%s";
private static final String NACOS_CLUSTER = "nacos.cluster";
private final PolarisDiscoveryProperties polarisDiscoveryProperties;
private final SDKContext polarisContext;
@ -83,20 +75,8 @@ public class PolarisRegistration implements Registration {
this.servletWebServerApplicationContext = servletWebServerApplicationContext;
this.reactiveWebServerApplicationContext = reactiveWebServerApplicationContext;
this.customizers = registrationCustomizers;
this.serviceId = polarisDiscoveryProperties.getService();
// generate serviceId
if (Objects.isNull(nacosContextProperties)) {
serviceId = polarisDiscoveryProperties.getService();
}
else {
String group = nacosContextProperties.getGroup();
if (StringUtils.isNotBlank(group) && !DEFAULT_GROUP.equals(group)) {
serviceId = String.format(GROUP_SERVER_ID_FORMAT, group, polarisDiscoveryProperties.getService());
}
else {
serviceId = polarisDiscoveryProperties.getService();
}
}
// generate host
host = polarisContext.getConfig().getGlobal().getAPI().getBindIP();
@ -112,15 +92,6 @@ public class PolarisRegistration implements Registration {
// generate metadata
if (CollectionUtils.isEmpty(metadata)) {
Map<String, String> instanceMetadata = new HashMap<>();
// put internal-nacos-cluster if necessary
if (Objects.nonNull(nacosContextProperties)) {
String clusterName = nacosContextProperties.getClusterName();
if (StringUtils.isNotBlank(clusterName) && !DEFAULT_CLUSTER.equals(clusterName)) {
instanceMetadata.put(NACOS_CLUSTER, clusterName);
}
}
instanceMetadata.putAll(staticMetadataManager.getMergedStaticMetadata());
this.metadata = instanceMetadata;
@ -135,7 +106,7 @@ public class PolarisRegistration implements Registration {
if (null != consulDiscoveryProperties) {
registerEnabled |= consulDiscoveryProperties.isRegister();
}
if (null != nacosContextProperties && nacosContextProperties.isEnabled()) {
if (null != nacosContextProperties && nacosContextProperties.isDiscoveryEnabled()) {
registerEnabled |= nacosContextProperties.isRegisterEnabled();
}
}

@ -0,0 +1,37 @@
/*
* Tencent is pleased to support the open source community by making spring-cloud-tencent available.
*
* Copyright (C) 2021 Tencent. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.tencent.cloud.polaris.registry.nacos;
import com.tencent.cloud.polaris.extend.nacos.NacosContextProperties;
import com.tencent.cloud.polaris.registry.PolarisServiceRegistryAutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration(proxyBeanMethods = false)
@AutoConfigureBefore(PolarisServiceRegistryAutoConfiguration.class)
public class NacosDiscoveryRegistryAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public NacosPolarisRegistrationCustomizer nacosPolarisRegistrationCustomizer(
NacosContextProperties nacosContextProperties) {
return new NacosPolarisRegistrationCustomizer(nacosContextProperties);
}
}

@ -0,0 +1,54 @@
/*
* Tencent is pleased to support the open source community by making spring-cloud-tencent available.
*
* Copyright (C) 2021 Tencent. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.tencent.cloud.polaris.registry.nacos;
import java.util.Map;
import java.util.Objects;
import com.tencent.cloud.polaris.extend.nacos.NacosContextProperties;
import com.tencent.cloud.polaris.registry.PolarisRegistration;
import com.tencent.cloud.polaris.registry.PolarisRegistrationCustomizer;
import com.tencent.polaris.api.utils.StringUtils;
import static com.tencent.polaris.plugins.connector.common.constant.NacosConstant.MetadataMapKey.NACOS_CLUSTER_KEY;
import static com.tencent.polaris.plugins.connector.common.constant.NacosConstant.MetadataMapKey.NACOS_GROUP_KEY;
import static shade.polaris.com.alibaba.nacos.api.common.Constants.DEFAULT_CLUSTER_NAME;
import static shade.polaris.com.alibaba.nacos.api.common.Constants.DEFAULT_GROUP;
public class NacosPolarisRegistrationCustomizer implements PolarisRegistrationCustomizer {
NacosContextProperties nacosContextProperties;
public NacosPolarisRegistrationCustomizer(NacosContextProperties nacosContextProperties) {
this.nacosContextProperties = nacosContextProperties;
}
@Override
public void customize(PolarisRegistration registration) {
// put internal-nacos-cluster if necessary
Map<String, String> instanceMetadata = registration.getMetadata();
if (Objects.nonNull(nacosContextProperties)) {
String clusterName = nacosContextProperties.getClusterName();
if (StringUtils.isNotBlank(clusterName) && !DEFAULT_CLUSTER_NAME.equals(clusterName)) {
instanceMetadata.put(NACOS_CLUSTER_KEY, clusterName);
}
String groupName = nacosContextProperties.getGroup();
if (StringUtils.isNotBlank(groupName) && !DEFAULT_GROUP.equals(groupName)) {
instanceMetadata.put(NACOS_GROUP_KEY, groupName);
}
}
}
}

@ -114,6 +114,18 @@
"sourceType": "com.tencent.cloud.polaris.extend.nacos.NacosContextProperties",
"defaultValue": false
},
{
"name": "spring.cloud.nacos.discovery.ephemeral",
"type": "java.lang.Boolean",
"sourceType": "com.tencent.cloud.polaris.extend.nacos.NacosContextProperties",
"defaultValue": true
},
{
"name": "spring.cloud.nacos.discovery.weight",
"type": "java.lang.Double",
"sourceType": "com.tencent.cloud.polaris.extend.nacos.NacosContextProperties",
"defaultValue": 1.0
},
{
"name": "spring.cloud.nacos.discovery.group",
"type": "java.lang.String",
@ -134,6 +146,12 @@
"description": "the nacos authentication password.",
"sourceType": "com.tencent.cloud.polaris.extend.nacos.NacosContextProperties"
},
{
"name": "spring.cloud.nacos.discovery.service",
"type": "java.lang.String",
"defaultValue": "${spring.application.name}",
"description": "the service name to register, default value is ${spring.application.name}."
},
{
"name": "spring.cloud.nacos.discovery.register-enabled",
"type": "java.lang.Boolean",
@ -180,7 +198,7 @@
],
"hints": [
{
"name": "spring.cloud.loadbalancer.strategy",
"name": "spring.cloud.loadbalancer.strategies",
"values": [
{
"value": "polarisWeightedRoundRobin",

@ -6,3 +6,4 @@ com.tencent.cloud.polaris.loadbalancer.PolarisLoadBalancerAutoConfiguration
com.tencent.cloud.polaris.loadbalancer.PolarisLoadBalancerPropertiesAutoConfiguration
com.tencent.cloud.polaris.registry.tsf.TsfDiscoveryRegistryAutoConfiguration
com.tencent.cloud.polaris.eager.config.PolarisEagerLoadAutoConfiguration
com.tencent.cloud.polaris.registry.nacos.NacosDiscoveryRegistryAutoConfiguration

@ -34,7 +34,14 @@ import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.util.CollectionUtils;
import static com.tencent.polaris.plugins.connector.common.constant.NacosConstant.MetadataMapKey.NACOS_CLUSTER_KEY;
import static com.tencent.polaris.plugins.connector.common.constant.NacosConstant.MetadataMapKey.NACOS_GROUP_KEY;
import static org.assertj.core.api.Assertions.assertThat;
import static shade.polaris.com.alibaba.nacos.api.PropertyKeyConst.CONTEXT_PATH;
import static shade.polaris.com.alibaba.nacos.api.PropertyKeyConst.NAMESPACE;
import static shade.polaris.com.alibaba.nacos.api.PropertyKeyConst.PASSWORD;
import static shade.polaris.com.alibaba.nacos.api.PropertyKeyConst.USERNAME;
/**
* Test for {@link NacosContextProperties}.
@ -55,7 +62,6 @@ public class NacosContextPropertiesTest {
@Test
public void testDefaultInitialization() {
assertThat(nacosContextProperties).isNotNull();
assertThat(nacosContextProperties.isEnabled()).isTrue();
assertThat(nacosContextProperties.getServerAddr()).isEqualTo("127.0.0.1:8848");
assertThat(nacosContextProperties.isRegisterEnabled()).isTrue();
assertThat(nacosContextProperties.isDiscoveryEnabled()).isTrue();
@ -82,11 +88,12 @@ public class NacosContextPropertiesTest {
assertThat(DefaultPlugins.SERVER_CONNECTOR_NACOS.equals(serverConnectorConfig.getProtocol())).isTrue();
Map<String, String> metadata = serverConnectorConfig.getMetadata();
assertThat(metadata.get(NacosConfigModifier.USERNAME)).isEqualTo(nacosContextProperties.getUsername());
assertThat(metadata.get(NacosConfigModifier.PASSWORD)).isEqualTo(nacosContextProperties.getPassword());
assertThat(metadata.get(NacosConfigModifier.CONTEXT_PATH)).isEqualTo(nacosContextProperties.getContextPath());
assertThat(metadata.get(NacosConfigModifier.NAMESPACE)).isEqualTo(nacosContextProperties.getNamespace());
assertThat(metadata.get(NacosConfigModifier.GROUP)).isEqualTo(nacosContextProperties.getGroup());
assertThat(metadata.get(USERNAME)).isEqualTo(nacosContextProperties.getUsername());
assertThat(metadata.get(PASSWORD)).isEqualTo(nacosContextProperties.getPassword());
assertThat(metadata.get(CONTEXT_PATH)).isEqualTo(nacosContextProperties.getContextPath());
assertThat(metadata.get(NAMESPACE)).isEqualTo(nacosContextProperties.getNamespace());
assertThat(metadata.get(NACOS_GROUP_KEY)).isEqualTo(nacosContextProperties.getGroup());
assertThat(metadata.get(NACOS_CLUSTER_KEY)).isEqualTo(nacosContextProperties.getClusterName());
}
@SpringBootApplication

@ -0,0 +1,81 @@
/*
* Tencent is pleased to support the open source community by making spring-cloud-tencent available.
*
* Copyright (C) 2021 Tencent. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.tencent.cloud.polaris.registry;
import java.util.Map;
import com.tencent.cloud.polaris.context.PolarisSDKContextManager;
import com.tencent.cloud.polaris.context.config.PolarisContextAutoConfiguration;
import com.tencent.cloud.polaris.discovery.PolarisDiscoveryClientConfiguration;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.runner.WebApplicationContextRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import static com.tencent.polaris.test.common.Consts.PORT;
import static com.tencent.polaris.test.common.Consts.SERVICE_PROVIDER;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
/**
* Test for {@link NacosPolarisRegistrationCustomizerTest}.
*
* @author Yuwei Fu
*/
public class NacosPolarisRegistrationCustomizerTest {
private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(
PolarisContextAutoConfiguration.class,
PolarisServiceRegistryAutoConfiguration.class,
PolarisDiscoveryClientConfiguration.class))
.withPropertyValues("spring.application.name=" + SERVICE_PROVIDER)
.withPropertyValues("server.port=" + PORT)
.withPropertyValues("spring.cloud.nacos.discovery.cluster-name=nacos")
.withPropertyValues("spring.cloud.nacos.discovery.group=nacos")
.withPropertyValues("spring.cloud.polaris.address=grpc://127.0.0.1:10081");
@BeforeEach
public void setUp() {
PolarisSDKContextManager.innerDestroy();
}
@Test
public void testCustomize() {
this.contextRunner.run(context -> {
PolarisRegistration polarisRegistration = context.getBean(PolarisRegistration.class);
polarisRegistration.customize();
Map<String, String> metadata = polarisRegistration.getMetadata();
assertThat(metadata.get("nacos.cluster")).isEqualTo("nacos");
assertThat(metadata.get("nacos.group")).isEqualTo("nacos");
});
}
@Configuration
@EnableAutoConfiguration
static class PolarisServiceRegistryAutoConfiguration {
@Bean
public PolarisRegistrationCustomizer polarisRegistrationCustomizer() {
return mock(PolarisRegistrationCustomizer.class);
}
}
}

@ -62,7 +62,7 @@ public class PolarisRegistrationCustomizerTest {
this.contextRunner.run(context -> {
PolarisRegistration polarisRegistration = context.getBean(PolarisRegistration.class);
polarisRegistration.customize();
PolarisRegistrationCustomizer customizer = context.getBean(PolarisRegistrationCustomizer.class);
PolarisRegistrationCustomizer customizer = context.getBeansOfType(PolarisRegistrationCustomizer.class).get("polarisRegistrationCustomizer");
verify(customizer, times(1)).customize(any(PolarisRegistration.class));
});
}

@ -46,7 +46,6 @@ import static com.tencent.polaris.test.common.Consts.SERVICE_PROVIDER;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Test for {@link PolarisRegistration}.
@ -82,7 +81,6 @@ public class PolarisRegistrationTest {
// mock NacosContextProperties
nacosContextProperties = mock(NacosContextProperties.class);
doReturn(true).when(nacosContextProperties).isEnabled();
doReturn(true).when(nacosContextProperties).isRegisterEnabled();
doReturn("/").when(nacosContextProperties).getContextPath();
doReturn("cluster").when(nacosContextProperties).getClusterName();
@ -179,7 +177,7 @@ public class PolarisRegistrationTest {
Map<String, String> metadata = polarisRegistration1.getMetadata();
assertThat(metadata).isNotNull();
assertThat(metadata).isNotEmpty();
assertThat(metadata.size()).isEqualTo(2);
assertThat(metadata.size()).isEqualTo(1);
assertThat(metadata.get("key1")).isEqualTo("value1");
}
@ -192,24 +190,4 @@ public class PolarisRegistrationTest {
public void testToString() {
System.out.println(polarisRegistration1);
}
@Test
public void testGetNacosServiceId() {
String groupName = "group";
String format = "%s__%s";
when(nacosContextProperties.getGroup()).thenReturn(groupName);
String serviceId = polarisRegistration1.getServiceId();
assertThat(String.format(format, groupName, SERVICE_PROVIDER).equals(serviceId));
}
@Test
public void testGetNacosMetadata() {
String clusterName = "cluster";
when(nacosContextProperties.getClusterName()).thenReturn(clusterName);
Map<String, String> metadata = polarisRegistration1.getMetadata();
assertThat(metadata).isNotNull();
assertThat(metadata).isNotEmpty();
assertThat(metadata.size()).isEqualTo(2);
assertThat(metadata.get("nacos.cluster")).isEqualTo(clusterName);
}
}

@ -50,7 +50,6 @@ public class RouterConfigModifier implements PolarisConfigModifier {
// Update modified config to source properties
configuration.getConsumer().getServiceRouter()
.setPluginConfig(ServiceRouterConfig.DEFAULT_ROUTER_RECOVER, recoverRouterConfig);
if (StringUtils.isNotBlank(polarisNearByRouterProperties.getMatchLevel())) {
RoutingProto.NearbyRoutingConfig.LocationLevel locationLevel =
RoutingProto.NearbyRoutingConfig.LocationLevel.valueOf(StringUtils.upperCase(polarisNearByRouterProperties.getMatchLevel()));

@ -45,7 +45,6 @@ public class MetadataRouterRequestInterceptor implements RouterRequestIntercepto
if (!polarisMetadataRouterProperties.isEnabled()) {
return;
}
// set metadata router label keys
MetadataContainer metadataContainer = MetadataContextHolder.get()
.getMetadataContainer(MetadataType.CUSTOM, false);

@ -6,6 +6,12 @@
"defaultValue": true,
"description": "the switch for metadata router."
},
{
"name": "spring.cloud.polaris.router.metadata-router.failOver",
"type": "java.lang.String",
"defaultValue": "METADATAFAILOVERALL",
"description": "the fail over type for rule based router."
},
{
"name": "spring.cloud.polaris.router.nearby-router.enabled",
"type": "java.lang.Boolean",

@ -25,7 +25,6 @@ import java.util.function.BiConsumer;
import com.tencent.cloud.common.constant.MetadataConstant;
import com.tencent.cloud.common.util.ApplicationContextAwareUtils;
import com.tencent.cloud.common.util.DiscoveryUtil;
import com.tencent.polaris.metadata.core.MetadataContainer;
import com.tencent.polaris.metadata.core.MetadataMapValue;
import com.tencent.polaris.metadata.core.MetadataObjectValue;
@ -107,7 +106,6 @@ public class MetadataContext extends com.tencent.polaris.metadata.core.manager.M
LOG.error("namespace should not be blank. please configure spring.cloud.polaris.namespace or "
+ "spring.cloud.polaris.discovery.namespace");
}
namespace = DiscoveryUtil.rewriteNamespace(namespace);
LOCAL_NAMESPACE = namespace;
String serviceName = ApplicationContextAwareUtils
@ -121,7 +119,6 @@ public class MetadataContext extends com.tencent.polaris.metadata.core.manager.M
LOG.warn("service name should not be blank. please configure spring.cloud.polaris.service or "
+ "spring.cloud.polaris.discovery.service or spring.application.name");
}
serviceName = DiscoveryUtil.rewriteServiceId(serviceName);
LOCAL_SERVICE = serviceName;
}

@ -1,108 +0,0 @@
/*
* Tencent is pleased to support the open source community by making spring-cloud-tencent available.
*
* Copyright (C) 2021 Tencent. 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.common.util;
/**
* Utils for Discovery.
*/
public final class DiscoveryUtil {
private static String ENABLE_NACOS;
private static String ENABLE_NACOS_DISCOVERY;
private static String ENABLE_NACOS_REGISTRY;
private static String ENABLE_POLARIS_DISCOVERY;
private static String NACOS_GROUP;
private static String NACOS_NAMESPACE;
private static final Object MUTEX = new Object();
private static boolean INITIALIZE = false;
private DiscoveryUtil() {
}
/**
* rewrite serviceId when open double registry and discovery by nacos and polaris.
*
* @param serviceId service id
* @return new service id
*/
public static String rewriteServiceId(String serviceId) {
init();
if (Boolean.parseBoolean(ENABLE_NACOS)) {
boolean rewrite = false;
if (Boolean.parseBoolean(ENABLE_NACOS_REGISTRY) && Boolean.parseBoolean(ENABLE_POLARIS_DISCOVERY)) {
rewrite = true;
}
if (Boolean.parseBoolean(ENABLE_NACOS_DISCOVERY) || Boolean.parseBoolean(ENABLE_POLARIS_DISCOVERY)) {
rewrite = true;
}
if (rewrite) {
serviceId = NACOS_GROUP + "__" + serviceId;
}
}
return serviceId;
}
/**
* rewrite namespace when open double registry and discovery by nacos and polaris.
*
* @param namespace namespace
* @return new namespace
*/
public static String rewriteNamespace(String namespace) {
init();
if (Boolean.parseBoolean(ENABLE_NACOS)) {
boolean rewrite = false;
if (Boolean.parseBoolean(ENABLE_NACOS_REGISTRY) && Boolean.parseBoolean(ENABLE_POLARIS_DISCOVERY)) {
rewrite = true;
}
if (Boolean.parseBoolean(ENABLE_NACOS_DISCOVERY) || Boolean.parseBoolean(ENABLE_POLARIS_DISCOVERY)) {
rewrite = true;
}
if (rewrite) {
namespace = NACOS_NAMESPACE;
}
}
return namespace;
}
private static void init() {
if (INITIALIZE) {
return;
}
synchronized (MUTEX) {
if (INITIALIZE) {
return;
}
ENABLE_NACOS = ApplicationContextAwareUtils.getProperties("spring.cloud.nacos.enabled");
ENABLE_NACOS_DISCOVERY = ApplicationContextAwareUtils.getProperties("spring.cloud.nacos.discovery.enabled");
ENABLE_NACOS_REGISTRY = ApplicationContextAwareUtils.getProperties("spring.cloud.nacos.discovery.register-enabled");
ENABLE_POLARIS_DISCOVERY = ApplicationContextAwareUtils.getProperties("spring.cloud.polaris.discovery.enabled");
NACOS_GROUP = ApplicationContextAwareUtils.getProperties("spring.cloud.nacos.discovery.group", "DEFAULT_GROUP");
NACOS_NAMESPACE = ApplicationContextAwareUtils.getProperties("spring.cloud.nacos.discovery.namespace", "public");
INITIALIZE = true;
}
}
}

@ -252,12 +252,6 @@
<version>${polaris.version}</version>
</dependency>
<dependency>
<groupId>com.tencent.polaris</groupId>
<artifactId>connector-nacos</artifactId>
<version>${polaris.version}</version>
</dependency>
<dependency>
<groupId>com.tencent.polaris</groupId>
<artifactId>polaris-test-common</artifactId>

Loading…
Cancel
Save