Merge branch 'master' of github.com:spring-cloud-incubator/spring-cloud-alibaba

pull/242/head
xiaolongzuo 6 years ago
commit 9d3a57e02d

@ -0,0 +1 @@
language: java

@ -50,7 +50,7 @@ Spring Cloud 使用 Maven 来构建最快的使用方式是将本项目clone
## 如何使用
### 如何引入依赖
项目已经发布了第一个版本,版本 0.2.0.RELEASE 对应的是 Spring Cloud Finchley 版本,版本 0.1.0.RELEASE 对应的是 Spring Cloud Edgware 版本。
项目的最新版本是 0.2.1.RELEASE 和 0.1.1.RELEASE版本 0.2.1.RELEASE 对应的是 Spring Cloud Finchley 版本,版本 0.1.1.RELEASE 对应的是 Spring Cloud Edgware 版本。
如果需要使用已发布的版本,在 `dependencyManagement` 中添加如下配置。
@ -59,7 +59,7 @@ Spring Cloud 使用 Maven 来构建最快的使用方式是将本项目clone
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>0.2.0.RELEASE</version>
<version>0.2.1.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>

@ -16,7 +16,7 @@
package org.springframework.cloud.alibaba.nacos;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
@ -26,7 +26,9 @@ import org.springframework.cloud.alibaba.nacos.registry.NacosAutoServiceRegistra
import org.springframework.cloud.alibaba.nacos.registry.NacosRegistration;
import org.springframework.cloud.alibaba.nacos.registry.NacosServiceRegistry;
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationAutoConfiguration;
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration;
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@ -41,6 +43,7 @@ import org.springframework.context.annotation.Configuration;
@ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true)
@AutoConfigureBefore({ AutoServiceRegistrationAutoConfiguration.class,
NacosDiscoveryClientAutoConfiguration.class })
@AutoConfigureAfter(AutoServiceRegistrationConfiguration.class)
public class NacosDiscoveryAutoConfiguration {
@Bean
@ -50,8 +53,10 @@ public class NacosDiscoveryAutoConfiguration {
@Bean
@ConditionalOnBean(AutoServiceRegistrationProperties.class)
public NacosRegistration nacosRegistration() {
return new NacosRegistration();
public NacosRegistration nacosRegistration(
NacosDiscoveryProperties nacosDiscoveryProperties,
ApplicationContext context) {
return new NacosRegistration(nacosDiscoveryProperties, context);
}
@Bean

@ -20,7 +20,6 @@ import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.ListView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
@ -36,9 +35,12 @@ public class NacosDiscoveryClient implements DiscoveryClient {
.getLogger(NacosDiscoveryClient.class);
public static final String DESCRIPTION = "Spring Cloud Nacos Discovery Client";
@Autowired
private NacosDiscoveryProperties discoveryProperties;
public NacosDiscoveryClient(NacosDiscoveryProperties discoveryProperties) {
this.discoveryProperties = discoveryProperties;
}
@Override
public String description() {
return DESCRIPTION;
@ -70,6 +72,11 @@ public class NacosDiscoveryClient implements DiscoveryClient {
metadata.put("cluster", instance.getClusterName() + "");
metadata.putAll(instance.getMetadata());
nacosServiceInstance.setMetadata(metadata);
if (metadata.containsKey("secure")) {
boolean secure = Boolean.parseBoolean(metadata.get("secure"));
nacosServiceInstance.setSecure(secure);
}
return nacosServiceInstance;
}

@ -32,8 +32,9 @@ import org.springframework.context.annotation.Configuration;
public class NacosDiscoveryClientAutoConfiguration {
@Bean
public DiscoveryClient nacosDiscoveryClient() {
return new NacosDiscoveryClient();
public DiscoveryClient nacosDiscoveryClient(
NacosDiscoveryProperties discoveryProperties) {
return new NacosDiscoveryClient(discoveryProperties);
}
@Bean

@ -143,6 +143,10 @@ public class NacosDiscoveryProperties {
@PostConstruct
public void init() throws SocketException {
if (secure) {
metadata.put("secure", "true");
}
serverAddr = Objects.toString(serverAddr, "");
endpoint = Objects.toString(endpoint, "");
namespace = Objects.toString(namespace, "");
@ -351,7 +355,7 @@ public class NacosDiscoveryProperties {
}
if (StringUtils.isEmpty(this.getClusterName())) {
this.setClusterName(env.resolvePlaceholders(
"${spring.cloud.nacos.discovery.clusterName-name:}"));
"${spring.cloud.nacos.discovery.cluster-name:}"));
}
if (StringUtils.isEmpty(this.getEndpoint())) {
this.setEndpoint(

@ -26,7 +26,6 @@ import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties;
@ -41,9 +40,12 @@ public class NacosDiscoveryEndpoint {
private static final Logger LOGGER = LoggerFactory
.getLogger(NacosDiscoveryEndpoint.class);
@Autowired
private NacosDiscoveryProperties nacosDiscoveryProperties;
public NacosDiscoveryEndpoint(NacosDiscoveryProperties nacosDiscoveryProperties) {
this.nacosDiscoveryProperties = nacosDiscoveryProperties;
}
/**
* @return nacos discovery endpoint
*/

@ -20,7 +20,7 @@ import org.springframework.boot.actuate.autoconfigure.endpoint.condition.Conditi
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@ -34,8 +34,9 @@ public class NacosDiscoveryEndpointAutoConfiguration {
@Bean
@ConditionalOnMissingBean
@ConditionalOnEnabledEndpoint
public NacosDiscoveryEndpoint nacosDiscoveryEndpoint() {
return new NacosDiscoveryEndpoint();
public NacosDiscoveryEndpoint nacosDiscoveryEndpoint(
NacosDiscoveryProperties nacosDiscoveryProperties) {
return new NacosDiscoveryEndpoint(nacosDiscoveryProperties);
}
}

@ -18,7 +18,6 @@ package org.springframework.cloud.alibaba.nacos.registry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.serviceregistry.AbstractAutoServiceRegistration;
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationProperties;
import org.springframework.cloud.client.serviceregistry.ServiceRegistry;
@ -33,7 +32,6 @@ public class NacosAutoServiceRegistration
private static final Logger LOGGER = LoggerFactory
.getLogger(NacosAutoServiceRegistration.class);
@Autowired
private NacosRegistration registration;
public NacosAutoServiceRegistration(

@ -17,7 +17,6 @@
package org.springframework.cloud.alibaba.nacos.registry;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.DefaultServiceInstance;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.ManagementServerPortUtils;
@ -38,16 +37,20 @@ import com.alibaba.nacos.api.naming.NamingService;
*/
public class NacosRegistration implements Registration, ServiceInstance {
private static final String MANAGEMENT_PORT = "management.port";
private static final String MANAGEMENT_CONTEXT_PATH = "management.context-path";
private static final String MANAGEMENT_ADDRESS = "management.address";
public static final String MANAGEMENT_PORT = "management.port";
public static final String MANAGEMENT_CONTEXT_PATH = "management.context-path";
public static final String MANAGEMENT_ADDRESS = "management.address";
@Autowired
private NacosDiscoveryProperties nacosDiscoveryProperties;
@Autowired
private ApplicationContext context;
public NacosRegistration(NacosDiscoveryProperties nacosDiscoveryProperties,
ApplicationContext context) {
this.nacosDiscoveryProperties = nacosDiscoveryProperties;
this.context = context;
}
@PostConstruct
public void init() {
@ -122,11 +125,6 @@ public class NacosRegistration implements Registration, ServiceInstance {
return nacosDiscoveryProperties.namingServiceInstance();
}
public void setNacosDiscoveryProperties(
NacosDiscoveryProperties nacosDiscoveryProperties) {
this.nacosDiscoveryProperties = nacosDiscoveryProperties;
}
@Override
public String toString() {
return "NacosRegistration{" + "nacosDiscoveryProperties="

@ -19,6 +19,7 @@ package org.springframework.cloud.alibaba.nacos.ribbon;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.ServerList;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@ -32,8 +33,8 @@ public class NacosRibbonClientConfiguration {
@Bean
@ConditionalOnMissingBean
public ServerList<?> ribbonServerList(IClientConfig config) {
NacosServerList serverList = new NacosServerList();
public ServerList<?> ribbonServerList(IClientConfig config, NacosDiscoveryProperties nacosDiscoveryProperties) {
NacosServerList serverList = new NacosServerList(nacosDiscoveryProperties);
serverList.initWithNiwsConfig(config);
return serverList;
}

@ -18,7 +18,6 @@ package org.springframework.cloud.alibaba.nacos.ribbon;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractServerList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties;
import java.util.ArrayList;
@ -32,16 +31,12 @@ import com.alibaba.nacos.api.naming.pojo.Instance;
*/
public class NacosServerList extends AbstractServerList<NacosServer> {
@Autowired
private NacosDiscoveryProperties discoveryProperties;
private String serviceId;
public NacosServerList() {
}
public NacosServerList(String serviceId) {
this.serviceId = serviceId;
public NacosServerList(NacosDiscoveryProperties discoveryProperties) {
this.discoveryProperties = discoveryProperties;
}
@Override

@ -1,83 +0,0 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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 org.springframework.cloud.alibaba.nacos;
import org.junit.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.test.context.runner.WebApplicationContextRunner;
import org.springframework.cloud.alibaba.nacos.registry.NacosRegistration;
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationProperties;
import org.springframework.cloud.commons.util.InetUtils;
import org.springframework.cloud.commons.util.InetUtilsProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author xiaojing
*/
public class NacosDiscoveryAutoConfigurationTests {
private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.withConfiguration(
AutoConfigurations.of(NacosDiscoveryTestConfiguration.class,
NacosDiscoveryAutoConfiguration.class,
NacosDiscoveryClientAutoConfiguration.class))
.withPropertyValues("spring.cloud.nacos.discovery.server-addr=127.0.0.1:8080")
.withPropertyValues("spring.cloud.nacos.discovery.port=18080")
.withPropertyValues("spring.cloud.nacos.discovery.service=myapp");
@Test
public void testProperties() {
this.contextRunner.run(context -> {
NacosDiscoveryProperties properties = context
.getBean(NacosDiscoveryProperties.class);
assertThat(properties.getPort()).isEqualTo(18080);
assertThat(properties.getServerAddr()).isEqualTo("127.0.0.1:8080");
assertThat(properties.getService()).isEqualTo("myapp");
});
}
@Test
public void nacosRegistration() {
this.contextRunner.run(context -> {
NacosRegistration nacosRegistration = context
.getBean(NacosRegistration.class);
assertThat(nacosRegistration.getPort()).isEqualTo(18080);
assertThat(nacosRegistration.getServiceId()).isEqualTo("myapp");
assertThat(nacosRegistration.getRegisterWeight()).isEqualTo(1F);
});
}
@Configuration
@AutoConfigureBefore(NacosDiscoveryAutoConfiguration.class)
static class NacosDiscoveryTestConfiguration {
@Bean
AutoServiceRegistrationProperties autoServiceRegistrationProperties() {
return new AutoServiceRegistrationProperties();
}
@Bean
InetUtils inetUtils() {
return new InetUtils(new InetUtilsProperties());
}
}
}

@ -0,0 +1,126 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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 org.springframework.cloud.alibaba.nacos;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.ListView;
import org.junit.Test;
import org.springframework.cloud.client.ServiceInstance;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.springframework.cloud.alibaba.nacos.test.NacosMockTest.serviceInstance;
/**
* @author xiaojing
*/
public class NacosDiscoveryClientTests {
private String host = "123.123.123.123";
private int port = 8888;
private String serviceName = "test-service";
@Test
public void testGetServers() throws Exception {
ArrayList<Instance> instances = new ArrayList<>();
HashMap<String, String> map = new HashMap<>();
map.put("test-key", "test-value");
map.put("secure", "true");
instances.add(serviceInstance(serviceName, false, host, port, map));
NacosDiscoveryProperties nacosDiscoveryProperties = mock(
NacosDiscoveryProperties.class);
NamingService namingService = mock(NamingService.class);
when(nacosDiscoveryProperties.namingServiceInstance()).thenReturn(namingService);
when(namingService.selectInstances(eq(serviceName), eq(true)))
.thenReturn(instances);
NacosDiscoveryClient discoveryClient = new NacosDiscoveryClient(
nacosDiscoveryProperties);
List<ServiceInstance> serviceInstances = discoveryClient
.getInstances(serviceName);
assertThat(serviceInstances.size()).isEqualTo(1);
ServiceInstance serviceInstance = serviceInstances.get(0);
assertThat(serviceInstance.getServiceId()).isEqualTo(serviceName);
assertThat(serviceInstance.getHost()).isEqualTo(host);
assertThat(serviceInstance.getPort()).isEqualTo(port);
assertThat(serviceInstance.isSecure()).isEqualTo(true);
assertThat(serviceInstance.getUri().toString())
.isEqualTo(getUri(serviceInstance));
assertThat(serviceInstance.getMetadata().get("test-key")).isEqualTo("test-value");
}
@Test
public void testGetAllService() throws Exception {
ListView<String> nacosServices = new ListView<>();
nacosServices.setData(new LinkedList<>());
nacosServices.getData().add(serviceName + "1");
nacosServices.getData().add(serviceName + "2");
nacosServices.getData().add(serviceName + "3");
NacosDiscoveryProperties nacosDiscoveryProperties = mock(
NacosDiscoveryProperties.class);
NamingService namingService = mock(NamingService.class);
NacosDiscoveryClient discoveryClient = new NacosDiscoveryClient(
nacosDiscoveryProperties);
when(nacosDiscoveryProperties.namingServiceInstance()).thenReturn(namingService);
when(namingService.getServicesOfServer(eq(1), eq(Integer.MAX_VALUE)))
.thenReturn(nacosServices);
List<String> services = discoveryClient.getServices();
assertThat(services.size()).isEqualTo(3);
assertThat(services.contains(serviceName + "1"));
assertThat(services.contains(serviceName + "2"));
assertThat(services.contains(serviceName + "3"));
}
private String getUri(ServiceInstance instance) {
if (instance.isSecure()) {
return "https://" + host + ":" + port;
}
return "http://" + host + ":" + port;
}
}

@ -0,0 +1,147 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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 org.springframework.cloud.alibaba.nacos.registry;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryAutoConfiguration;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryClientAutoConfiguration;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties;
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration;
import org.springframework.cloud.commons.util.InetUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
/**
* @author xiaojing
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = NacosAutoServiceRegistrationIpNetworkInterfaceTests.TestConfig.class, properties = {
"spring.application.name=myTestService1",
"spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848" }, webEnvironment = RANDOM_PORT)
public class NacosAutoServiceRegistrationIpNetworkInterfaceTests {
@Autowired
private NacosRegistration registration;
@Autowired
private NacosAutoServiceRegistration nacosAutoServiceRegistration;
@Autowired
private NacosDiscoveryProperties properties;
@Autowired
private InetUtils inetUtils;
@Test
public void contextLoads() throws Exception {
assertNotNull("NacosRegistration was not created", registration);
assertNotNull("NacosDiscoveryProperties was not created", properties);
assertNotNull("NacosAutoServiceRegistration was not created",
nacosAutoServiceRegistration);
checkoutNacosDiscoveryServiceIP();
}
private void checkoutNacosDiscoveryServiceIP() {
assertEquals("NacosDiscoveryProperties service IP was wrong",
getIPFromNetworkInterface(TestConfig.netWorkInterfaceName),
registration.getHost());
}
private String getIPFromNetworkInterface(String networkInterface) {
if (!TestConfig.hasValidNetworkInterface) {
return inetUtils.findFirstNonLoopbackHostInfo().getIpAddress();
}
try {
NetworkInterface netInterface = NetworkInterface.getByName(networkInterface);
Enumeration<InetAddress> inetAddress = netInterface.getInetAddresses();
while (inetAddress.hasMoreElements()) {
InetAddress currentAddress = inetAddress.nextElement();
if (currentAddress instanceof Inet4Address
&& !currentAddress.isLoopbackAddress()) {
return currentAddress.getHostAddress();
}
}
return networkInterface;
}
catch (Exception e) {
return networkInterface;
}
}
@Configuration
@EnableAutoConfiguration
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
NacosDiscoveryClientAutoConfiguration.class,
NacosDiscoveryAutoConfiguration.class })
public static class TestConfig {
static boolean hasValidNetworkInterface = false;
static String netWorkInterfaceName;
static {
try {
Enumeration<NetworkInterface> enumeration = NetworkInterface
.getNetworkInterfaces();
while (enumeration.hasMoreElements() && !hasValidNetworkInterface) {
NetworkInterface networkInterface = enumeration.nextElement();
Enumeration<InetAddress> inetAddress = networkInterface
.getInetAddresses();
while (inetAddress.hasMoreElements()) {
InetAddress currentAddress = inetAddress.nextElement();
if (currentAddress instanceof Inet4Address
&& !currentAddress.isLoopbackAddress()) {
hasValidNetworkInterface = true;
netWorkInterfaceName = networkInterface.getName();
System.setProperty(
"spring.cloud.nacos.discovery.network-interface",
networkInterface.getName());
break;
}
}
}
}
catch (Exception e) {
}
}
}
}

@ -0,0 +1,82 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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 org.springframework.cloud.alibaba.nacos.registry;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryAutoConfiguration;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryClientAutoConfiguration;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties;
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
/**
* @author xiaojing
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = NacosAutoServiceRegistrationIpTests.TestConfig.class, properties = {
"spring.application.name=myTestService1",
"spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848",
"spring.cloud.nacos.discovery.ip=123.123.123.123" }, webEnvironment = RANDOM_PORT)
public class NacosAutoServiceRegistrationIpTests {
@Autowired
private NacosRegistration registration;
@Autowired
private NacosAutoServiceRegistration nacosAutoServiceRegistration;
@Autowired
private NacosDiscoveryProperties properties;
@Test
public void contextLoads() throws Exception {
assertNotNull("NacosRegistration was not created", registration);
assertNotNull("NacosDiscoveryProperties was not created", properties);
assertNotNull("NacosAutoServiceRegistration was not created",
nacosAutoServiceRegistration);
checkoutNacosDiscoveryServiceIP();
}
private void checkoutNacosDiscoveryServiceIP() {
assertEquals("NacosDiscoveryProperties service IP was wrong", "123.123.123.123",
registration.getHost());
}
@Configuration
@EnableAutoConfiguration
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
NacosDiscoveryClientAutoConfiguration.class,
NacosDiscoveryAutoConfiguration.class })
public static class TestConfig {
}
}

@ -0,0 +1,88 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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 org.springframework.cloud.alibaba.nacos.registry;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
import static org.springframework.cloud.alibaba.nacos.registry.NacosRegistration.MANAGEMENT_PORT;
import static org.springframework.cloud.alibaba.nacos.registry.NacosRegistration.MANAGEMENT_CONTEXT_PATH;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryAutoConfiguration;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryClientAutoConfiguration;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties;
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
/**
* @author xiaojing
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = NacosAutoServiceRegistrationManagementPortTests.TestConfig.class, properties = {
"spring.application.name=myTestService1", "management.server.port=8888",
"management.server.servlet.context-path=/test-context-path",
"spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848",
"spring.cloud.nacos.discovery.port=8888" }, webEnvironment = RANDOM_PORT)
public class NacosAutoServiceRegistrationManagementPortTests {
@Autowired
private NacosRegistration registration;
@Autowired
private NacosAutoServiceRegistration nacosAutoServiceRegistration;
@Autowired
private NacosDiscoveryProperties properties;
@Test
public void contextLoads() throws Exception {
assertNotNull("NacosRegistration was not created", registration);
assertNotNull("NacosDiscoveryProperties was not created", properties);
assertNotNull("NacosAutoServiceRegistration was not created",
nacosAutoServiceRegistration);
checkoutNacosDiscoveryManagementData();
}
private void checkoutNacosDiscoveryManagementData() {
assertEquals("NacosDiscoveryProperties management port was wrong", "8888",
properties.getMetadata().get(MANAGEMENT_PORT));
assertEquals("NacosDiscoveryProperties management context path was wrong",
"/test-context-path",
properties.getMetadata().get(MANAGEMENT_CONTEXT_PATH));
}
@Configuration
@EnableAutoConfiguration
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
NacosDiscoveryClientAutoConfiguration.class,
NacosDiscoveryAutoConfiguration.class })
public static class TestConfig {
}
}

@ -0,0 +1,82 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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 org.springframework.cloud.alibaba.nacos.registry;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryAutoConfiguration;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryClientAutoConfiguration;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties;
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
/**
* @author xiaojing
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = NacosAutoServiceRegistrationPortTests.TestConfig.class, properties = {
"spring.application.name=myTestService1",
"spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848",
"spring.cloud.nacos.discovery.port=8888" }, webEnvironment = RANDOM_PORT)
public class NacosAutoServiceRegistrationPortTests {
@Autowired
private NacosRegistration registration;
@Autowired
private NacosAutoServiceRegistration nacosAutoServiceRegistration;
@Autowired
private NacosDiscoveryProperties properties;
@Test
public void contextLoads() throws Exception {
assertNotNull("NacosRegistration was not created", registration);
assertNotNull("NacosDiscoveryProperties was not created", properties);
assertNotNull("NacosAutoServiceRegistration was not created",
nacosAutoServiceRegistration);
checkoutNacosDiscoveryServicePort();
}
private void checkoutNacosDiscoveryServicePort() {
assertEquals("NacosDiscoveryProperties service Port was wrong", 8888,
registration.getPort());
}
@Configuration
@EnableAutoConfiguration
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
NacosDiscoveryClientAutoConfiguration.class,
NacosDiscoveryAutoConfiguration.class })
public static class TestConfig {
}
}

@ -0,0 +1,199 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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 org.springframework.cloud.alibaba.nacos.registry;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryAutoConfiguration;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryClientAutoConfiguration;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties;
import org.springframework.cloud.alibaba.nacos.endpoint.NacosDiscoveryEndpoint;
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration;
import org.springframework.cloud.commons.util.InetUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
/**
* @author xiaojing
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = NacosAutoServiceRegistrationTests.TestConfig.class, properties = {
"spring.application.name=myTestService1",
"spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848",
"spring.cloud.nacos.discovery.endpoint=test-endpoint",
"spring.cloud.nacos.discovery.namespace=test-namespace",
"spring.cloud.nacos.discovery.log-name=test-logName",
"spring.cloud.nacos.discovery.weight=2",
"spring.cloud.nacos.discovery.clusterName=test-cluster",
"spring.cloud.nacos.discovery.namingLoadCacheAtStart=true",
"spring.cloud.nacos.discovery.secure=true",
"spring.cloud.nacos.discovery.accessKey=test-accessKey",
"spring.cloud.nacos.discovery.secretKey=test-secretKey" }, webEnvironment = RANDOM_PORT)
public class NacosAutoServiceRegistrationTests {
@Autowired
private NacosRegistration registration;
@Autowired
private NacosAutoServiceRegistration nacosAutoServiceRegistration;
@LocalServerPort
private int port;
@Autowired
private NacosDiscoveryProperties properties;
@Autowired
private InetUtils inetUtils;
@Test
public void contextLoads() throws Exception {
assertNotNull("NacosRegistration was not created", registration);
assertNotNull("NacosDiscoveryProperties was not created", properties);
assertNotNull("NacosAutoServiceRegistration was not created",
nacosAutoServiceRegistration);
checkoutNacosDiscoveryServerAddr();
checkoutNacosDiscoveryEndpoint();
checkoutNacosDiscoveryNamespace();
checkoutNacosDiscoveryLogName();
checkoutNacosDiscoveryWeight();
checkoutNacosDiscoveryClusterName();
checkoutNacosDiscoveryCache();
checkoutNacosDiscoverySecure();
checkoutNacosDiscoveryAccessKey();
checkoutNacosDiscoverySecrectKey();
checkoutNacosDiscoveryServiceName();
checkoutNacosDiscoveryServiceIP();
checkoutNacosDiscoveryServicePort();
checkAutoRegister();
checkoutEndpoint();
}
private void checkAutoRegister() {
assertTrue("Nacos Auto Registration was not start",
nacosAutoServiceRegistration.isRunning());
}
private void checkoutNacosDiscoveryServerAddr() {
assertEquals("NacosDiscoveryProperties server address was wrong",
"127.0.0.1:8848", properties.getServerAddr());
}
private void checkoutNacosDiscoveryEndpoint() {
assertEquals("NacosDiscoveryProperties endpoint was wrong", "test-endpoint",
properties.getEndpoint());
}
private void checkoutNacosDiscoveryNamespace() {
assertEquals("NacosDiscoveryProperties namespace was wrong", "test-namespace",
properties.getNamespace());
}
private void checkoutNacosDiscoveryLogName() {
assertEquals("NacosDiscoveryProperties logName was wrong", "test-logName",
properties.getLogName());
}
private void checkoutNacosDiscoveryWeight() {
assertEquals(2, properties.getWeight(), 0.00000001);
}
private void checkoutNacosDiscoveryClusterName() {
assertEquals("NacosDiscoveryProperties cluster was wrong", "test-cluster",
properties.getClusterName());
}
private void checkoutNacosDiscoveryCache() {
assertEquals("NacosDiscoveryProperties naming load cache was wrong", "true",
properties.getNamingLoadCacheAtStart());
}
private void checkoutNacosDiscoverySecure() {
assertEquals("NacosDiscoveryProperties is secure was wrong", true,
properties.isSecure());
assertEquals("NacosDiscoveryProperties is secure was wrong", "true",
properties.getMetadata().get("secure"));
}
private void checkoutNacosDiscoveryAccessKey() {
assertEquals("NacosDiscoveryProperties is access key was wrong", "test-accessKey",
properties.getAccessKey());
}
private void checkoutNacosDiscoverySecrectKey() {
assertEquals("NacosDiscoveryProperties is secret key was wrong", "test-secretKey",
properties.getSecretKey());
}
private void checkoutNacosDiscoveryServiceName() {
assertEquals("NacosDiscoveryProperties service name was wrong", "myTestService1",
properties.getService());
}
private void checkoutNacosDiscoveryServiceIP() {
assertEquals("NacosDiscoveryProperties service IP was wrong",
inetUtils.findFirstNonLoopbackHostInfo().getIpAddress(),
registration.getHost());
}
private void checkoutNacosDiscoveryServicePort() {
assertEquals("NacosDiscoveryProperties service Port was wrong", port,
registration.getPort());
}
private void checkoutEndpoint() throws Exception {
NacosDiscoveryEndpoint nacosDiscoveryEndpoint = new NacosDiscoveryEndpoint(
properties);
Map<String, Object> map = nacosDiscoveryEndpoint.nacosDiscovery();
assertEquals(map.get("NacosDiscoveryProperties"), properties);
assertEquals(map.get("subscribe"),
properties.namingServiceInstance().getSubscribeServices());
}
@Configuration
@EnableAutoConfiguration
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
NacosDiscoveryClientAutoConfiguration.class,
NacosDiscoveryAutoConfiguration.class })
public static class TestConfig {
}
}

@ -25,7 +25,7 @@ public class NacosRibbonClientConfigurationTests {
NacosRibbonClientConfiguration.class,
NacosDiscoveryClientAutoConfiguration.class,
RibbonNacosAutoConfiguration.class))
.withPropertyValues("spring.cloud.nacos.discovery.server-addr=127.0.0.1:8080")
.withPropertyValues("spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848")
.withPropertyValues("spring.cloud.nacos.discovery.port=18080")
.withPropertyValues("spring.cloud.nacos.discovery.service=myapp");
@ -45,7 +45,6 @@ public class NacosRibbonClientConfigurationTests {
@Bean
IClientConfig iClientConfig() {
// return new IClientConfig.Builder().s.build();
DefaultClientConfigImpl config = new DefaultClientConfigImpl();
config.setClientName("myapp");
return config;

@ -0,0 +1,159 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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 org.springframework.cloud.alibaba.nacos.ribbon;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.netflix.client.config.IClientConfig;
import org.junit.Test;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.springframework.cloud.alibaba.nacos.test.NacosMockTest.serviceInstance;
/**
* @author xiaojing
*/
public class NacosServerListTests {
@Test
@SuppressWarnings("unchecked")
public void testEmptyInstancesReturnsEmptyList() throws Exception {
NacosDiscoveryProperties nacosDiscoveryProperties = mock(
NacosDiscoveryProperties.class);
NamingService namingService = mock(NamingService.class);
when(nacosDiscoveryProperties.namingServiceInstance()).thenReturn(namingService);
when(namingService.selectInstances(anyString(), eq(true))).thenReturn(null);
NacosServerList serverList = new NacosServerList(nacosDiscoveryProperties);
List<NacosServer> servers = serverList.getInitialListOfServers();
assertThat(servers).isEmpty();
}
@Test
@SuppressWarnings("unchecked")
public void testGetServers() throws Exception {
ArrayList<Instance> instances = new ArrayList<>();
instances.add(serviceInstance("test-service", false, Collections.emptyMap()));
NacosDiscoveryProperties nacosDiscoveryProperties = mock(
NacosDiscoveryProperties.class);
NamingService namingService = mock(NamingService.class);
when(nacosDiscoveryProperties.namingServiceInstance()).thenReturn(namingService);
when(namingService.selectInstances(eq("test-service"), eq(true)))
.thenReturn(instances);
IClientConfig clientConfig = mock(IClientConfig.class);
when(clientConfig.getClientName()).thenReturn("test-service");
NacosServerList serverList = new NacosServerList(nacosDiscoveryProperties);
serverList.initWithNiwsConfig(clientConfig);
List<NacosServer> servers = serverList.getInitialListOfServers();
assertThat(servers).hasSize(1);
servers = serverList.getUpdatedListOfServers();
assertThat(servers).hasSize(1);
}
@Test
@SuppressWarnings("unchecked")
public void testGetServersWithInstanceStatus() throws Exception {
ArrayList<Instance> instances = new ArrayList<>();
HashMap<String, String> map1 = new HashMap<>();
map1.put("instanceNum", "1");
HashMap<String, String> map2 = new HashMap<>();
map2.put("instanceNum", "2");
instances.add(serviceInstance("test-service", false, map1));
instances.add(serviceInstance("test-service", true, map2));
NacosDiscoveryProperties nacosDiscoveryProperties = mock(
NacosDiscoveryProperties.class);
NamingService namingService = mock(NamingService.class);
when(nacosDiscoveryProperties.namingServiceInstance()).thenReturn(namingService);
when(namingService.selectInstances(eq("test-service"), eq(true)))
.thenReturn(instances.stream().filter(Instance::isHealthy)
.collect(Collectors.toList()));
IClientConfig clientConfig = mock(IClientConfig.class);
when(clientConfig.getClientName()).thenReturn("test-service");
NacosServerList serverList = new NacosServerList(nacosDiscoveryProperties);
serverList.initWithNiwsConfig(clientConfig);
List<NacosServer> servers = serverList.getInitialListOfServers();
assertThat(servers).hasSize(1);
NacosServer nacosServer = servers.get(0);
assertThat(nacosServer.getMetaInfo().getInstanceId())
.isEqualTo(instances.get(1).getInstanceId());
assertThat(nacosServer.getMetadata()).isEqualTo(map2);
assertThat(nacosServer.getInstance().isHealthy()).isEqualTo(true);
assertThat(nacosServer.getInstance().getServiceName()).isEqualTo("test-service");
assertThat(nacosServer.getInstance().getMetadata().get("instanceNum"))
.isEqualTo("2");
}
@Test
public void testUpdateServers() throws Exception {
ArrayList<Instance> instances = new ArrayList<>();
HashMap<String, String> map = new HashMap<>();
map.put("instanceNum", "1");
instances.add(serviceInstance("test-service", true, map));
NacosDiscoveryProperties nacosDiscoveryProperties = mock(
NacosDiscoveryProperties.class);
NamingService namingService = mock(NamingService.class);
when(nacosDiscoveryProperties.namingServiceInstance()).thenReturn(namingService);
when(namingService.selectInstances(eq("test-service"), eq(true)))
.thenReturn(instances.stream().filter(Instance::isHealthy)
.collect(Collectors.toList()));
IClientConfig clientConfig = mock(IClientConfig.class);
when(clientConfig.getClientName()).thenReturn("test-service");
NacosServerList serverList = new NacosServerList(nacosDiscoveryProperties);
serverList.initWithNiwsConfig(clientConfig);
List<NacosServer> servers = serverList.getUpdatedListOfServers();
assertThat(servers).hasSize(1);
assertThat(servers.get(0).getInstance().isHealthy()).isEqualTo(true);
assertThat(servers.get(0).getInstance().getMetadata().get("instanceNum"))
.isEqualTo("1");
}
}

@ -0,0 +1,36 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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 org.springframework.cloud.alibaba.nacos.test;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
/**
* @author xiaojing
*/
@Configuration
public class CommonTestConfig {
@Bean
@LoadBalanced
RestTemplate loadBalancedRestTemplate() {
return new RestTemplate();
}
}

@ -0,0 +1,49 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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 org.springframework.cloud.alibaba.nacos.test;
import java.util.Map;
import java.util.UUID;
import com.alibaba.nacos.api.naming.pojo.Instance;
/**
* @author xiaojing
*/
public class NacosMockTest {
public static Instance serviceInstance(String serviceName, boolean isHealthy,
Map<String, String> metadata) {
Instance instance = new Instance();
instance.setInstanceId(UUID.randomUUID().toString());
instance.setServiceName(serviceName);
instance.setHealthy(isHealthy);
instance.setMetadata(metadata);
return instance;
}
public static Instance serviceInstance(String serviceName, boolean isHealthy,
String host, int port, Map<String, String> metadata) {
Instance instance = new Instance();
instance.setIp(host);
instance.setPort(port);
instance.setServiceName(serviceName);
instance.setHealthy(isHealthy);
instance.setMetadata(metadata);
return instance;
}
}

@ -83,6 +83,13 @@
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<scope>provided</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>

@ -1,5 +1,8 @@
package org.springframework.cloud.alibaba.sentinel.datasource.config;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import org.springframework.cloud.alibaba.sentinel.datasource.RuleType;
import com.alibaba.csp.sentinel.datasource.AbstractDataSource;
@ -18,7 +21,9 @@ import com.fasterxml.jackson.annotation.JsonIgnore;
*/
public class AbstractDataSourceProperties {
@NotEmpty
private String dataType = "json";
@NotNull
private RuleType ruleType;
private String converterClass;
@JsonIgnore
@ -61,6 +66,7 @@ public class AbstractDataSourceProperties {
}
public void preCheck(String dataSourceName) {
}
public void postRegister(AbstractDataSource dataSource) {

@ -1,5 +1,7 @@
package org.springframework.cloud.alibaba.sentinel.datasource.config;
import javax.validation.constraints.NotEmpty;
import org.springframework.cloud.alibaba.sentinel.datasource.factorybean.ApolloDataSourceFactoryBean;
/**
@ -10,7 +12,9 @@ import org.springframework.cloud.alibaba.sentinel.datasource.factorybean.ApolloD
*/
public class ApolloDataSourceProperties extends AbstractDataSourceProperties {
@NotEmpty
private String namespaceName;
@NotEmpty
private String flowRulesKey;
private String defaultFlowRuleValue;

@ -2,6 +2,8 @@ package org.springframework.cloud.alibaba.sentinel.datasource.config;
import java.io.IOException;
import javax.validation.constraints.NotEmpty;
import org.springframework.cloud.alibaba.sentinel.datasource.factorybean.FileRefreshableDataSourceFactoryBean;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
@ -14,6 +16,7 @@ import org.springframework.util.StringUtils;
*/
public class FileDataSourceProperties extends AbstractDataSourceProperties {
@NotEmpty
private String file;
private String charset = "utf-8";
private long recommendRefreshMs = 3000L;

@ -1,5 +1,7 @@
package org.springframework.cloud.alibaba.sentinel.datasource.config;
import javax.validation.constraints.NotEmpty;
import org.springframework.cloud.alibaba.sentinel.datasource.RuleType;
import org.springframework.cloud.alibaba.sentinel.datasource.SentinelDataSourceConstants;
import org.springframework.cloud.alibaba.sentinel.datasource.factorybean.NacosDataSourceFactoryBean;
@ -15,7 +17,11 @@ import org.springframework.util.StringUtils;
public class NacosDataSourceProperties extends AbstractDataSourceProperties {
private String serverAddr;
@NotEmpty
private String groupId;
@NotEmpty
private String dataId;
// commercialized usage

@ -1,5 +1,7 @@
package org.springframework.cloud.alibaba.sentinel.datasource.config;
import javax.validation.constraints.NotEmpty;
import org.springframework.cloud.alibaba.sentinel.datasource.factorybean.ZookeeperDataSourceFactoryBean;
/**
@ -14,6 +16,7 @@ public class ZookeeperDataSourceProperties extends AbstractDataSourceProperties
super(ZookeeperDataSourceFactoryBean.class.getName());
}
@NotEmpty
private String serverAddr;
private String path;

@ -24,6 +24,7 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
import org.springframework.cloud.alibaba.sentinel.datasource.config.DataSourcePropertiesConfiguration;
import org.springframework.core.Ordered;
import org.springframework.validation.annotation.Validated;
import com.alibaba.csp.sentinel.config.SentinelConfig;
import com.alibaba.csp.sentinel.log.LogBase;
@ -36,6 +37,7 @@ import com.alibaba.csp.sentinel.transport.config.TransportConfig;
* @author <a href="mailto:fangjian0423@gmail.com">Jim</a>
*/
@ConfigurationProperties(prefix = SentinelConstants.PROPERTY_PREFIX)
@Validated
public class SentinelProperties {
/**

@ -28,6 +28,7 @@ import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.cloud.alibaba.sentinel.annotation.SentinelRestTemplate;
import org.springframework.context.ApplicationContext;
import org.springframework.core.type.StandardMethodMetadata;
import org.springframework.core.type.classreading.MethodMetadataReadingVisitor;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
@ -49,9 +50,16 @@ public class SentinelBeanPostProcessor implements MergedBeanDefinitionPostProces
public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition,
Class<?> beanType, String beanName) {
if (checkSentinelProtect(beanDefinition, beanType)) {
SentinelRestTemplate sentinelRestTemplate = ((StandardMethodMetadata) beanDefinition
SentinelRestTemplate sentinelRestTemplate;
if (beanDefinition.getSource() instanceof StandardMethodMetadata) {
sentinelRestTemplate = ((StandardMethodMetadata) beanDefinition
.getSource()).getIntrospectedMethod()
.getAnnotation(SentinelRestTemplate.class);
}
else {
sentinelRestTemplate = beanDefinition.getResolvedFactoryMethod()
.getAnnotation(SentinelRestTemplate.class);
}
cache.put(beanName, sentinelRestTemplate);
}
}
@ -59,11 +67,22 @@ public class SentinelBeanPostProcessor implements MergedBeanDefinitionPostProces
private boolean checkSentinelProtect(RootBeanDefinition beanDefinition,
Class<?> beanType) {
return beanType == RestTemplate.class
&& beanDefinition.getSource() instanceof StandardMethodMetadata
&& (checkStandardMethodMetadata(beanDefinition)
|| checkMethodMetadataReadingVisitor(beanDefinition));
}
private boolean checkStandardMethodMetadata(RootBeanDefinition beanDefinition) {
return beanDefinition.getSource() instanceof StandardMethodMetadata
&& ((StandardMethodMetadata) beanDefinition.getSource())
.isAnnotated(SentinelRestTemplate.class.getName());
}
private boolean checkMethodMetadataReadingVisitor(RootBeanDefinition beanDefinition) {
return beanDefinition.getSource() instanceof MethodMetadataReadingVisitor
&& ((MethodMetadataReadingVisitor) beanDefinition.getSource())
.isAnnotated(SentinelRestTemplate.class.getName());
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName)
throws BeansException {

Loading…
Cancel
Save