mirror of
https://gitee.com/mirrors/Spring-Cloud-Alibaba.git
synced 2021-06-26 13:25:11 +08:00
Merge remote-tracking branch 'upstream/1.x' into binder-dev-1.x
This commit is contained in:
commit
2ad46027cf
1
pom.xml
1
pom.xml
@ -86,6 +86,7 @@
|
||||
<module>spring-cloud-alibaba-dependencies</module>
|
||||
<module>spring-cloud-alibaba-sentinel</module>
|
||||
<module>spring-cloud-alibaba-sentinel-datasource</module>
|
||||
<module>spring-cloud-alibaba-sentinel-zuul</module>
|
||||
<module>spring-cloud-alibaba-nacos-config</module>
|
||||
<module>spring-cloud-alibaba-nacos-discovery</module>
|
||||
<module>spring-cloud-alibaba-fescar</module>
|
||||
|
@ -18,8 +18,8 @@
|
||||
<properties>
|
||||
<sentinel.version>1.4.2</sentinel.version>
|
||||
<oss.version>3.1.0</oss.version>
|
||||
<nacos.version>0.8.2</nacos.version>
|
||||
<fescar.version>0.1.3</fescar.version>
|
||||
<nacos.version>0.9.1</nacos.version>
|
||||
<fescar.version>0.2.3</fescar.version>
|
||||
<acm.version>1.0.8</acm.version>
|
||||
<ans.version>1.0.1</ans.version>
|
||||
<aliyun.sdk.version>4.0.1</aliyun.sdk.version>
|
||||
@ -29,7 +29,6 @@
|
||||
<schedulerX.client.version>2.1.6</schedulerX.client.version>
|
||||
<aliyun.java.sdk.dysmsapi>1.1.0</aliyun.java.sdk.dysmsapi>
|
||||
<aliyun.sdk.mns>1.1.8</aliyun.sdk.mns>
|
||||
<aliyun.java.sdk.dysmsapi>1.1.0</aliyun.java.sdk.dysmsapi>
|
||||
</properties>
|
||||
|
||||
<dependencyManagement>
|
||||
@ -134,6 +133,11 @@
|
||||
<artifactId>sentinel-web-servlet</artifactId>
|
||||
<version>${sentinel.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.alibaba.csp</groupId>
|
||||
<artifactId>sentinel-zuul-adapter</artifactId>
|
||||
<version>${sentinel.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.alibaba.csp</groupId>
|
||||
<artifactId>sentinel-transport-simple-http</artifactId>
|
||||
|
@ -29,11 +29,6 @@
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-alicloud-sms</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>alibaba.com</groupId>
|
||||
<artifactId>env-extension</artifactId>
|
||||
<version>0.1.2.BUILD-SNAPSHOT</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.code.gson</groupId>
|
||||
<artifactId>gson</artifactId>
|
||||
@ -47,6 +42,14 @@
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-deploy-plugin</artifactId>
|
||||
<version>${maven-deploy-plugin.version}</version>
|
||||
<configuration>
|
||||
<skip>true</skip>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
@ -1,11 +1,9 @@
|
||||
package org.springframework.cloud.alibaba.cloud.example;
|
||||
|
||||
import org.springframework.alicloud.env.extension.ImportExtraConfig;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
@ImportExtraConfig(name = "/Users/toava/sms.properties")
|
||||
public class SmsApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
@ -71,6 +71,18 @@
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.powermock</groupId>
|
||||
<artifactId>powermock-module-junit4</artifactId>
|
||||
<version>1.7.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.powermock</groupId>
|
||||
<artifactId>powermock-api-mockito</artifactId>
|
||||
<version>1.7.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
||||
|
@ -1,94 +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.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
|
||||
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||
import org.springframework.cloud.alibaba.nacos.client.NacosPropertySourceLocator;
|
||||
import org.springframework.cloud.alibaba.nacos.refresh.NacosRefreshProperties;
|
||||
import org.springframework.cloud.context.refresh.ContextRefresher;
|
||||
import org.springframework.cloud.context.scope.refresh.RefreshScope;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.env.Environment;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* @author xiaojing
|
||||
*/
|
||||
public class NacosConfigAutoConfigurationTests {
|
||||
|
||||
private ConfigurableApplicationContext context;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
this.context = new SpringApplicationBuilder(
|
||||
NacosConfigBootstrapConfiguration.class,
|
||||
NacosConfigAutoConfiguration.class, TestConfiguration.class).web(false)
|
||||
.run("--spring.cloud.nacos.config.name=myapp",
|
||||
"--spring.cloud.config.enabled=true",
|
||||
"--spring.cloud.nacos.config.server-addr=127.0.0.1:8848",
|
||||
"--spring.cloud.nacos.config.prefix=test");
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
if (this.context != null) {
|
||||
this.context.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNacosConfigProperties() {
|
||||
NacosConfigProperties nacosConfigProperties = this.context.getParent()
|
||||
.getBean(NacosConfigProperties.class);
|
||||
assertThat(nacosConfigProperties.getFileExtension()).isEqualTo("properties");
|
||||
assertThat(nacosConfigProperties.getPrefix()).isEqualTo("test");
|
||||
assertThat(nacosConfigProperties.getName()).isEqualTo("myapp");
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNacosRefreshProperties() {
|
||||
|
||||
NacosRefreshProperties nacosRefreshProperties = this.context
|
||||
.getBean(NacosRefreshProperties.class);
|
||||
assertThat(nacosRefreshProperties.isEnabled()).isEqualTo(true);
|
||||
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@AutoConfigureBefore(NacosConfigAutoConfiguration.class)
|
||||
static class TestConfiguration {
|
||||
|
||||
@Autowired
|
||||
ConfigurableApplicationContext context;
|
||||
|
||||
@Bean
|
||||
ContextRefresher contextRefresher() {
|
||||
return new ContextRefresher(context, new RefreshScope());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -1,81 +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 java.lang.reflect.Field;
|
||||
|
||||
import com.alibaba.nacos.api.config.ConfigService;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||
import org.springframework.cloud.alibaba.nacos.client.NacosPropertySourceLocator;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.util.ReflectionUtils;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* @author xiaojing
|
||||
*/
|
||||
public class NacosConfigBootstrapConfigurationTests {
|
||||
|
||||
private ConfigurableApplicationContext context;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
this.context = new SpringApplicationBuilder(
|
||||
NacosConfigBootstrapConfiguration.class).web(false).run(
|
||||
"--spring.cloud.nacos.config.name=true",
|
||||
"--spring.cloud.config.enabled=true",
|
||||
"--spring.cloud.nacos.config.server-addr=127.0.0.1:8848",
|
||||
"--spring.cloud.nacos.config.prefix=myapp");
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
if (this.context != null) {
|
||||
this.context.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNacosPropertySourceLocator() {
|
||||
|
||||
NacosPropertySourceLocator locator = this.context
|
||||
.getBean(NacosPropertySourceLocator.class);
|
||||
Environment environment = this.context.getEnvironment();
|
||||
try {
|
||||
locator.locate(environment);
|
||||
}
|
||||
catch (Exception e) {
|
||||
|
||||
}
|
||||
|
||||
Field nacosConfigPropertiesField = ReflectionUtils
|
||||
.findField(NacosPropertySourceLocator.class, "nacosConfigProperties");
|
||||
nacosConfigPropertiesField.setAccessible(true);
|
||||
|
||||
NacosConfigProperties configService = (NacosConfigProperties) ReflectionUtils
|
||||
.getField(nacosConfigPropertiesField, locator);
|
||||
|
||||
assertThat(configService).isNotNull();
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,153 @@
|
||||
/*
|
||||
* 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 static org.junit.Assert.assertNotNull;
|
||||
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE;
|
||||
|
||||
import java.lang.reflect.InvocationHandler;
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
import com.alibaba.nacos.client.config.NacosConfigService;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.powermock.api.mockito.PowerMockito;
|
||||
import org.powermock.api.support.MethodProxy;
|
||||
import org.powermock.core.classloader.annotations.PowerMockIgnore;
|
||||
import org.powermock.core.classloader.annotations.PrepareForTest;
|
||||
import org.powermock.modules.junit4.PowerMockRunner;
|
||||
import org.powermock.modules.junit4.PowerMockRunnerDelegate;
|
||||
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.client.NacosPropertySourceLocator;
|
||||
import org.springframework.cloud.alibaba.nacos.endpoint.NacosConfigEndpointAutoConfiguration;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
/**
|
||||
* @author xiaojing
|
||||
*/
|
||||
|
||||
@RunWith(PowerMockRunner.class)
|
||||
@PowerMockIgnore("javax.management.*")
|
||||
@PowerMockRunnerDelegate(SpringRunner.class)
|
||||
@PrepareForTest({ NacosConfigService.class })
|
||||
@SpringBootTest(classes = NacosConfigurationExtConfigTests.TestConfig.class, properties = {
|
||||
"spring.application.name=myTestService1", "spring.profiles.active=dev,test",
|
||||
"spring.cloud.nacos.config.server-addr=127.0.0.1:8848",
|
||||
"spring.cloud.nacos.config.encode=utf-8",
|
||||
"spring.cloud.nacos.config.timeout=1000",
|
||||
"spring.cloud.nacos.config.file-extension=properties",
|
||||
|
||||
"spring.cloud.nacos.config.ext-config[0].data-id=ext-config-common01.properties",
|
||||
|
||||
"spring.cloud.nacos.config.ext-config[1].data-id=ext-config-common02.properties",
|
||||
"spring.cloud.nacos.config.ext-config[1].group=GLOBAL_GROUP",
|
||||
|
||||
"spring.cloud.nacos.config.shared-dataids=common1.properties,common2.properties",
|
||||
|
||||
"spring.cloud.nacos.config.accessKey=test-accessKey",
|
||||
"spring.cloud.nacos.config.secretKey=test-secretKey" }, webEnvironment = NONE)
|
||||
public class NacosConfigurationExtConfigTests {
|
||||
|
||||
static {
|
||||
|
||||
try {
|
||||
// when(any(ConfigService.class).getConfig(eq("test-name.properties"),
|
||||
// eq("test-group"), any())).thenReturn("user.name=hello");
|
||||
|
||||
Method method = PowerMockito.method(NacosConfigService.class, "getConfig",
|
||||
String.class, String.class, long.class);
|
||||
MethodProxy.proxy(method, new InvocationHandler() {
|
||||
@Override
|
||||
public Object invoke(Object proxy, Method method, Object[] args)
|
||||
throws Throwable {
|
||||
|
||||
if ("test-name.properties".equals(args[0])
|
||||
&& "DEFAULT_GROUP".equals(args[1])) {
|
||||
return "user.name=hello\nuser.age=12";
|
||||
}
|
||||
|
||||
if ("test-name-dev.properties".equals(args[0])
|
||||
&& "DEFAULT_GROUP".equals(args[1])) {
|
||||
return "user.name=dev";
|
||||
}
|
||||
|
||||
if ("ext-config-common01.properties".equals(args[0])
|
||||
&& "DEFAULT_GROUP".equals(args[1])) {
|
||||
return "test-ext-config1=config1\ntest-ext-config2=config1";
|
||||
}
|
||||
if ("ext-config-common02.properties".equals(args[0])
|
||||
&& "GLOBAL_GROUP".equals(args[1])) {
|
||||
return "test-ext-config2=config2";
|
||||
}
|
||||
|
||||
if ("common1.properties".equals(args[0])
|
||||
&& "DEFAULT_GROUP".equals(args[1])) {
|
||||
return "test-common1=common1\ntest-common2=common1";
|
||||
}
|
||||
|
||||
if ("common2.properties".equals(args[0])
|
||||
&& "DEFAULT_GROUP".equals(args[1])) {
|
||||
return "test-common2=common2";
|
||||
}
|
||||
|
||||
return "";
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
catch (Exception ignore) {
|
||||
ignore.printStackTrace();
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@Autowired
|
||||
private Environment environment;
|
||||
|
||||
@Autowired
|
||||
private NacosPropertySourceLocator locator;
|
||||
|
||||
@Autowired
|
||||
private NacosConfigProperties properties;
|
||||
|
||||
@Test
|
||||
public void contextLoads() throws Exception {
|
||||
|
||||
assertNotNull("NacosPropertySourceLocator was not created", locator);
|
||||
assertNotNull("NacosConfigProperties was not created", properties);
|
||||
|
||||
Assert.assertEquals(environment.getProperty("test-ext-config1"), "config1");
|
||||
Assert.assertEquals(environment.getProperty("test-ext-config2"), "config2");
|
||||
Assert.assertEquals(environment.getProperty("test-common1"), "common1");
|
||||
Assert.assertEquals(environment.getProperty("test-common2"), "common2");
|
||||
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@EnableAutoConfiguration
|
||||
@ImportAutoConfiguration({ NacosConfigEndpointAutoConfiguration.class,
|
||||
NacosConfigAutoConfiguration.class, NacosConfigBootstrapConfiguration.class })
|
||||
public static class TestConfig {
|
||||
}
|
||||
}
|
@ -0,0 +1,261 @@
|
||||
/*
|
||||
* 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 static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE;
|
||||
|
||||
import java.lang.reflect.InvocationHandler;
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import com.alibaba.nacos.client.config.NacosConfigService;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.powermock.api.mockito.PowerMockito;
|
||||
import org.powermock.api.support.MethodProxy;
|
||||
import org.powermock.core.classloader.annotations.PowerMockIgnore;
|
||||
import org.powermock.core.classloader.annotations.PrepareForTest;
|
||||
import org.powermock.modules.junit4.PowerMockRunner;
|
||||
import org.powermock.modules.junit4.PowerMockRunnerDelegate;
|
||||
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.client.NacosPropertySourceLocator;
|
||||
import org.springframework.cloud.alibaba.nacos.endpoint.NacosConfigEndpoint;
|
||||
import org.springframework.cloud.alibaba.nacos.endpoint.NacosConfigEndpointAutoConfiguration;
|
||||
import org.springframework.cloud.alibaba.nacos.refresh.NacosRefreshHistory;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
/**
|
||||
* @author xiaojing
|
||||
*/
|
||||
|
||||
@RunWith(PowerMockRunner.class)
|
||||
@PowerMockIgnore("javax.management.*")
|
||||
@PowerMockRunnerDelegate(SpringRunner.class)
|
||||
@PrepareForTest({ NacosConfigService.class })
|
||||
@SpringBootTest(classes = NacosConfigurationTests.TestConfig.class, properties = {
|
||||
"spring.application.name=myTestService1", "spring.profiles.active=dev,test",
|
||||
"spring.cloud.nacos.config.server-addr=127.0.0.1:8848",
|
||||
"spring.cloud.nacos.config.endpoint=test-endpoint",
|
||||
"spring.cloud.nacos.config.namespace=test-namespace",
|
||||
"spring.cloud.nacos.config.encode=utf-8",
|
||||
"spring.cloud.nacos.config.timeout=1000",
|
||||
"spring.cloud.nacos.config.group=test-group",
|
||||
"spring.cloud.nacos.config.name=test-name",
|
||||
"spring.cloud.nacos.config.cluster-name=test-cluster",
|
||||
"spring.cloud.nacos.config.file-extension=properties",
|
||||
"spring.cloud.nacos.config.contextPath=test-contextpath",
|
||||
|
||||
"spring.cloud.nacos.config.ext-config[0].data-id=ext-config-common01.properties",
|
||||
|
||||
"spring.cloud.nacos.config.ext-config[1].data-id=ext-config-common02.properties",
|
||||
"spring.cloud.nacos.config.ext-config[1].group=GLOBAL_GROUP",
|
||||
|
||||
"spring.cloud.nacos.config.shared-dataids=common1.properties,common2.properties",
|
||||
|
||||
"spring.cloud.nacos.config.accessKey=test-accessKey",
|
||||
"spring.cloud.nacos.config.secretKey=test-secretKey" }, webEnvironment = NONE)
|
||||
public class NacosConfigurationTests {
|
||||
|
||||
static {
|
||||
|
||||
try {
|
||||
// when(any(ConfigService.class).getConfig(eq("test-name.properties"),
|
||||
// eq("test-group"), any())).thenReturn("user.name=hello");
|
||||
|
||||
Method method = PowerMockito.method(NacosConfigService.class, "getConfig",
|
||||
String.class, String.class, long.class);
|
||||
MethodProxy.proxy(method, new InvocationHandler() {
|
||||
@Override
|
||||
public Object invoke(Object proxy, Method method, Object[] args)
|
||||
throws Throwable {
|
||||
|
||||
if ("test-name.properties".equals(args[0])
|
||||
&& "test-group".equals(args[1])) {
|
||||
return "user.name=hello\nuser.age=12";
|
||||
}
|
||||
|
||||
if ("test-name-dev.properties".equals(args[0])
|
||||
&& "test-group".equals(args[1])) {
|
||||
return "user.name=dev";
|
||||
}
|
||||
|
||||
if ("ext-config-common01.properties".equals(args[0])
|
||||
&& "DEFAULT_GROUP".equals(args[1])) {
|
||||
return "test-ext-config1=config1\ntest-ext-config2=config1";
|
||||
}
|
||||
if ("ext-config-common02.properties".equals(args[0])
|
||||
&& "GLOBAL_GROUP".equals(args[1])) {
|
||||
return "test-ext-config2=config2";
|
||||
}
|
||||
|
||||
if ("common1.properties".equals(args[0])
|
||||
&& "DEFAULT_GROUP".equals(args[1])) {
|
||||
return "test-common1=common1\ntest-common2=common1";
|
||||
}
|
||||
|
||||
if ("common2.properties".equals(args[0])
|
||||
&& "DEFAULT_GROUP".equals(args[1])) {
|
||||
return "test-common2=common2";
|
||||
}
|
||||
|
||||
return "";
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
catch (Exception ignore) {
|
||||
ignore.printStackTrace();
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@Autowired
|
||||
private Environment environment;
|
||||
|
||||
@Autowired
|
||||
private NacosPropertySourceLocator locator;
|
||||
|
||||
@Autowired
|
||||
private NacosConfigProperties properties;
|
||||
|
||||
@Autowired
|
||||
private NacosRefreshHistory refreshHistory;
|
||||
|
||||
@Test
|
||||
public void contextLoads() throws Exception {
|
||||
|
||||
assertNotNull("NacosPropertySourceLocator was not created", locator);
|
||||
assertNotNull("NacosConfigProperties was not created", properties);
|
||||
|
||||
checkoutNacosConfigServerAddr();
|
||||
checkoutNacosConfigEndpoint();
|
||||
checkoutNacosConfigNamespace();
|
||||
checkoutNacosConfigClusterName();
|
||||
checkoutNacosConfigAccessKey();
|
||||
checkoutNacosConfigSecrectKey();
|
||||
checkoutNacosConfigName();
|
||||
checkoutNacosConfigGroup();
|
||||
checkoutNacosConfigContextPath();
|
||||
checkoutNacosConfigFileExtension();
|
||||
checkoutNacosConfigTimeout();
|
||||
checkoutNacosConfigEncode();
|
||||
checkoutNacosConfigProfiles();
|
||||
|
||||
checkoutEndpoint();
|
||||
checkoutDataLoad();
|
||||
|
||||
}
|
||||
|
||||
private void checkoutNacosConfigServerAddr() {
|
||||
assertEquals("NacosConfigProperties server address is wrong", "127.0.0.1:8848",
|
||||
properties.getServerAddr());
|
||||
|
||||
}
|
||||
|
||||
private void checkoutNacosConfigEndpoint() {
|
||||
assertEquals("NacosConfigProperties endpoint is wrong", "test-endpoint",
|
||||
properties.getEndpoint());
|
||||
|
||||
}
|
||||
|
||||
private void checkoutNacosConfigNamespace() {
|
||||
assertEquals("NacosConfigProperties namespace is wrong", "test-namespace",
|
||||
properties.getNamespace());
|
||||
|
||||
}
|
||||
|
||||
private void checkoutNacosConfigClusterName() {
|
||||
assertEquals("NacosConfigProperties' cluster is wrong", "test-cluster",
|
||||
properties.getClusterName());
|
||||
}
|
||||
|
||||
private void checkoutNacosConfigAccessKey() {
|
||||
assertEquals("NacosConfigProperties' is access key is wrong", "test-accessKey",
|
||||
properties.getAccessKey());
|
||||
}
|
||||
|
||||
private void checkoutNacosConfigSecrectKey() {
|
||||
assertEquals("NacosConfigProperties' is secret key is wrong", "test-secretKey",
|
||||
properties.getSecretKey());
|
||||
}
|
||||
|
||||
private void checkoutNacosConfigContextPath() {
|
||||
assertEquals("NacosConfigProperties' context path is wrong", "test-contextpath",
|
||||
properties.getContextPath());
|
||||
}
|
||||
|
||||
private void checkoutNacosConfigName() {
|
||||
assertEquals("NacosConfigProperties' name is wrong", "test-name",
|
||||
properties.getName());
|
||||
}
|
||||
|
||||
private void checkoutNacosConfigGroup() {
|
||||
assertEquals("NacosConfigProperties' group is wrong", "test-group",
|
||||
properties.getGroup());
|
||||
}
|
||||
|
||||
private void checkoutNacosConfigFileExtension() {
|
||||
assertEquals("NacosConfigProperties' file extension is wrong", "properties",
|
||||
properties.getFileExtension());
|
||||
}
|
||||
|
||||
private void checkoutNacosConfigTimeout() {
|
||||
assertEquals("NacosConfigProperties' timeout is wrong", 1000,
|
||||
properties.getTimeout());
|
||||
}
|
||||
|
||||
private void checkoutNacosConfigEncode() {
|
||||
assertEquals("NacosConfigProperties' encode is wrong", "utf-8",
|
||||
properties.getEncode());
|
||||
}
|
||||
|
||||
private void checkoutDataLoad() {
|
||||
|
||||
Assert.assertEquals(environment.getProperty("user.name"), "dev");
|
||||
Assert.assertEquals(environment.getProperty("user.age"), "12");
|
||||
}
|
||||
|
||||
private void checkoutNacosConfigProfiles() {
|
||||
assertEquals("NacosConfigProperties' profiles is wrong",
|
||||
new String[] { "dev", "test" }, properties.getActiveProfiles());
|
||||
}
|
||||
|
||||
private void checkoutEndpoint() throws Exception {
|
||||
NacosConfigEndpoint nacosConfigEndpoint = new NacosConfigEndpoint(properties,
|
||||
refreshHistory);
|
||||
Map<String, Object> map = nacosConfigEndpoint.invoke();
|
||||
assertEquals(map.get("NacosConfigProperties"), properties);
|
||||
assertEquals(map.get("RefreshHistory"), refreshHistory.getRecords());
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@EnableAutoConfiguration
|
||||
@ImportAutoConfiguration({ NacosConfigEndpointAutoConfiguration.class,
|
||||
NacosConfigAutoConfiguration.class, NacosConfigBootstrapConfiguration.class })
|
||||
public static class TestConfig {
|
||||
}
|
||||
}
|
@ -0,0 +1,98 @@
|
||||
/*
|
||||
* Copyright (C) 2019 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 static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE;
|
||||
|
||||
import java.lang.reflect.InvocationHandler;
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
import com.alibaba.nacos.client.config.NacosConfigService;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.powermock.api.mockito.PowerMockito;
|
||||
import org.powermock.api.support.MethodProxy;
|
||||
import org.powermock.core.classloader.annotations.PowerMockIgnore;
|
||||
import org.powermock.core.classloader.annotations.PrepareForTest;
|
||||
import org.powermock.modules.junit4.PowerMockRunner;
|
||||
import org.powermock.modules.junit4.PowerMockRunnerDelegate;
|
||||
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.endpoint.NacosConfigEndpointAutoConfiguration;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
/**
|
||||
* @author xiaojing
|
||||
*/
|
||||
|
||||
@RunWith(PowerMockRunner.class)
|
||||
@PowerMockIgnore("javax.management.*")
|
||||
@PowerMockRunnerDelegate(SpringRunner.class)
|
||||
@PrepareForTest({ NacosConfigService.class })
|
||||
@SpringBootTest(classes = NacosFileExtensionTest.TestConfig.class, properties = {
|
||||
"spring.application.name=test-name",
|
||||
"spring.cloud.nacos.config.server-addr=127.0.0.1:8848",
|
||||
"spring.cloud.nacos.config.file-extension=yaml" }, webEnvironment = NONE)
|
||||
public class NacosFileExtensionTest {
|
||||
|
||||
static {
|
||||
|
||||
try {
|
||||
Method method = PowerMockito.method(NacosConfigService.class, "getConfig",
|
||||
String.class, String.class, long.class);
|
||||
MethodProxy.proxy(method, new InvocationHandler() {
|
||||
@Override
|
||||
public Object invoke(Object proxy, Method method, Object[] args)
|
||||
throws Throwable {
|
||||
if ("test-name.yaml".equals(args[0])
|
||||
&& "DEFAULT_GROUP".equals(args[1])) {
|
||||
return "user:\n name: hello\n age: 12";
|
||||
}
|
||||
return "";
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
catch (Exception ignore) {
|
||||
ignore.printStackTrace();
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@Autowired
|
||||
private Environment environment;
|
||||
|
||||
@Test
|
||||
public void contextLoads() throws Exception {
|
||||
|
||||
Assert.assertEquals(environment.getProperty("user.name"), "hello");
|
||||
Assert.assertEquals(environment.getProperty("user.age"), "12");
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@EnableAutoConfiguration
|
||||
@ImportAutoConfiguration({ NacosConfigEndpointAutoConfiguration.class,
|
||||
NacosConfigAutoConfiguration.class, NacosConfigBootstrapConfiguration.class })
|
||||
public static class TestConfig {
|
||||
}
|
||||
}
|
@ -0,0 +1,141 @@
|
||||
/*
|
||||
* 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.endpoint;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE;
|
||||
|
||||
import java.lang.reflect.InvocationHandler;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import com.alibaba.nacos.client.config.NacosConfigService;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.powermock.api.mockito.PowerMockito;
|
||||
import org.powermock.api.support.MethodProxy;
|
||||
import org.powermock.core.classloader.annotations.PowerMockIgnore;
|
||||
import org.powermock.core.classloader.annotations.PrepareForTest;
|
||||
import org.powermock.modules.junit4.PowerMockRunner;
|
||||
import org.powermock.modules.junit4.PowerMockRunnerDelegate;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.actuate.health.Health.Builder;
|
||||
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.NacosConfigAutoConfiguration;
|
||||
import org.springframework.cloud.alibaba.nacos.NacosConfigBootstrapConfiguration;
|
||||
import org.springframework.cloud.alibaba.nacos.NacosConfigProperties;
|
||||
import org.springframework.cloud.alibaba.nacos.refresh.NacosRefreshHistory;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
/**
|
||||
* @author xiaojing
|
||||
*/
|
||||
|
||||
@RunWith(PowerMockRunner.class)
|
||||
@PowerMockIgnore("javax.management.*")
|
||||
@PowerMockRunnerDelegate(SpringRunner.class)
|
||||
@PrepareForTest({ NacosConfigService.class })
|
||||
@SpringBootTest(classes = NacosConfigEndpointTests.TestConfig.class, properties = {
|
||||
"spring.application.name=test-name",
|
||||
"spring.cloud.nacos.config.server-addr=127.0.0.1:8848",
|
||||
"spring.cloud.nacos.config.file-extension=properties" }, webEnvironment = NONE)
|
||||
public class NacosConfigEndpointTests {
|
||||
|
||||
static {
|
||||
|
||||
try {
|
||||
|
||||
Method method = PowerMockito.method(NacosConfigService.class, "getConfig",
|
||||
String.class, String.class, long.class);
|
||||
MethodProxy.proxy(method, new InvocationHandler() {
|
||||
@Override
|
||||
public Object invoke(Object proxy, Method method, Object[] args)
|
||||
throws Throwable {
|
||||
|
||||
if ("test-name.properties".equals(args[0])
|
||||
&& "DEFAULT_GROUP".equals(args[1])) {
|
||||
return "user.name=hello\nuser.age=12";
|
||||
}
|
||||
return "";
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
catch (Exception ignore) {
|
||||
ignore.printStackTrace();
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@Autowired
|
||||
private NacosConfigProperties properties;
|
||||
|
||||
@Autowired
|
||||
private NacosRefreshHistory refreshHistory;
|
||||
|
||||
@Test
|
||||
public void contextLoads() throws Exception {
|
||||
|
||||
checkoutEndpoint();
|
||||
checkoutAcmHealthIndicator();
|
||||
|
||||
}
|
||||
|
||||
private void checkoutAcmHealthIndicator() {
|
||||
try {
|
||||
Builder builder = new Builder();
|
||||
|
||||
NacosConfigHealthIndicator healthIndicator = new NacosConfigHealthIndicator(
|
||||
properties, properties.configServiceInstance());
|
||||
healthIndicator.doHealthCheck(builder);
|
||||
|
||||
Builder builder1 = new Builder();
|
||||
List<String> dataIds = new ArrayList<>();
|
||||
dataIds.add("test-name.properties");
|
||||
builder1.up().withDetail("dataIds", dataIds);
|
||||
|
||||
Assert.assertTrue(builder.build().equals(builder1.build()));
|
||||
|
||||
}
|
||||
catch (Exception ignoreE) {
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private void checkoutEndpoint() throws Exception {
|
||||
NacosConfigEndpoint endpoint = new NacosConfigEndpoint(properties,
|
||||
refreshHistory);
|
||||
Map<String, Object> map = endpoint.invoke();
|
||||
assertEquals(map.get("NacosConfigProperties"), properties);
|
||||
assertEquals(map.get("RefreshHistory"), refreshHistory.getRecords());
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@EnableAutoConfiguration
|
||||
@ImportAutoConfiguration({ NacosConfigEndpointAutoConfiguration.class,
|
||||
NacosConfigAutoConfiguration.class, NacosConfigBootstrapConfiguration.class })
|
||||
public static class TestConfig {
|
||||
}
|
||||
}
|
@ -30,6 +30,7 @@ import org.springframework.cloud.alibaba.nacos.discovery.NacosDiscoveryClientAut
|
||||
import org.springframework.cloud.alibaba.nacos.registry.NacosAutoServiceRegistration;
|
||||
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;
|
||||
@ -46,7 +47,8 @@ import org.springframework.context.annotation.Configuration;
|
||||
@ConditionalOnClass(name = "org.springframework.boot.context.embedded.EmbeddedServletContainerInitializedEvent")
|
||||
@ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true)
|
||||
@AutoConfigureBefore(NacosDiscoveryClientAutoConfiguration.class)
|
||||
@AutoConfigureAfter(AutoServiceRegistrationConfiguration.class)
|
||||
@AutoConfigureAfter({ AutoServiceRegistrationConfiguration.class,
|
||||
AutoServiceRegistrationAutoConfiguration.class })
|
||||
public class NacosDiscoveryAutoConfiguration {
|
||||
|
||||
@Bean
|
||||
|
44
spring-cloud-alibaba-sentinel-zuul/pom.xml
Normal file
44
spring-cloud-alibaba-sentinel-zuul/pom.xml
Normal file
@ -0,0 +1,44 @@
|
||||
<?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-alibaba</artifactId>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<version>0.1.2.BUILD-SNAPSHOT</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-alibaba-sentinel-zuul</artifactId>
|
||||
<name>Spring Cloud Alibaba Sentinel Zuul</name>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.alibaba.csp</groupId>
|
||||
<artifactId>sentinel-zuul-adapter</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-configuration-processor</artifactId>
|
||||
<scope>provided</scope>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.mockito</groupId>
|
||||
<artifactId>mockito-core</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
@ -0,0 +1,114 @@
|
||||
/*
|
||||
* Copyright 1999-2018 Alibaba Group Holding Ltd.
|
||||
*
|
||||
* 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.sentinel.zuul;
|
||||
|
||||
import static org.springframework.cloud.alibaba.sentinel.zuul.SentinelZuulAutoConfiguration.PREFIX;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.cloud.alibaba.sentinel.zuul.handler.FallBackProviderHandler;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.env.Environment;
|
||||
|
||||
import com.alibaba.csp.sentinel.adapter.zuul.fallback.DefaultRequestOriginParser;
|
||||
import com.alibaba.csp.sentinel.adapter.zuul.fallback.DefaultUrlCleaner;
|
||||
import com.alibaba.csp.sentinel.adapter.zuul.fallback.RequestOriginParser;
|
||||
import com.alibaba.csp.sentinel.adapter.zuul.fallback.UrlCleaner;
|
||||
import com.alibaba.csp.sentinel.adapter.zuul.filters.SentinelErrorFilter;
|
||||
import com.alibaba.csp.sentinel.adapter.zuul.filters.SentinelPostFilter;
|
||||
import com.alibaba.csp.sentinel.adapter.zuul.filters.SentinelPreFilter;
|
||||
import com.alibaba.csp.sentinel.adapter.zuul.properties.SentinelZuulProperties;
|
||||
import com.alibaba.csp.sentinel.util.StringUtil;
|
||||
|
||||
import com.netflix.zuul.ZuulFilter;
|
||||
|
||||
/**
|
||||
* Sentinel Spring Cloud Zuul AutoConfiguration
|
||||
*
|
||||
* @author tiger
|
||||
*/
|
||||
@Configuration
|
||||
@ConditionalOnProperty(prefix = PREFIX, name = "enabled", havingValue = "true", matchIfMissing = true)
|
||||
public class SentinelZuulAutoConfiguration {
|
||||
|
||||
@Autowired
|
||||
private Environment environment;
|
||||
|
||||
public static final String PREFIX = "spring.cloud.sentinel.zuul";
|
||||
|
||||
@Bean
|
||||
public SentinelZuulProperties sentinelZuulProperties() {
|
||||
SentinelZuulProperties properties = new SentinelZuulProperties();
|
||||
String enabledStr = environment.getProperty(PREFIX + "." + "enabled");
|
||||
String preOrderStr = environment.getProperty(PREFIX + "." + "order.pre");
|
||||
String postOrderStr = environment.getProperty(PREFIX + "." + "order.post");
|
||||
String errorOrderStr = environment.getProperty(PREFIX + "." + "order.error");
|
||||
if (StringUtil.isNotEmpty(enabledStr)) {
|
||||
Boolean enabled = Boolean.valueOf(enabledStr);
|
||||
properties.setEnabled(enabled);
|
||||
}
|
||||
if (StringUtil.isNotEmpty(preOrderStr)) {
|
||||
properties.getOrder().setPre(Integer.parseInt(preOrderStr));
|
||||
}
|
||||
if (StringUtil.isNotEmpty(postOrderStr)) {
|
||||
properties.getOrder().setPost(Integer.parseInt(postOrderStr));
|
||||
}
|
||||
if (StringUtil.isNotEmpty(errorOrderStr)) {
|
||||
properties.getOrder().setError(Integer.parseInt(errorOrderStr));
|
||||
}
|
||||
return properties;
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean(UrlCleaner.class)
|
||||
public UrlCleaner urlCleaner() {
|
||||
return new DefaultUrlCleaner();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean(RequestOriginParser.class)
|
||||
public RequestOriginParser requestOriginParser() {
|
||||
return new DefaultRequestOriginParser();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ZuulFilter preFilter(SentinelZuulProperties sentinelZuulProperties,
|
||||
UrlCleaner urlCleaner, RequestOriginParser requestOriginParser) {
|
||||
return new SentinelPreFilter(sentinelZuulProperties, urlCleaner,
|
||||
requestOriginParser);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ZuulFilter postFilter(SentinelZuulProperties sentinelZuulProperties) {
|
||||
return new SentinelPostFilter(sentinelZuulProperties);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ZuulFilter errorFilter(SentinelZuulProperties sentinelZuulProperties) {
|
||||
return new SentinelErrorFilter(sentinelZuulProperties);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public FallBackProviderHandler fallBackProviderListener(
|
||||
DefaultListableBeanFactory beanFactory) {
|
||||
return new FallBackProviderHandler(beanFactory);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,45 @@
|
||||
package org.springframework.cloud.alibaba.sentinel.zuul.handler;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.commons.collections.MapUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.SmartInitializingSingleton;
|
||||
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
|
||||
|
||||
import com.alibaba.csp.sentinel.adapter.zuul.fallback.DefaultBlockFallbackProvider;
|
||||
import com.alibaba.csp.sentinel.adapter.zuul.fallback.ZuulBlockFallbackManager;
|
||||
import com.alibaba.csp.sentinel.adapter.zuul.fallback.ZuulBlockFallbackProvider;
|
||||
|
||||
/**
|
||||
* @author tiger
|
||||
*/
|
||||
public class FallBackProviderHandler implements SmartInitializingSingleton {
|
||||
|
||||
private static final Logger logger = LoggerFactory
|
||||
.getLogger(FallBackProviderHandler.class);
|
||||
|
||||
private final DefaultListableBeanFactory beanFactory;
|
||||
|
||||
public FallBackProviderHandler(DefaultListableBeanFactory beanFactory) {
|
||||
this.beanFactory = beanFactory;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterSingletonsInstantiated() {
|
||||
Map<String, ZuulBlockFallbackProvider> providerMap = beanFactory
|
||||
.getBeansOfType(ZuulBlockFallbackProvider.class);
|
||||
if (MapUtils.isNotEmpty(providerMap)) {
|
||||
for (String k : providerMap.keySet()) {
|
||||
logger.info("[Sentinel Zuul] Register provider name:{}, instance: {}", k,
|
||||
providerMap.get(k));
|
||||
ZuulBlockFallbackManager.registerProvider(providerMap.get(k));
|
||||
}
|
||||
}
|
||||
else {
|
||||
logger.info("[Sentinel Zuul] Register default fallback provider. ");
|
||||
ZuulBlockFallbackManager.registerProvider(new DefaultBlockFallbackProvider());
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,2 @@
|
||||
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
|
||||
org.springframework.cloud.alibaba.sentinel.zuul.SentinelZuulAutoConfiguration
|
@ -310,6 +310,12 @@ public class SentinelProperties {
|
||||
*/
|
||||
private List<String> urlPatterns;
|
||||
|
||||
/**
|
||||
* Enable to instance
|
||||
* {@link com.alibaba.csp.sentinel.adapter.servlet.CommonFilter}.
|
||||
*/
|
||||
private boolean enabled = true;
|
||||
|
||||
public int getOrder() {
|
||||
return this.order;
|
||||
}
|
||||
@ -325,7 +331,15 @@ public class SentinelProperties {
|
||||
public void setUrlPatterns(List<String> urlPatterns) {
|
||||
this.urlPatterns = urlPatterns;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isEnabled() {
|
||||
return enabled;
|
||||
}
|
||||
|
||||
public void setEnabled(boolean enabled) {
|
||||
this.enabled = enabled;
|
||||
}
|
||||
}
|
||||
|
||||
public static class Log {
|
||||
|
||||
|
@ -49,7 +49,8 @@ public class SentinelWebAutoConfiguration {
|
||||
private SentinelProperties properties;
|
||||
|
||||
@Bean
|
||||
public FilterRegistrationBean servletRequestListener() {
|
||||
@ConditionalOnProperty(name = "spring.cloud.sentinel.filter.enabled", matchIfMissing = true)
|
||||
public FilterRegistrationBean sentinelFilter() {
|
||||
FilterRegistrationBean registration = new FilterRegistrationBean();
|
||||
|
||||
SentinelProperties.Filter filterConfig = properties.getFilter();
|
||||
|
@ -31,6 +31,7 @@ import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
|
||||
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRuleManager;
|
||||
import com.alibaba.csp.sentinel.slots.system.SystemRuleManager;
|
||||
import com.alibaba.csp.sentinel.transport.config.TransportConfig;
|
||||
import com.alibaba.csp.sentinel.util.AppNameUtil;
|
||||
|
||||
/**
|
||||
* Endpoint for Sentinel, contains ans properties and rules
|
||||
@ -50,6 +51,7 @@ public class SentinelEndpoint extends AbstractEndpoint<Map<String, Object>> {
|
||||
final Map<String, Object> result = new HashMap<>();
|
||||
if (sentinelProperties.isEnabled()) {
|
||||
|
||||
result.put("appName", AppNameUtil.getAppName());
|
||||
result.put("logDir", LogBase.getLogBaseDir());
|
||||
result.put("logUsePid", LogBase.isLogNameUsePid());
|
||||
result.put("blockPage", WebServletConfig.getBlockPage());
|
||||
|
@ -39,6 +39,12 @@
|
||||
"defaultValue": "Integer.MIN_VALUE",
|
||||
"description": "sentinel filter chain order, will be set to FilterRegistrationBean."
|
||||
},
|
||||
{
|
||||
"name": "spring.cloud.sentinel.filter.enabled",
|
||||
"type": "java.lang.Boolean",
|
||||
"defaultValue": true,
|
||||
"description": "Enable to instance com.alibaba.csp.sentinel.adapter.servlet.CommonFilter."
|
||||
},
|
||||
{
|
||||
"name": "spring.cloud.sentinel.metric.charset",
|
||||
"type": "java.lang.String",
|
||||
|
@ -63,7 +63,7 @@ public class SentinelAutoConfigurationTests {
|
||||
|
||||
@Test
|
||||
public void testFilter() {
|
||||
assertThat(context.getBean("servletRequestListener")
|
||||
assertThat(context.getBean("sentinelFilter")
|
||||
.getClass() == FilterRegistrationBean.class).isTrue();
|
||||
}
|
||||
|
||||
|
@ -73,7 +73,6 @@
|
||||
<version>1.7.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.powermock</groupId>
|
||||
<artifactId>powermock-api-mockito</artifactId>
|
||||
|
@ -81,6 +81,18 @@
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.powermock</groupId>
|
||||
<artifactId>powermock-module-junit4</artifactId>
|
||||
<version>1.7.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.powermock</groupId>
|
||||
<artifactId>powermock-api-mockito</artifactId>
|
||||
<version>1.7.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
|
@ -17,21 +17,19 @@
|
||||
package org.springframework.cloud.alicloud.ans;
|
||||
|
||||
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;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.cloud.alicloud.ans.migrate.MigrateOnConditionMissingClass;
|
||||
import org.springframework.cloud.alicloud.ans.registry.AnsAutoServiceRegistration;
|
||||
import org.springframework.cloud.alicloud.ans.registry.AnsRegistration;
|
||||
import org.springframework.cloud.alicloud.ans.registry.AnsServiceRegistry;
|
||||
import org.springframework.cloud.alicloud.context.ans.AnsProperties;
|
||||
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.Conditional;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
@ -39,12 +37,11 @@ import org.springframework.context.annotation.Configuration;
|
||||
*/
|
||||
@Configuration
|
||||
@EnableConfigurationProperties
|
||||
@Conditional(MigrateOnConditionMissingClass.class)
|
||||
@ConditionalOnClass(name = "org.springframework.boot.context.embedded.EmbeddedServletContainerInitializedEvent")
|
||||
@ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true)
|
||||
@ConditionalOnAnsEnabled
|
||||
@AutoConfigureBefore(AnsDiscoveryClientAutoConfiguration.class)
|
||||
@AutoConfigureAfter(AutoServiceRegistrationConfiguration.class)
|
||||
@AutoConfigureAfter({ AutoServiceRegistrationConfiguration.class,
|
||||
AutoServiceRegistrationAutoConfiguration.class })
|
||||
public class AnsAutoConfiguration {
|
||||
|
||||
@Bean
|
||||
|
@ -19,12 +19,10 @@ package org.springframework.cloud.alicloud.ans;
|
||||
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.cloud.alicloud.ans.migrate.MigrateOnConditionMissingClass;
|
||||
import org.springframework.cloud.alicloud.ans.registry.AnsRegistration;
|
||||
import org.springframework.cloud.client.discovery.DiscoveryClient;
|
||||
import org.springframework.cloud.client.discovery.simple.SimpleDiscoveryClientAutoConfiguration;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Conditional;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
@ -32,7 +30,6 @@ import org.springframework.context.annotation.Configuration;
|
||||
* @author pbting
|
||||
*/
|
||||
@Configuration
|
||||
@Conditional(MigrateOnConditionMissingClass.class)
|
||||
@ConditionalOnMissingBean(DiscoveryClient.class)
|
||||
@EnableConfigurationProperties
|
||||
@AutoConfigureBefore(SimpleDiscoveryClientAutoConfiguration.class)
|
||||
|
@ -1,34 +0,0 @@
|
||||
package org.springframework.cloud.alicloud.ans.migrate;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.actuate.endpoint.AbstractEndpoint;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
|
||||
/**
|
||||
* @author pbting
|
||||
*/
|
||||
public class MigrateEndpoint
|
||||
extends AbstractEndpoint<Map<String, ConcurrentMap<String, ServerWrapper>>> {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(MigrateEndpoint.class);
|
||||
|
||||
public MigrateEndpoint() {
|
||||
super("migrate");
|
||||
}
|
||||
|
||||
/**
|
||||
* @return ans endpoint
|
||||
*/
|
||||
@Override
|
||||
public Map<String, ConcurrentMap<String, ServerWrapper>> invoke() {
|
||||
|
||||
Map<String, ConcurrentMap<String, ServerWrapper>> result = ServerListInvocationHandler
|
||||
.getServerRegistry();
|
||||
|
||||
log.info("migrate server list :" + result);
|
||||
return result;
|
||||
}
|
||||
}
|
@ -1,21 +0,0 @@
|
||||
package org.springframework.cloud.alicloud.ans.migrate;
|
||||
|
||||
import org.springframework.boot.actuate.endpoint.Endpoint;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Conditional;
|
||||
|
||||
/**
|
||||
* @author pbting
|
||||
*/
|
||||
@ConditionalOnWebApplication
|
||||
@ConditionalOnClass(value = Endpoint.class)
|
||||
@Conditional(MigrateOnConditionClass.class)
|
||||
public class MigrateEndpointAutoConfiguration {
|
||||
|
||||
@Bean
|
||||
public MigrateEndpoint ansEndpoint() {
|
||||
return new MigrateEndpoint();
|
||||
}
|
||||
}
|
@ -1,48 +0,0 @@
|
||||
package org.springframework.cloud.alicloud.ans.migrate;
|
||||
|
||||
import org.springframework.beans.factory.BeanClassLoaderAware;
|
||||
import org.springframework.context.annotation.Condition;
|
||||
import org.springframework.context.annotation.ConditionContext;
|
||||
import org.springframework.core.type.AnnotatedTypeMetadata;
|
||||
import org.springframework.util.ClassUtils;
|
||||
|
||||
/**
|
||||
* @author pbting
|
||||
*/
|
||||
public abstract class MigrateOnCondition implements Condition, BeanClassLoaderAware {
|
||||
|
||||
final String[] conditionOnClass = new String[] {
|
||||
"org.springframework.cloud.consul.serviceregistry.ConsulAutoServiceRegistration",
|
||||
"org.springframework.cloud.netflix.eureka.serviceregistry.EurekaAutoServiceRegistration" };
|
||||
|
||||
ClassLoader classLoader;
|
||||
|
||||
@Override
|
||||
public void setBeanClassLoader(ClassLoader classLoader) {
|
||||
this.classLoader = classLoader;
|
||||
}
|
||||
|
||||
@Override
|
||||
public abstract boolean matches(ConditionContext context,
|
||||
AnnotatedTypeMetadata metadata);
|
||||
|
||||
boolean isPresent(String className, ClassLoader classLoader) {
|
||||
if (classLoader == null) {
|
||||
classLoader = ClassUtils.getDefaultClassLoader();
|
||||
}
|
||||
|
||||
try {
|
||||
forName(className, classLoader);
|
||||
return true;
|
||||
}
|
||||
catch (Throwable throwable) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
Class<?> forName(String className, ClassLoader classLoader)
|
||||
throws ClassNotFoundException {
|
||||
return classLoader != null ? classLoader.loadClass(className)
|
||||
: Class.forName(className);
|
||||
}
|
||||
}
|
@ -1,23 +0,0 @@
|
||||
package org.springframework.cloud.alicloud.ans.migrate;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.context.annotation.ConditionContext;
|
||||
import org.springframework.core.type.AnnotatedTypeMetadata;
|
||||
|
||||
/**
|
||||
* @author pbting
|
||||
*/
|
||||
public class MigrateOnConditionClass extends MigrateOnCondition {
|
||||
|
||||
private static final Logger log = LoggerFactory
|
||||
.getLogger(MigrateOnConditionClass.class);
|
||||
|
||||
@Override
|
||||
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
|
||||
boolean result = isPresent(conditionOnClass[0], classLoader)
|
||||
|| isPresent(conditionOnClass[1], classLoader);
|
||||
log.info("the result of matcher is " + result);
|
||||
return result;
|
||||
}
|
||||
}
|
@ -1,22 +0,0 @@
|
||||
package org.springframework.cloud.alicloud.ans.migrate;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.context.annotation.ConditionContext;
|
||||
import org.springframework.core.type.AnnotatedTypeMetadata;
|
||||
|
||||
/**
|
||||
* @author pbting
|
||||
*/
|
||||
public class MigrateOnConditionMissingClass extends MigrateOnConditionClass {
|
||||
private static final Logger log = LoggerFactory
|
||||
.getLogger(MigrateOnConditionMissingClass.class);
|
||||
|
||||
@Override
|
||||
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
|
||||
boolean result = !super.matches(context, metadata);
|
||||
log.info(" the result of matcher is " + result);
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
@ -1,102 +0,0 @@
|
||||
package org.springframework.cloud.alicloud.ans.migrate;
|
||||
|
||||
import com.netflix.client.config.IClientConfig;
|
||||
import com.netflix.loadbalancer.ILoadBalancer;
|
||||
import com.netflix.loadbalancer.Server;
|
||||
import com.netflix.loadbalancer.ServerList;
|
||||
import org.aopalliance.aop.Advice;
|
||||
import org.aopalliance.intercept.MethodInterceptor;
|
||||
import org.aopalliance.intercept.MethodInvocation;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.aop.framework.ProxyFactory;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentSkipListSet;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
/**
|
||||
* @author pbting
|
||||
*/
|
||||
final class MigrateProxyManager {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(MigrateProxyManager.class);
|
||||
|
||||
private final static AtomicBoolean IS_PROXY = new AtomicBoolean(true);
|
||||
|
||||
private final static Set<String> SERVICES_ID = new ConcurrentSkipListSet<>();
|
||||
|
||||
private static Object springProxyFactory(Object target, ClassLoader classLoader,
|
||||
List<Advice> adviceList, Class... interfaces) {
|
||||
final ProxyFactory proxyFactory = new ProxyFactory(interfaces);
|
||||
proxyFactory.setTarget(target);
|
||||
for (Iterator<Advice> iterator = adviceList.iterator(); iterator.hasNext();) {
|
||||
proxyFactory.addAdvice(iterator.next());
|
||||
}
|
||||
return proxyFactory.getProxy(classLoader);
|
||||
}
|
||||
|
||||
static Object newServerListProxy(Object bean, ClassLoader classLoader,
|
||||
IClientConfig clientConfig) {
|
||||
List<Advice> adviceLists = new LinkedList<>();
|
||||
adviceLists.add(new ServerListInvocationHandler(clientConfig));
|
||||
bean = springProxyFactory(bean, classLoader, adviceLists,
|
||||
new Class[] { ServerList.class });
|
||||
log.info("[service id]" + clientConfig.getClientName()
|
||||
+ " new a ServerList proxy instance for spring cloud netflix to spring cloud alibaba ");
|
||||
collectServiceId(clientConfig.getClientName());
|
||||
return bean;
|
||||
}
|
||||
|
||||
static Object newLoadBalancerProxy(Object bean, ClassLoader classLoader,
|
||||
final IClientConfig clientConfig) {
|
||||
// step 1: initializer a advice for after returning advice
|
||||
final List<Advice> adviceLists = new LinkedList<>();
|
||||
adviceLists.add(new MethodInterceptor() {
|
||||
private final IClientConfig iclientConfig = clientConfig;
|
||||
|
||||
@Override
|
||||
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
|
||||
Object returnValue = methodInvocation.proceed();
|
||||
String methodName = methodInvocation.getMethod().getName();
|
||||
if (!"chooseServer".equals(methodName)) {
|
||||
return returnValue;
|
||||
}
|
||||
|
||||
String serviceId = iclientConfig.getClientName();
|
||||
Server server = ServerListInvocationHandler
|
||||
.checkAndGetServiceServer(serviceId, (Server) returnValue);
|
||||
ServerListInvocationHandler.incrementCallService(serviceId, server);
|
||||
return server;
|
||||
}
|
||||
});
|
||||
// step 2: new proxy instance by spring factory
|
||||
bean = springProxyFactory(bean, classLoader, adviceLists,
|
||||
new Class[] { ILoadBalancer.class });
|
||||
log.info("[service id]" + clientConfig.getClientName()
|
||||
+ " new a ILoadBalancer proxy instance for spring cloud netflix to spring cloud alibaba ");
|
||||
return bean;
|
||||
}
|
||||
|
||||
static void migrateProxyClose() {
|
||||
IS_PROXY.set(false);
|
||||
}
|
||||
|
||||
static void migrateProxyUp() {
|
||||
IS_PROXY.set(true);
|
||||
}
|
||||
|
||||
static boolean isMigrateProxy() {
|
||||
|
||||
return IS_PROXY.get();
|
||||
}
|
||||
|
||||
static void collectServiceId(String serviceId) {
|
||||
SERVICES_ID.add(serviceId);
|
||||
}
|
||||
|
||||
static Set<String> getServicesId() {
|
||||
|
||||
return Collections.unmodifiableSet(SERVICES_ID);
|
||||
}
|
||||
}
|
@ -1,100 +0,0 @@
|
||||
package org.springframework.cloud.alicloud.ans.migrate;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.cloud.context.named.NamedContextFactory;
|
||||
import org.springframework.cloud.endpoint.event.RefreshEvent;
|
||||
import org.springframework.context.ApplicationListener;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.netflix.loadbalancer.ILoadBalancer;
|
||||
|
||||
/**
|
||||
* @author pbting
|
||||
*/
|
||||
@Component
|
||||
public class MigrateRefreshEventListener implements ApplicationListener<RefreshEvent> {
|
||||
private static final Logger log = LoggerFactory
|
||||
.getLogger(MigrateRefreshEventListener.class);
|
||||
|
||||
private final static int CHECK_INTERVAL = 1;
|
||||
|
||||
private final static String MIGRATE_SWITCH = "spring.cloud.alicloud.migarte.ans.switch";
|
||||
|
||||
private volatile String lastScaMigrateAnsSwitchValue = "true";
|
||||
|
||||
private Environment environment;
|
||||
|
||||
private NamedContextFactory namedContextFactory;
|
||||
|
||||
public MigrateRefreshEventListener(Environment environment,
|
||||
NamedContextFactory namedContextFactory) {
|
||||
this.environment = environment;
|
||||
this.namedContextFactory = namedContextFactory;
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
public void initTimerCheck() {
|
||||
Executors.newSingleThreadScheduledExecutor()
|
||||
.scheduleWithFixedDelay(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
onApplicationEvent(null);
|
||||
}
|
||||
catch (Exception e) {
|
||||
log.error(
|
||||
"check the value of 'sca.migrate.ans.switch' in environment whether changed or not cause an Exeption",
|
||||
e);
|
||||
}
|
||||
}
|
||||
}, CHECK_INTERVAL, CHECK_INTERVAL, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onApplicationEvent(RefreshEvent event) {
|
||||
String value = environment.getProperty(MIGRATE_SWITCH, "true");
|
||||
|
||||
// check 1: check the value
|
||||
if (value.equals(lastScaMigrateAnsSwitchValue)) {
|
||||
return;
|
||||
}
|
||||
|
||||
updateLastScaMigrateAnsResetValue(value);
|
||||
|
||||
// step 1: migrate up
|
||||
if ("true".equals(value)) {
|
||||
MigrateProxyManager.migrateProxyUp();
|
||||
serviceIdContextInit();
|
||||
return;
|
||||
}
|
||||
|
||||
// step 2: migrate close
|
||||
if ("false".equals(value)) {
|
||||
MigrateProxyManager.migrateProxyClose();
|
||||
serviceIdContextInit();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private void serviceIdContextInit() {
|
||||
namedContextFactory.destroy();
|
||||
// initializer each spring context for service id
|
||||
Set<String> serviceIds = MigrateProxyManager.getServicesId();
|
||||
for (Iterator<String> iterator = serviceIds.iterator(); iterator.hasNext();) {
|
||||
namedContextFactory.getInstance(iterator.next(), ILoadBalancer.class);
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void updateLastScaMigrateAnsResetValue(String value) {
|
||||
this.lastScaMigrateAnsSwitchValue = value;
|
||||
}
|
||||
}
|
@ -1,62 +0,0 @@
|
||||
package org.springframework.cloud.alicloud.ans.migrate;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.beans.factory.BeanClassLoaderAware;
|
||||
import org.springframework.beans.factory.config.BeanPostProcessor;
|
||||
|
||||
import com.netflix.client.config.IClientConfig;
|
||||
import com.netflix.loadbalancer.ILoadBalancer;
|
||||
import com.netflix.loadbalancer.ServerList;
|
||||
|
||||
/**
|
||||
* @author pbting
|
||||
*/
|
||||
public class MigrateRibbonBeanPostProcessor
|
||||
implements BeanPostProcessor, BeanClassLoaderAware {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(MigrateOnCondition.class);
|
||||
|
||||
private ClassLoader classLoader;
|
||||
private IClientConfig clientConfig;
|
||||
|
||||
public MigrateRibbonBeanPostProcessor(IClientConfig clientConfig) {
|
||||
this.clientConfig = clientConfig;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object postProcessAfterInitialization(Object bean, String beanName)
|
||||
throws BeansException {
|
||||
|
||||
// step 1 : check the bean whether proxy or not
|
||||
if (!MigrateProxyManager.isMigrateProxy()) {
|
||||
log.info("Migrate proxy is Close.");
|
||||
return bean;
|
||||
}
|
||||
|
||||
// step 2 : proxy the designated bean
|
||||
if (bean instanceof ServerList) {
|
||||
bean = MigrateProxyManager.newServerListProxy(bean, classLoader,
|
||||
clientConfig);
|
||||
}
|
||||
|
||||
if (bean instanceof ILoadBalancer) {
|
||||
bean = MigrateProxyManager.newLoadBalancerProxy(bean, classLoader,
|
||||
clientConfig);
|
||||
}
|
||||
return bean;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object postProcessBeforeInitialization(Object o, String s)
|
||||
throws BeansException {
|
||||
return o;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setBeanClassLoader(ClassLoader classLoader) {
|
||||
this.classLoader = classLoader;
|
||||
}
|
||||
|
||||
}
|
@ -1,69 +0,0 @@
|
||||
package org.springframework.cloud.alicloud.ans.migrate;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||
import org.springframework.cloud.alicloud.ans.registry.AnsRegistration;
|
||||
import org.springframework.cloud.alicloud.ans.registry.AnsServiceRegistry;
|
||||
import org.springframework.cloud.alicloud.context.ans.AnsProperties;
|
||||
import org.springframework.cloud.client.serviceregistry.ServiceRegistry;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* @author pbting
|
||||
*/
|
||||
@Component
|
||||
public class MigrateServiceRegistry {
|
||||
|
||||
private static final Logger log = LoggerFactory
|
||||
.getLogger(MigrateServiceRegistry.class);
|
||||
|
||||
private AtomicBoolean running = new AtomicBoolean(false);
|
||||
|
||||
private ServiceRegistry serviceRegistry;
|
||||
private AnsRegistration ansRegistration;
|
||||
|
||||
public MigrateServiceRegistry(AnsProperties ansProperties,
|
||||
ApplicationContext context) {
|
||||
this.ansRegistration = new AnsRegistration(ansProperties, context);
|
||||
this.ansRegistration.init();
|
||||
this.serviceRegistry = new AnsServiceRegistry();
|
||||
}
|
||||
|
||||
@EventListener(ApplicationReadyEvent.class)
|
||||
public void onApplicationEvent(ApplicationReadyEvent event) {
|
||||
String serverPort = event.getApplicationContext().getEnvironment()
|
||||
.getProperty("server.port");
|
||||
if (null != serverPort && serverPort.trim().length() > 0) {
|
||||
try {
|
||||
this.ansRegistration.setPort(Integer.parseInt(serverPort));
|
||||
}
|
||||
catch (NumberFormatException e) {
|
||||
// nothing to do
|
||||
}
|
||||
}
|
||||
log.info("[ Migrate ] change the port to " + serverPort);
|
||||
|
||||
if (this.running.get()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.ansRegistration.getPort() > 0) {
|
||||
long s = System.currentTimeMillis();
|
||||
log.info("[Migrate] start to registry server to ANS");
|
||||
this.serviceRegistry.register(this.ansRegistration);
|
||||
log.info("[migrate] end to registry server to ANS cost time with "
|
||||
+ (System.currentTimeMillis() - s) + " ms.");
|
||||
}
|
||||
else {
|
||||
log.warn("the server port is smaller than zero. "
|
||||
+ this.ansRegistration.getPort());
|
||||
}
|
||||
this.running.set(true);
|
||||
}
|
||||
|
||||
}
|
@ -1,39 +0,0 @@
|
||||
package org.springframework.cloud.alicloud.ans.migrate;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.cloud.alicloud.ans.ConditionalOnAnsEnabled;
|
||||
import org.springframework.cloud.alicloud.context.ans.AnsProperties;
|
||||
import org.springframework.cloud.context.named.NamedContextFactory;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Conditional;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.env.Environment;
|
||||
|
||||
/**
|
||||
* @author pbting
|
||||
*/
|
||||
@Configuration
|
||||
@EnableConfigurationProperties
|
||||
@Conditional(MigrateOnConditionClass.class)
|
||||
@ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true)
|
||||
@ConditionalOnAnsEnabled
|
||||
public class MigrationAutoconfiguration {
|
||||
|
||||
@Bean
|
||||
public MigrateServiceRegistry migrationManger(AnsProperties ansProperties,
|
||||
ApplicationContext applicationContext) {
|
||||
|
||||
return new MigrateServiceRegistry(ansProperties, applicationContext);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public MigrateRefreshEventListener migrateRefreshEventListener(
|
||||
Environment environment,
|
||||
@Qualifier(value = "springClientFactory") NamedContextFactory namedContextFactory) {
|
||||
|
||||
return new MigrateRefreshEventListener(environment, namedContextFactory);
|
||||
}
|
||||
}
|
@ -1,177 +0,0 @@
|
||||
package org.springframework.cloud.alicloud.ans.migrate;
|
||||
|
||||
import com.netflix.client.config.IClientConfig;
|
||||
import com.netflix.loadbalancer.Server;
|
||||
import org.aopalliance.intercept.MethodInterceptor;
|
||||
import org.aopalliance.intercept.MethodInvocation;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.cloud.alicloud.ans.ribbon.AnsServer;
|
||||
import org.springframework.cloud.alicloud.ans.ribbon.AnsServerList;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
import java.util.concurrent.ConcurrentSkipListSet;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
/**
|
||||
* @author pbting
|
||||
*/
|
||||
class ServerListInvocationHandler implements MethodInterceptor {
|
||||
|
||||
private static final Logger log = LoggerFactory
|
||||
.getLogger(ServerListInvocationHandler.class);
|
||||
|
||||
private final static ConcurrentMap<String, AnsServerList> SERVER_LIST_CONCURRENT_MAP = new ConcurrentHashMap<>();
|
||||
|
||||
private final static ConcurrentMap<String, ConcurrentMap<String, ServerWrapper>> CALL_SERVICE_COUNT = new ConcurrentHashMap<>();
|
||||
private final static Set<String> INTERCEPTOR_METHOD_NAME = new ConcurrentSkipListSet();
|
||||
|
||||
private IClientConfig clientConfig;
|
||||
private AnsServerList ansServerList;
|
||||
private AtomicBoolean isFirst = new AtomicBoolean(false);
|
||||
|
||||
static {
|
||||
INTERCEPTOR_METHOD_NAME.add("getInitialListOfServers");
|
||||
INTERCEPTOR_METHOD_NAME.add("getUpdatedListOfServers");
|
||||
}
|
||||
|
||||
ServerListInvocationHandler(IClientConfig clientConfig) {
|
||||
this.clientConfig = clientConfig;
|
||||
this.ansServerList = new AnsServerList(clientConfig.getClientName());
|
||||
SERVER_LIST_CONCURRENT_MAP.put(ansServerList.getDom(), ansServerList);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object invoke(MethodInvocation invocation) throws Throwable {
|
||||
String methodName = invocation.getMethod().getName();
|
||||
// step 1: check the method is not interceptor
|
||||
if (!INTERCEPTOR_METHOD_NAME.contains(methodName)) {
|
||||
return invocation.proceed();
|
||||
}
|
||||
|
||||
// step 2: interceptor the method
|
||||
List<Server> serverList = (List<Server>) invocation.proceed();
|
||||
long s = System.currentTimeMillis();
|
||||
log.info("[ START ] merage server list for " + clientConfig.getClientName());
|
||||
serverList = mergeAnsServerList(serverList);
|
||||
log.info("[ END ] merage server list for " + clientConfig.getClientName()
|
||||
+ ", cost time " + (System.currentTimeMillis() - s) + " ms .");
|
||||
return serverList;
|
||||
}
|
||||
|
||||
/**
|
||||
* 后台线程 和 Eureka 两个注册中心进行 Merage 的时候,List 表中始终保持是有效的 Server. 即不考虑 ANS 客户端本地容灾的情况
|
||||
*/
|
||||
private List<Server> mergeAnsServerList(final List<Server> source) {
|
||||
if (source.size() > 0 && isFirst.compareAndSet(false, true)) {
|
||||
return source;
|
||||
}
|
||||
|
||||
// step 1: get all of server list and filter the alive
|
||||
List<AnsServer> ansServerList = filterAliveAnsServer(
|
||||
this.ansServerList.getInitialListOfServers());
|
||||
|
||||
if (ansServerList.isEmpty()) {
|
||||
return source;
|
||||
}
|
||||
|
||||
log.info("[" + this.clientConfig.getClientName() + "] Get Server List from ANS:"
|
||||
+ ansServerList + "; loadbalancer server list override before:" + source);
|
||||
|
||||
// step 2:remove servers of that have in load balancer list
|
||||
final Iterator<Server> serverIterator = source.iterator();
|
||||
while (serverIterator.hasNext()) {
|
||||
final Server server = serverIterator.next();
|
||||
for (Iterator<AnsServer> iterator = ansServerList.iterator(); iterator
|
||||
.hasNext();) {
|
||||
AnsServer ansServer = iterator.next();
|
||||
if (server.getHostPort()
|
||||
.equals(ansServer.getHealthService().toInetAddr())) {
|
||||
// fix bug: mast be set the zone, update server list,will filter
|
||||
// by: ZoneAffinityPredicate
|
||||
serverIterator.remove();
|
||||
log.info("Source Server is remove " + server.getHostPort()
|
||||
+ ", and from ANS Server is override:"
|
||||
+ ansServer.toString());
|
||||
}
|
||||
ansServer.setZone(server.getZone());
|
||||
ansServer.setSchemea(server.getScheme());
|
||||
ansServer.setId(ansServer.getHealthService().toInetAddr());
|
||||
ansServer.setReadyToServe(true);
|
||||
}
|
||||
}
|
||||
|
||||
for (Iterator<AnsServer> iterator = ansServerList.iterator(); iterator
|
||||
.hasNext();) {
|
||||
source.add(iterator.next());
|
||||
}
|
||||
log.info("[" + this.clientConfig.getClientName() + "] "
|
||||
+ "; loadbalancer server list override after:" + source);
|
||||
// override
|
||||
return source;
|
||||
}
|
||||
|
||||
private List<AnsServer> filterAliveAnsServer(List<AnsServer> sourceServerList) {
|
||||
final List<AnsServer> resultServerList = new LinkedList<>();
|
||||
for (Iterator<AnsServer> iterator = sourceServerList.iterator(); iterator
|
||||
.hasNext();) {
|
||||
AnsServer ansServer = iterator.next();
|
||||
boolean isAlive = ansServer.isAlive(3);
|
||||
if (isAlive) {
|
||||
resultServerList.add(ansServer);
|
||||
}
|
||||
log.warn(ansServer.toString() + " isAlive :" + isAlive);
|
||||
}
|
||||
return resultServerList;
|
||||
}
|
||||
|
||||
static Map<String, ConcurrentMap<String, ServerWrapper>> getServerRegistry() {
|
||||
|
||||
return Collections.unmodifiableMap(CALL_SERVICE_COUNT);
|
||||
}
|
||||
|
||||
static Server checkAndGetServiceServer(String serviceId, Server server) {
|
||||
if (server != null) {
|
||||
return server;
|
||||
}
|
||||
|
||||
log.warn(String.format("[%s] refers the server is null", server));
|
||||
|
||||
List<AnsServer> ansServerList = SERVER_LIST_CONCURRENT_MAP.get(serviceId)
|
||||
.getInitialListOfServers();
|
||||
|
||||
if (!ansServerList.isEmpty()) {
|
||||
return ansServerList.get(0);
|
||||
}
|
||||
|
||||
return server;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param serviceId
|
||||
* @param server
|
||||
* @return
|
||||
*/
|
||||
static long incrementCallService(String serviceId, Server server) {
|
||||
ConcurrentMap<String, ServerWrapper> concurrentHashMap = CALL_SERVICE_COUNT
|
||||
.putIfAbsent(serviceId, new ConcurrentHashMap<String, ServerWrapper>());
|
||||
|
||||
if (concurrentHashMap == null) {
|
||||
concurrentHashMap = CALL_SERVICE_COUNT.get(serviceId);
|
||||
}
|
||||
|
||||
String ipPort = server.getHostPort();
|
||||
ServerWrapper serverWraper = concurrentHashMap.putIfAbsent(ipPort,
|
||||
new ServerWrapper(server, new AtomicLong()));
|
||||
|
||||
if (serverWraper == null) {
|
||||
serverWraper = concurrentHashMap.get(ipPort);
|
||||
}
|
||||
serverWraper.setServer(server);
|
||||
return serverWraper.getCallCount().incrementAndGet();
|
||||
}
|
||||
}
|
@ -1,38 +0,0 @@
|
||||
package org.springframework.cloud.alicloud.ans.migrate;
|
||||
|
||||
import com.netflix.loadbalancer.Server;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
/**
|
||||
* @author pbting
|
||||
*/
|
||||
public class ServerWrapper {
|
||||
|
||||
private Server server;
|
||||
private AtomicLong callCount;
|
||||
|
||||
public ServerWrapper() {
|
||||
}
|
||||
|
||||
public ServerWrapper(Server server, AtomicLong callCount) {
|
||||
this.server = server;
|
||||
this.callCount = callCount;
|
||||
}
|
||||
|
||||
public Server getServer() {
|
||||
return server;
|
||||
}
|
||||
|
||||
public void setServer(Server server) {
|
||||
this.server = server;
|
||||
}
|
||||
|
||||
public AtomicLong getCallCount() {
|
||||
return callCount;
|
||||
}
|
||||
|
||||
public void setCallCount(AtomicLong callCount) {
|
||||
this.callCount = callCount;
|
||||
}
|
||||
}
|
@ -18,12 +18,9 @@ package org.springframework.cloud.alicloud.ans.registry;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.context.embedded.EmbeddedServletContainerInitializedEvent;
|
||||
import org.springframework.cloud.client.serviceregistry.AbstractAutoServiceRegistration;
|
||||
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationProperties;
|
||||
import org.springframework.cloud.client.serviceregistry.ServiceRegistry;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
@ -31,7 +28,6 @@ import org.springframework.util.StringUtils;
|
||||
* @author xiaolongzuo
|
||||
* @author pbting
|
||||
*/
|
||||
@Component
|
||||
public class AnsAutoServiceRegistration
|
||||
extends AbstractAutoServiceRegistration<AnsRegistration> {
|
||||
|
||||
@ -66,16 +62,6 @@ public class AnsAutoServiceRegistration
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void start() {
|
||||
// nothing to do
|
||||
}
|
||||
|
||||
@EventListener(EmbeddedServletContainerInitializedEvent.class)
|
||||
public void doStart() {
|
||||
super.start();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void register() {
|
||||
if (!this.registration.getAnsProperties().isRegisterEnabled()) {
|
||||
|
@ -16,11 +16,6 @@
|
||||
|
||||
package org.springframework.cloud.alicloud.ans.registry;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
|
||||
import org.springframework.cloud.alicloud.context.ans.AnsProperties;
|
||||
import org.springframework.cloud.client.DefaultServiceInstance;
|
||||
import org.springframework.cloud.client.ServiceInstance;
|
||||
@ -30,14 +25,18 @@ import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import java.net.URI;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @author xiaolongzuo
|
||||
*/
|
||||
public class AnsRegistration 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";
|
||||
static final String MANAGEMENT_PORT = "management.port";
|
||||
static final String MANAGEMENT_CONTEXT_PATH = "management.context-path";
|
||||
static final String MANAGEMENT_ADDRESS = "management.address";
|
||||
|
||||
private AnsProperties ansProperties;
|
||||
private ApplicationContext context;
|
||||
|
@ -18,6 +18,7 @@ package org.springframework.cloud.alicloud.ans.registry;
|
||||
|
||||
import com.alibaba.ans.core.NamingService;
|
||||
import com.alibaba.ans.shaded.com.taobao.vipserver.client.ipms.NodeReactor;
|
||||
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@ -40,11 +41,11 @@ public class AnsServiceRegistry implements ServiceRegistry<AnsRegistration> {
|
||||
public void register(AnsRegistration registration) {
|
||||
|
||||
if (!registration.isRegisterEnabled()) {
|
||||
log.info("Registration is disabled...");
|
||||
log.warn("Registration is disabled...");
|
||||
return;
|
||||
}
|
||||
if (StringUtils.isEmpty(registration.getServiceId())) {
|
||||
log.info("No service to register for client...");
|
||||
log.warn("No service to register for client...");
|
||||
return;
|
||||
}
|
||||
|
||||
@ -62,14 +63,13 @@ public class AnsServiceRegistry implements ServiceRegistry<AnsRegistration> {
|
||||
NamingService.regDom(dom, registration.getHost(), registration.getPort(),
|
||||
registration.getRegisterWeight(dom), registration.getCluster(),
|
||||
tags);
|
||||
log.info("INFO_ANS_REGISTER, " + dom + " "
|
||||
+ registration.getAnsProperties().getClientIp() + ":"
|
||||
+ registration.getAnsProperties().getClientPort()
|
||||
+ " register finished");
|
||||
log.info("INFO_ANS_REGISTER, {} {}:{} register finished", dom,
|
||||
registration.getAnsProperties().getClientIp(),
|
||||
registration.getAnsProperties().getClientPort());
|
||||
}
|
||||
catch (Exception e) {
|
||||
log.error("ERR_ANS_REGISTER, " + dom + " register failed..."
|
||||
+ registration.toString() + ",", e);
|
||||
log.error("ERR_ANS_REGISTER, {} register failed...{},", dom,
|
||||
registration.toString(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -80,7 +80,7 @@ public class AnsServiceRegistry implements ServiceRegistry<AnsRegistration> {
|
||||
log.info("De-registering from ANSServer now...");
|
||||
|
||||
if (StringUtils.isEmpty(registration.getServiceId())) {
|
||||
log.info("No dom to de-register for client...");
|
||||
log.warn("No dom to de-register for client...");
|
||||
return;
|
||||
}
|
||||
|
||||
@ -89,8 +89,8 @@ public class AnsServiceRegistry implements ServiceRegistry<AnsRegistration> {
|
||||
registration.getPort(), registration.getCluster());
|
||||
}
|
||||
catch (Exception e) {
|
||||
log.error("ERR_ANS_DEREGISTER, de-register failed..."
|
||||
+ registration.toString() + ",", e);
|
||||
log.error("ERR_ANS_DEREGISTER, de-register failed...{},",
|
||||
registration.toString(), e);
|
||||
}
|
||||
|
||||
log.info("De-registration finished.");
|
||||
|
@ -16,21 +16,17 @@
|
||||
|
||||
package org.springframework.cloud.alicloud.ans.ribbon;
|
||||
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.cloud.alicloud.ans.migrate.MigrateOnConditionMissingClass;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Conditional;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import com.netflix.client.config.IClientConfig;
|
||||
import com.netflix.loadbalancer.ServerList;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* @author xiaolongzuo
|
||||
* @author pbting
|
||||
*/
|
||||
@Configuration
|
||||
@Conditional(MigrateOnConditionMissingClass.class)
|
||||
public class AnsRibbonClientConfiguration {
|
||||
|
||||
@Bean
|
||||
|
@ -16,19 +16,14 @@
|
||||
|
||||
package org.springframework.cloud.alicloud.ans.ribbon;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.Socket;
|
||||
import java.util.HashMap;
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import com.alibaba.ans.shaded.com.taobao.vipserver.client.core.Host;
|
||||
import com.netflix.loadbalancer.Server;
|
||||
|
||||
/**
|
||||
* @author xiaolongzuo
|
||||
* @author pbting
|
||||
*/
|
||||
public class AnsServer extends Server {
|
||||
|
||||
@ -39,8 +34,7 @@ public class AnsServer extends Server {
|
||||
public AnsServer(final Host host, final String dom) {
|
||||
super(host.getIp(), host.getPort());
|
||||
this.host = host;
|
||||
this.metadata = new HashMap();
|
||||
this.metadata.put("source", "ANS");
|
||||
this.metadata = Collections.emptyMap();
|
||||
metaInfo = new MetaInfo() {
|
||||
@Override
|
||||
public String getAppName() {
|
||||
@ -65,33 +59,6 @@ public class AnsServer extends Server {
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAlive() {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param timeOut Unit: Seconds
|
||||
* @return
|
||||
*/
|
||||
public boolean isAlive(long timeOut) {
|
||||
try {
|
||||
String hostName = this.host.getHostname();
|
||||
hostName = hostName != null && hostName.trim().length() > 0 ? hostName
|
||||
: this.host.getIp();
|
||||
Socket socket = new Socket();
|
||||
socket.connect(new InetSocketAddress(hostName, this.host.getPort()),
|
||||
(int) TimeUnit.SECONDS.toMillis(timeOut));
|
||||
socket.close();
|
||||
return true;
|
||||
}
|
||||
catch (IOException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public MetaInfo getMetaInfo() {
|
||||
return metaInfo;
|
||||
|
@ -16,22 +16,19 @@
|
||||
|
||||
package org.springframework.cloud.alicloud.ans.ribbon;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import com.alibaba.ans.core.NamingService;
|
||||
import com.alibaba.ans.shaded.com.taobao.vipserver.client.core.Host;
|
||||
import com.netflix.client.config.IClientConfig;
|
||||
import com.netflix.loadbalancer.AbstractServerList;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author xiaolongzuo
|
||||
* @author pbting
|
||||
*/
|
||||
public class AnsServerList extends AbstractServerList<AnsServer> {
|
||||
|
||||
private final static int CONNECT_TIME_OUT = 3;
|
||||
|
||||
private String dom;
|
||||
|
||||
public AnsServerList(String dom) {
|
||||
@ -63,12 +60,10 @@ public class AnsServerList extends AbstractServerList<AnsServer> {
|
||||
List<AnsServer> result = new ArrayList<AnsServer>(hosts.size());
|
||||
for (Host host : hosts) {
|
||||
if (host.isValid()) {
|
||||
AnsServer ansServer = hostToServer(host);
|
||||
if (ansServer.isAlive(CONNECT_TIME_OUT)) {
|
||||
result.add(ansServer);
|
||||
}
|
||||
result.add(hostToServer(host));
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
@ -1,20 +0,0 @@
|
||||
package org.springframework.cloud.alicloud.ans.ribbon;
|
||||
|
||||
import org.springframework.cloud.alicloud.ans.migrate.MigrateRibbonBeanPostProcessor;
|
||||
import org.springframework.cloud.alicloud.ans.migrate.MigrateOnConditionClass;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Conditional;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import com.netflix.client.config.IClientConfig;
|
||||
|
||||
@Configuration
|
||||
@Conditional(MigrateOnConditionClass.class)
|
||||
public class MigrateRibbonCofiguration {
|
||||
|
||||
@Bean
|
||||
public MigrateRibbonBeanPostProcessor migrateBeanPostProcessor(IClientConfig clientConfig) {
|
||||
|
||||
return new MigrateRibbonBeanPostProcessor(clientConfig);
|
||||
}
|
||||
}
|
@ -34,7 +34,6 @@ import org.springframework.context.annotation.Configuration;
|
||||
@ConditionalOnBean(SpringClientFactory.class)
|
||||
@ConditionalOnRibbonAns
|
||||
@AutoConfigureAfter(RibbonAutoConfiguration.class)
|
||||
@RibbonClients(defaultConfiguration = { AnsRibbonClientConfiguration.class,
|
||||
MigrateRibbonCofiguration.class })
|
||||
@RibbonClients(defaultConfiguration = AnsRibbonClientConfiguration.class)
|
||||
public class RibbonAnsAutoConfiguration {
|
||||
}
|
||||
|
@ -2,7 +2,4 @@ org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
|
||||
org.springframework.cloud.alicloud.ans.endpoint.AnsEndpointAutoConfiguration,\
|
||||
org.springframework.cloud.alicloud.ans.ribbon.RibbonAnsAutoConfiguration,\
|
||||
org.springframework.cloud.alicloud.ans.AnsAutoConfiguration,\
|
||||
org.springframework.cloud.alicloud.ans.migrate.MigrateEndpointAutoConfiguration,\
|
||||
org.springframework.cloud.alicloud.ans.migrate.MigrationAutoconfiguration
|
||||
org.springframework.cloud.client.discovery.EnableDiscoveryClient=\
|
||||
org.springframework.cloud.alicloud.ans.AnsDiscoveryClientAutoConfiguration
|
@ -1,78 +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.ans.ribbon;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import static org.mockito.BDDMockito.given;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.cloud.alicloud.ans.ribbon.AnsServer;
|
||||
import org.springframework.cloud.alicloud.ans.ribbon.AnsServerList;
|
||||
|
||||
import com.alibaba.ans.shaded.com.taobao.vipserver.client.core.Host;
|
||||
import com.netflix.loadbalancer.Server;
|
||||
|
||||
/**
|
||||
* @author xiaolongzuo
|
||||
*/
|
||||
public class AnsServiceListTests {
|
||||
|
||||
static final String IP_ADDR = "10.0.0.2";
|
||||
|
||||
static final int PORT = 8080;
|
||||
|
||||
@Test
|
||||
public void testAnsServer() {
|
||||
AnsServerList serverList = getAnsServerList();
|
||||
List<AnsServer> servers = serverList.getInitialListOfServers();
|
||||
assertNotNull("servers was null", servers);
|
||||
assertEquals("servers was not size 1", 1, servers.size());
|
||||
Server des = assertAnsServer(servers);
|
||||
assertEquals("hostPort was wrong", IP_ADDR + ":" + PORT, des.getHostPort());
|
||||
}
|
||||
|
||||
protected Server assertAnsServer(List<AnsServer> servers) {
|
||||
Server actualServer = servers.get(0);
|
||||
assertTrue("server was not a DomainExtractingServer",
|
||||
actualServer instanceof AnsServer);
|
||||
AnsServer des = AnsServer.class.cast(actualServer);
|
||||
assertNotNull("host is null", des.getHealthService());
|
||||
assertEquals("unit was wrong", "DEFAULT", des.getHealthService().getUnit());
|
||||
return des;
|
||||
}
|
||||
|
||||
protected AnsServerList getAnsServerList() {
|
||||
Host host = mock(Host.class);
|
||||
given(host.getIp()).willReturn(IP_ADDR);
|
||||
given(host.getDoubleWeight()).willReturn(1.0);
|
||||
given(host.getPort()).willReturn(PORT);
|
||||
given(host.getWeight()).willReturn(1);
|
||||
given(host.getUnit()).willReturn("DEFAULT");
|
||||
|
||||
AnsServer server = new AnsServer(host, "testDom");
|
||||
@SuppressWarnings("unchecked")
|
||||
AnsServerList originalServerList = mock(AnsServerList.class);
|
||||
given(originalServerList.getInitialListOfServers())
|
||||
.willReturn(Arrays.asList(server));
|
||||
return originalServerList;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,120 @@
|
||||
/*
|
||||
* 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.alicloud.ans;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Matchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.springframework.cloud.alicloud.ans.test.AnsMockTest.hostInstance;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.powermock.api.mockito.PowerMockito;
|
||||
import org.powermock.core.classloader.annotations.PrepareForTest;
|
||||
import org.powermock.modules.junit4.PowerMockRunner;
|
||||
import org.springframework.cloud.alicloud.ans.registry.AnsRegistration;
|
||||
import org.springframework.cloud.client.ServiceInstance;
|
||||
|
||||
import com.alibaba.ans.core.NamingService;
|
||||
import com.alibaba.ans.shaded.com.taobao.vipserver.client.core.Host;
|
||||
|
||||
/**
|
||||
* @author xiaojing
|
||||
*/
|
||||
@RunWith(PowerMockRunner.class)
|
||||
@PrepareForTest(NamingService.class)
|
||||
public class AnsDiscoveryClientTests {
|
||||
|
||||
private String host = "123.123.123.123";
|
||||
private int port = 8888;
|
||||
private String serviceName = "test-service";
|
||||
|
||||
@Test
|
||||
public void testGetServers() throws Exception {
|
||||
|
||||
ArrayList<Host> hosts = new ArrayList<>();
|
||||
|
||||
HashMap<String, String> map = new HashMap<>();
|
||||
map.put("test-key", "test-value");
|
||||
map.put("secure", "true");
|
||||
|
||||
hosts.add(hostInstance(serviceName, false, host, port, map));
|
||||
|
||||
PowerMockito.mockStatic(NamingService.class);
|
||||
when(NamingService.getHosts(eq(serviceName))).thenReturn(hosts);
|
||||
|
||||
AnsRegistration ansRegistration = mock(AnsRegistration.class);
|
||||
AnsDiscoveryClient discoveryClient = new AnsDiscoveryClient(ansRegistration);
|
||||
|
||||
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);
|
||||
// ans doesn't support metadata
|
||||
assertThat(serviceInstance.getUri().toString())
|
||||
.isEqualTo(getUri(serviceInstance));
|
||||
// assertThat(serviceInstance.getMetadata().get("test-key")).isEqualTo("test-value");
|
||||
// ans doesn't support metadata
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetAllService() throws Exception {
|
||||
|
||||
Set<String> subscribedServices = new HashSet<>();
|
||||
|
||||
subscribedServices.add(serviceName + "1");
|
||||
subscribedServices.add(serviceName + "2");
|
||||
subscribedServices.add(serviceName + "3");
|
||||
|
||||
PowerMockito.mockStatic(NamingService.class);
|
||||
when(NamingService.getDomsSubscribed()).thenReturn(subscribedServices);
|
||||
|
||||
AnsRegistration ansRegistration = mock(AnsRegistration.class);
|
||||
AnsDiscoveryClient discoveryClient = new AnsDiscoveryClient(ansRegistration);
|
||||
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,80 @@
|
||||
/*
|
||||
* 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.alicloud.ans.registry;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
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.alicloud.ans.AnsAutoConfiguration;
|
||||
import org.springframework.cloud.alicloud.ans.AnsDiscoveryClientAutoConfiguration;
|
||||
import org.springframework.cloud.alicloud.context.ans.AnsProperties;
|
||||
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 = AnsAutoServiceRegistrationEnabledTests.TestConfig.class, properties = {
|
||||
"spring.application.name=myTestService1",
|
||||
"spring.cloud.alicloud.ans.server-list=127.0.0.1",
|
||||
"spring.cloud.alicloud.ans.server-port=8080",
|
||||
"spring.cloud.alicloud.ans.register-enabled=false" }, webEnvironment = RANDOM_PORT)
|
||||
public class AnsAutoServiceRegistrationEnabledTests {
|
||||
|
||||
@Autowired
|
||||
private AnsRegistration registration;
|
||||
|
||||
@Autowired
|
||||
private AnsAutoServiceRegistration ansAutoServiceRegistration;
|
||||
|
||||
@Autowired
|
||||
private AnsProperties properties;
|
||||
|
||||
@Test
|
||||
public void contextLoads() throws Exception {
|
||||
|
||||
assertNotNull("AnsRegistration was not created", registration);
|
||||
assertNotNull("AnsProperties was not created", properties);
|
||||
assertNotNull("AnsAutoServiceRegistration was not created",
|
||||
ansAutoServiceRegistration);
|
||||
|
||||
checkEnabled();
|
||||
|
||||
}
|
||||
|
||||
private void checkEnabled() {
|
||||
assertFalse("Ans Auto Registration should not start",
|
||||
ansAutoServiceRegistration.isEnabled());
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@EnableAutoConfiguration
|
||||
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
|
||||
AnsDiscoveryClientAutoConfiguration.class, AnsAutoConfiguration.class })
|
||||
public static class TestConfig {
|
||||
}
|
||||
}
|
@ -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.alicloud.ans.registry;
|
||||
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
|
||||
|
||||
import java.net.Inet4Address;
|
||||
import java.net.InetAddress;
|
||||
import java.net.NetworkInterface;
|
||||
import java.util.Enumeration;
|
||||
|
||||
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.alicloud.ans.AnsAutoConfiguration;
|
||||
import org.springframework.cloud.alicloud.ans.AnsDiscoveryClientAutoConfiguration;
|
||||
import org.springframework.cloud.alicloud.context.ans.AnsProperties;
|
||||
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 = AnsAutoServiceRegistrationIpNetworkInterfaceTests.TestConfig.class, properties = {
|
||||
"spring.application.name=myTestService1",
|
||||
"spring.cloud.alicloud.ans.server-list=127.0.0.1",
|
||||
"spring.cloud.alicloud.ans.server-port=8080" }, webEnvironment = RANDOM_PORT)
|
||||
public class AnsAutoServiceRegistrationIpNetworkInterfaceTests {
|
||||
|
||||
@Autowired
|
||||
private AnsRegistration registration;
|
||||
|
||||
@Autowired
|
||||
private AnsAutoServiceRegistration ansAutoServiceRegistration;
|
||||
|
||||
@Autowired
|
||||
private AnsProperties properties;
|
||||
|
||||
@Autowired
|
||||
private InetUtils inetUtils;
|
||||
|
||||
@Test
|
||||
public void contextLoads() throws Exception {
|
||||
|
||||
assertNotNull("AnsRegistration was not created", registration);
|
||||
assertNotNull("AnsProperties was not created", properties);
|
||||
assertNotNull("AnsAutoServiceRegistration was not created",
|
||||
ansAutoServiceRegistration);
|
||||
|
||||
checkoutAnsDiscoveryServiceIP();
|
||||
|
||||
}
|
||||
|
||||
private void checkoutAnsDiscoveryServiceIP() {
|
||||
assertEquals("AnsProperties 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,
|
||||
AnsDiscoveryClientAutoConfiguration.class, AnsAutoConfiguration.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.alicloud.ans.client-interface-name",
|
||||
networkInterface.getName());
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
catch (Exception e) {
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,92 @@
|
||||
/*
|
||||
* 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.alicloud.ans.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 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.alicloud.ans.AnsAutoConfiguration;
|
||||
import org.springframework.cloud.alicloud.ans.AnsDiscoveryClientAutoConfiguration;
|
||||
import org.springframework.cloud.alicloud.context.ans.AnsProperties;
|
||||
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 = AnsAutoServiceRegistrationIpTests.TestConfig.class, properties = {
|
||||
"spring.application.name=myTestService1",
|
||||
"spring.cloud.alicloud.ans.client-domains=myTestService2",
|
||||
"spring.cloud.alicloud.ans.server-list=127.0.0.1",
|
||||
"spring.cloud.alicloud.ans.client-weight=2",
|
||||
"spring.cloud.alicloud.ans.server-port=8080",
|
||||
"spring.cloud.alicloud.ans.client-ip=123.123.123.123" }, webEnvironment = RANDOM_PORT)
|
||||
public class AnsAutoServiceRegistrationIpTests {
|
||||
|
||||
@Autowired
|
||||
private AnsRegistration registration;
|
||||
|
||||
@Autowired
|
||||
private AnsAutoServiceRegistration ansAutoServiceRegistration;
|
||||
|
||||
@Autowired
|
||||
private AnsProperties properties;
|
||||
|
||||
@Test
|
||||
public void contextLoads() throws Exception {
|
||||
|
||||
assertNotNull("AnsRegistration was not created", registration);
|
||||
assertNotNull("AnsProperties was not created", properties);
|
||||
assertNotNull("AnsAutoServiceRegistration was not created",
|
||||
ansAutoServiceRegistration);
|
||||
|
||||
checkoutAnsDiscoveryServiceIP();
|
||||
checkoutAnsDiscoveryServiceName();
|
||||
checkoutAnsDiscoveryWeight();
|
||||
}
|
||||
|
||||
private void checkoutAnsDiscoveryServiceIP() {
|
||||
assertEquals("AnsProperties service IP was wrong", "123.123.123.123",
|
||||
registration.getHost());
|
||||
}
|
||||
|
||||
private void checkoutAnsDiscoveryServiceName() {
|
||||
assertEquals("AnsDiscoveryProperties service name was wrong", "myTestService2",
|
||||
properties.getClientDomains());
|
||||
}
|
||||
|
||||
private void checkoutAnsDiscoveryWeight() {
|
||||
assertEquals(2L, properties.getClientWeight(), 0);
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@EnableAutoConfiguration
|
||||
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
|
||||
AnsDiscoveryClientAutoConfiguration.class, AnsAutoConfiguration.class })
|
||||
public static class TestConfig {
|
||||
}
|
||||
}
|
@ -0,0 +1,87 @@
|
||||
/*
|
||||
* 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.alicloud.ans.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.alicloud.ans.registry.AnsRegistration.MANAGEMENT_CONTEXT_PATH;
|
||||
import static org.springframework.cloud.alicloud.ans.registry.AnsRegistration.MANAGEMENT_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.alicloud.ans.AnsAutoConfiguration;
|
||||
import org.springframework.cloud.alicloud.ans.AnsDiscoveryClientAutoConfiguration;
|
||||
import org.springframework.cloud.alicloud.context.ans.AnsProperties;
|
||||
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 = AnsAutoServiceRegistrationManagementPortTests.TestConfig.class, properties = {
|
||||
"spring.application.name=myTestService1", "management.port=8888",
|
||||
"management.context-path=/test-context-path",
|
||||
"spring.cloud.alicloud.ans.server-list=127.0.0.1",
|
||||
"spring.cloud.alicloud.ans.server-port=8080" }, webEnvironment = RANDOM_PORT)
|
||||
public class AnsAutoServiceRegistrationManagementPortTests {
|
||||
|
||||
@Autowired
|
||||
private AnsRegistration registration;
|
||||
|
||||
@Autowired
|
||||
private AnsAutoServiceRegistration ansAutoServiceRegistration;
|
||||
|
||||
@Autowired
|
||||
private AnsProperties properties;
|
||||
|
||||
@Test
|
||||
public void contextLoads() throws Exception {
|
||||
|
||||
assertNotNull("AnsRegistration was not created", registration);
|
||||
assertNotNull("AnsProperties was not created", properties);
|
||||
assertNotNull("AnsAutoServiceRegistration was not created",
|
||||
ansAutoServiceRegistration);
|
||||
|
||||
checkoutNacosDiscoveryManagementData();
|
||||
|
||||
}
|
||||
|
||||
private void checkoutNacosDiscoveryManagementData() {
|
||||
assertEquals("AnsProperties management port was wrong", "8888",
|
||||
properties.getClientMetadata().get(MANAGEMENT_PORT));
|
||||
|
||||
assertEquals("AnsProperties management context path was wrong",
|
||||
"/test-context-path",
|
||||
properties.getClientMetadata().get(MANAGEMENT_CONTEXT_PATH));
|
||||
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@EnableAutoConfiguration
|
||||
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
|
||||
AnsDiscoveryClientAutoConfiguration.class, AnsAutoConfiguration.class })
|
||||
public static class TestConfig {
|
||||
}
|
||||
}
|
@ -0,0 +1,81 @@
|
||||
/*
|
||||
* 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.alicloud.ans.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 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.alicloud.ans.AnsAutoConfiguration;
|
||||
import org.springframework.cloud.alicloud.ans.AnsDiscoveryClientAutoConfiguration;
|
||||
import org.springframework.cloud.alicloud.context.ans.AnsProperties;
|
||||
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 = AnsAutoServiceRegistrationPortTests.TestConfig.class, properties = {
|
||||
"spring.application.name=myTestService1",
|
||||
"spring.cloud.alicloud.ans.server-list=127.0.0.1",
|
||||
"spring.cloud.alicloud.ans.server-port=8080",
|
||||
"spring.cloud.alicloud.ans.client-port=8888" }, webEnvironment = RANDOM_PORT)
|
||||
public class AnsAutoServiceRegistrationPortTests {
|
||||
|
||||
@Autowired
|
||||
private AnsRegistration registration;
|
||||
|
||||
@Autowired
|
||||
private AnsAutoServiceRegistration ansAutoServiceRegistration;
|
||||
|
||||
@Autowired
|
||||
private AnsProperties properties;
|
||||
|
||||
@Test
|
||||
public void contextLoads() throws Exception {
|
||||
|
||||
assertNotNull("AnsRegistration was not created", registration);
|
||||
assertNotNull("AnsDiscoveryProperties was not created", properties);
|
||||
assertNotNull("AnsAutoServiceRegistration was not created",
|
||||
ansAutoServiceRegistration);
|
||||
|
||||
checkoutAnsDiscoveryServicePort();
|
||||
|
||||
}
|
||||
|
||||
private void checkoutAnsDiscoveryServicePort() {
|
||||
assertEquals("AnsDiscoveryProperties service Port was wrong", 8888,
|
||||
registration.getPort());
|
||||
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@EnableAutoConfiguration
|
||||
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
|
||||
AnsDiscoveryClientAutoConfiguration.class, AnsAutoConfiguration.class })
|
||||
public static class TestConfig {
|
||||
}
|
||||
}
|
@ -0,0 +1,160 @@
|
||||
/*
|
||||
* 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.alicloud.ans.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 java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import com.alibaba.ans.core.NamingService;
|
||||
import com.alibaba.ans.shaded.com.taobao.vipserver.client.core.Host;
|
||||
|
||||
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.context.embedded.LocalServerPort;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.cloud.alicloud.ans.AnsAutoConfiguration;
|
||||
import org.springframework.cloud.alicloud.ans.AnsDiscoveryClientAutoConfiguration;
|
||||
import org.springframework.cloud.alicloud.ans.endpoint.AnsEndpoint;
|
||||
import org.springframework.cloud.alicloud.context.ans.AnsProperties;
|
||||
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 = AnsAutoServiceRegistrationTests.TestConfig.class, properties = {
|
||||
"spring.application.name=myTestService1",
|
||||
"spring.cloud.alicloud.ans.server-list=127.0.0.1",
|
||||
"spring.cloud.alicloud.ans.server-port=8080",
|
||||
"spring.cloud.alicloud.ans.secure=true",
|
||||
"spring.cloud.alicloud.ans.endpoint=test-endpoint" }, webEnvironment = RANDOM_PORT)
|
||||
public class AnsAutoServiceRegistrationTests {
|
||||
|
||||
@Autowired
|
||||
private AnsRegistration registration;
|
||||
|
||||
@Autowired
|
||||
private AnsAutoServiceRegistration ansAutoServiceRegistration;
|
||||
|
||||
@LocalServerPort
|
||||
private int port;
|
||||
|
||||
@Autowired
|
||||
private AnsProperties properties;
|
||||
|
||||
@Autowired
|
||||
private InetUtils inetUtils;
|
||||
|
||||
@Test
|
||||
public void contextLoads() throws Exception {
|
||||
|
||||
assertNotNull("AnsRegistration was not created", registration);
|
||||
assertNotNull("AnsProperties was not created", properties);
|
||||
assertNotNull("AnsAutoServiceRegistration was not created",
|
||||
ansAutoServiceRegistration);
|
||||
|
||||
checkoutAnsDiscoveryServerList();
|
||||
checkoutAnsDiscoveryServerPort();
|
||||
|
||||
checkoutAnsDiscoveryServiceName();
|
||||
checkoutAnsDiscoveryServiceIP();
|
||||
checkoutAnsDiscoveryServicePort();
|
||||
checkoutAnsDiscoverySecure();
|
||||
|
||||
checkAutoRegister();
|
||||
|
||||
checkoutEndpoint();
|
||||
|
||||
}
|
||||
|
||||
private void checkAutoRegister() {
|
||||
assertTrue("Ans Auto Registration was not start",
|
||||
ansAutoServiceRegistration.isRunning());
|
||||
}
|
||||
|
||||
private void checkoutAnsDiscoveryServerList() {
|
||||
assertEquals("AnsDiscoveryProperties server list was wrong", "127.0.0.1",
|
||||
properties.getServerList());
|
||||
}
|
||||
|
||||
private void checkoutAnsDiscoveryServerPort() {
|
||||
assertEquals("AnsDiscoveryProperties server port was wrong", "8080",
|
||||
properties.getServerPort());
|
||||
}
|
||||
|
||||
private void checkoutAnsDiscoveryServiceName() {
|
||||
assertEquals("AnsDiscoveryProperties service name was wrong", "myTestService1",
|
||||
properties.getClientDomains());
|
||||
}
|
||||
|
||||
private void checkoutAnsDiscoveryServiceIP() {
|
||||
assertEquals("AnsDiscoveryProperties service IP was wrong",
|
||||
inetUtils.findFirstNonLoopbackHostInfo().getIpAddress(),
|
||||
registration.getHost());
|
||||
}
|
||||
|
||||
private void checkoutAnsDiscoveryServicePort() {
|
||||
assertEquals("AnsDiscoveryProperties service Port was wrong", port,
|
||||
registration.getPort());
|
||||
}
|
||||
|
||||
private void checkoutAnsDiscoverySecure() {
|
||||
assertTrue("AnsDiscoveryProperties secure should be true", properties.isSecure());
|
||||
|
||||
}
|
||||
|
||||
private void checkoutEndpoint() throws Exception {
|
||||
AnsEndpoint ansEndpoint = new AnsEndpoint(properties);
|
||||
Map<String, Object> map = ansEndpoint.invoke();
|
||||
assertEquals(map.get("ansProperties"), properties);
|
||||
|
||||
Map<String, Object> subscribes = new HashMap<>();
|
||||
Set<String> subscribeServices = NamingService.getDomsSubscribed();
|
||||
for (String service : subscribeServices) {
|
||||
try {
|
||||
List<Host> hosts = NamingService.getHosts(service);
|
||||
subscribes.put(service, hosts);
|
||||
}
|
||||
catch (Exception ignoreException) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
assertEquals(map.get("subscribes"), subscribes);
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@EnableAutoConfiguration
|
||||
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
|
||||
AnsDiscoveryClientAutoConfiguration.class, AnsAutoConfiguration.class })
|
||||
public static class TestConfig {
|
||||
}
|
||||
}
|
@ -0,0 +1,86 @@
|
||||
/*
|
||||
* 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.alicloud.ans.ribbon;
|
||||
|
||||
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.alicloud.ans.AnsAutoConfiguration;
|
||||
import org.springframework.cloud.alicloud.ans.AnsDiscoveryClientAutoConfiguration;
|
||||
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
|
||||
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import com.netflix.client.config.DefaultClientConfigImpl;
|
||||
import com.netflix.client.config.IClientConfig;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
|
||||
|
||||
/**
|
||||
* @author xiaojing
|
||||
*/
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = AnsRibbonClientConfigurationTests.TestConfig.class, properties = {
|
||||
"spring.application.name=myTestService1",
|
||||
"spring.cloud.alicloud.ans.server-list=127.0.0.1",
|
||||
"spring.cloud.alicloud.ans.server-port=8080",
|
||||
"spring.cloud.alicloud.ans.endpoint=test-endpoint" }, webEnvironment = RANDOM_PORT)
|
||||
public class AnsRibbonClientConfigurationTests {
|
||||
|
||||
@Autowired
|
||||
private AnsServerList serverList;
|
||||
|
||||
@Test
|
||||
public void contextLoads() throws Exception {
|
||||
assertThat(serverList.getDom()).isEqualTo("myapp");
|
||||
}
|
||||
|
||||
@Configuration
|
||||
public static class AnsRibbonTestConfiguration {
|
||||
|
||||
@Bean
|
||||
IClientConfig iClientConfig() {
|
||||
DefaultClientConfigImpl config = new DefaultClientConfigImpl();
|
||||
config.setClientName("myapp");
|
||||
return config;
|
||||
}
|
||||
|
||||
@Bean
|
||||
@LoadBalanced
|
||||
RestTemplate restTemplate() {
|
||||
return new RestTemplate();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@EnableAutoConfiguration
|
||||
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
|
||||
AnsDiscoveryClientAutoConfiguration.class, AnsAutoConfiguration.class,
|
||||
AnsRibbonTestConfiguration.class, RibbonAnsAutoConfiguration.class,
|
||||
AnsRibbonClientConfiguration.class })
|
||||
public static class TestConfig {
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,157 @@
|
||||
/*
|
||||
* 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.alicloud.ans.ribbon;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Matchers.anyString;
|
||||
import static org.mockito.Matchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.springframework.cloud.alicloud.ans.test.AnsMockTest.hostInstance;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.powermock.api.mockito.PowerMockito;
|
||||
import org.powermock.core.classloader.annotations.PrepareForTest;
|
||||
import org.powermock.modules.junit4.PowerMockRunner;
|
||||
|
||||
import com.alibaba.ans.core.NamingService;
|
||||
import com.alibaba.ans.shaded.com.taobao.vipserver.client.core.Host;
|
||||
|
||||
import com.netflix.client.config.IClientConfig;
|
||||
|
||||
/**
|
||||
* @author xiaojing
|
||||
*/
|
||||
@RunWith(PowerMockRunner.class)
|
||||
@PrepareForTest({ NamingService.class, AnsServer.class })
|
||||
public class AnsServerListTests {
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
public void testEmptyInstancesReturnsEmptyList() throws Exception {
|
||||
|
||||
PowerMockito.mockStatic(NamingService.class);
|
||||
when(NamingService.getHosts(anyString())).thenReturn(Collections.EMPTY_LIST);
|
||||
|
||||
IClientConfig clientConfig = mock(IClientConfig.class);
|
||||
when(clientConfig.getClientName()).thenReturn("test-service");
|
||||
AnsServerList serverList = new AnsServerList("test-service");
|
||||
serverList.initWithNiwsConfig(clientConfig);
|
||||
List<AnsServer> servers = serverList.getInitialListOfServers();
|
||||
assertThat(servers).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
public void testGetServers() throws Exception {
|
||||
|
||||
ArrayList<Host> hosts = new ArrayList<>();
|
||||
hosts.add(hostInstance("test-service", true,
|
||||
Collections.<String, String> emptyMap()));
|
||||
|
||||
PowerMockito.mockStatic(NamingService.class);
|
||||
when(NamingService.getHosts(anyString())).thenReturn(hosts);
|
||||
|
||||
IClientConfig clientConfig = mock(IClientConfig.class);
|
||||
when(clientConfig.getClientName()).thenReturn("test-service");
|
||||
AnsServerList serverList = new AnsServerList("test-service");
|
||||
serverList.initWithNiwsConfig(clientConfig);
|
||||
List<AnsServer> servers = serverList.getInitialListOfServers();
|
||||
assertThat(servers).hasSize(1);
|
||||
|
||||
servers = serverList.getUpdatedListOfServers();
|
||||
assertThat(servers).hasSize(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
public void testGetServersWithInstanceStatus() throws Exception {
|
||||
ArrayList<Host> hosts = new ArrayList<>();
|
||||
|
||||
HashMap<String, String> map1 = new HashMap<>();
|
||||
map1.put("instanceNum", "1");
|
||||
HashMap<String, String> map2 = new HashMap<>();
|
||||
map2.put("instanceNum", "2");
|
||||
hosts.add(hostInstance("test-service", false, map1));
|
||||
hosts.add(hostInstance("test-service", true, map2));
|
||||
|
||||
PowerMockito.mockStatic(NamingService.class);
|
||||
|
||||
List<Host> returnInstances = new LinkedList<>();
|
||||
|
||||
for (Host host : hosts) {
|
||||
if (host.isValid()) {
|
||||
returnInstances.add(host);
|
||||
}
|
||||
}
|
||||
when(NamingService.getHosts(eq("test-service"))).thenReturn(returnInstances);
|
||||
|
||||
IClientConfig clientConfig = mock(IClientConfig.class);
|
||||
when(clientConfig.getClientName()).thenReturn("test-service");
|
||||
AnsServerList serverList = new AnsServerList("test-service");
|
||||
serverList.initWithNiwsConfig(clientConfig);
|
||||
List<AnsServer> servers = serverList.getInitialListOfServers();
|
||||
assertThat(servers).hasSize(1);
|
||||
|
||||
AnsServer ansServer = servers.get(0);
|
||||
Host host = ansServer.getHealthService();
|
||||
|
||||
assertThat(ansServer.getMetaInfo().getInstanceId()).isEqualTo(
|
||||
host.getIp() + ":" + host.getHostname() + ":" + host.getPort());
|
||||
assertThat(ansServer.getHealthService().isValid()).isEqualTo(true);
|
||||
assertThat(ansServer.getHealthService().getHostname()).isEqualTo("test-service");
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUpdateServers() throws Exception {
|
||||
ArrayList<Host> hosts = new ArrayList<>();
|
||||
|
||||
HashMap<String, String> map = new HashMap<>();
|
||||
map.put("instanceNum", "1");
|
||||
hosts.add(hostInstance("test-service", true, map));
|
||||
|
||||
PowerMockito.mockStatic(NamingService.class);
|
||||
|
||||
List<Host> returnInstances = new LinkedList<>();
|
||||
for (Host host : hosts) {
|
||||
if (host.isValid()) {
|
||||
returnInstances.add(host);
|
||||
}
|
||||
}
|
||||
when(NamingService.getHosts(eq("test-service"))).thenReturn(returnInstances);
|
||||
|
||||
when(NamingService.getHosts(eq("test-service"))).thenReturn(returnInstances);
|
||||
|
||||
IClientConfig clientConfig = mock(IClientConfig.class);
|
||||
when(clientConfig.getClientName()).thenReturn("test-service");
|
||||
AnsServerList serverList = new AnsServerList("test-service");
|
||||
serverList.initWithNiwsConfig(clientConfig);
|
||||
|
||||
List<AnsServer> servers = serverList.getUpdatedListOfServers();
|
||||
assertThat(servers).hasSize(1);
|
||||
|
||||
assertThat(servers.get(0).getHealthService().isValid()).isEqualTo(true);
|
||||
}
|
||||
}
|
@ -0,0 +1,45 @@
|
||||
/*
|
||||
* 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.alicloud.ans.test;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import com.alibaba.ans.shaded.com.taobao.vipserver.client.core.Host;
|
||||
|
||||
/**
|
||||
* @author xiaojing
|
||||
*/
|
||||
public class AnsMockTest {
|
||||
|
||||
public static Host hostInstance(String serviceName, boolean valid,
|
||||
Map<String, String> metadata) {
|
||||
Host host = new Host();
|
||||
host.setHostname(serviceName);
|
||||
host.setValid(valid);
|
||||
return host;
|
||||
}
|
||||
|
||||
public static Host hostInstance(String serviceName, boolean valid, String ip,
|
||||
int port, Map<String, String> metadata) {
|
||||
Host host = new Host();
|
||||
host.setIp(ip);
|
||||
host.setPort(port);
|
||||
host.setValid(valid);
|
||||
host.setHostname(serviceName);
|
||||
return host;
|
||||
}
|
||||
}
|
@ -17,15 +17,20 @@ package org.springframework.cloud.alicloud.sms;
|
||||
|
||||
import java.text.ParseException;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.cloud.alicloud.context.AliCloudProperties;
|
||||
import org.springframework.cloud.alicloud.context.sms.SmsProperties;
|
||||
import org.springframework.cloud.alicloud.sms.base.DefaultAlicomMessagePuller;
|
||||
import org.springframework.cloud.alicloud.sms.endpoint.EndpointManager;
|
||||
import org.springframework.cloud.alicloud.sms.endpoint.ReceiveMessageEntity;
|
||||
|
||||
import com.aliyuncs.dysmsapi.model.v20170525.*;
|
||||
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsRequest;
|
||||
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse;
|
||||
import com.aliyuncs.dysmsapi.model.v20170525.SendBatchSmsRequest;
|
||||
import com.aliyuncs.dysmsapi.model.v20170525.SendBatchSmsResponse;
|
||||
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
|
||||
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
|
||||
import com.aliyuncs.exceptions.ClientException;
|
||||
import com.aliyuncs.exceptions.ServerException;
|
||||
|
||||
@ -34,7 +39,7 @@ import com.aliyuncs.exceptions.ServerException;
|
||||
*/
|
||||
public final class SmsServiceImpl extends AbstractSmsService {
|
||||
|
||||
private static final Log log = LogFactory.getLog(SmsServiceImpl.class);
|
||||
private static final Logger log = LoggerFactory.getLogger(SmsServiceImpl.class);
|
||||
/**
|
||||
* will expose user to call this method send sms message
|
||||
* @param sendSmsRequest
|
||||
|
@ -15,14 +15,6 @@
|
||||
*/
|
||||
package org.springframework.cloud.alicloud.sms.base;
|
||||
|
||||
import com.aliyun.mns.client.CloudQueue;
|
||||
import com.aliyun.mns.common.ClientException;
|
||||
import com.aliyun.mns.common.ServiceException;
|
||||
import com.aliyun.mns.model.Message;
|
||||
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
@ -33,12 +25,22 @@ import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledThreadPoolExecutor;
|
||||
|
||||
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.aliyun.mns.client.CloudQueue;
|
||||
import com.aliyun.mns.common.ClientException;
|
||||
import com.aliyun.mns.common.ServiceException;
|
||||
import com.aliyun.mns.model.Message;
|
||||
|
||||
/**
|
||||
* 阿里通信官方消息默认拉取工具类
|
||||
*/
|
||||
public class DefaultAlicomMessagePuller {
|
||||
|
||||
private Log logger = LogFactory.getLog(DefaultAlicomMessagePuller.class);
|
||||
private static final Logger log = LoggerFactory
|
||||
.getLogger(DefaultAlicomMessagePuller.class);
|
||||
|
||||
private String mnsAccountEndpoint = "https://1943695596114318.mns.cn-hangzhou.aliyuncs.com/";// 阿里通信消息的endpoint,固定。
|
||||
private String endpointNameForPop = "cn-hangzhou";
|
||||
@ -103,7 +105,7 @@ public class DefaultAlicomMessagePuller {
|
||||
sPollingMap.put(queueName, false);
|
||||
lockObj.notifyAll();
|
||||
if (debugLogOpen) {
|
||||
logger.info("PullMessageTask_WakeUp:Everyone WakeUp and Work!");
|
||||
log.info("PullMessageTask_WakeUp:Everyone WakeUp and Work!");
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -131,7 +133,7 @@ public class DefaultAlicomMessagePuller {
|
||||
if (p != null && p) {
|
||||
try {
|
||||
if (debugLogOpen) {
|
||||
logger.info("PullMessageTask_sleep:"
|
||||
log.info("PullMessageTask_sleep:"
|
||||
+ Thread.currentThread().getName()
|
||||
+ " Have a nice sleep!");
|
||||
}
|
||||
@ -140,7 +142,7 @@ public class DefaultAlicomMessagePuller {
|
||||
}
|
||||
catch (InterruptedException e) {
|
||||
if (debugLogOpen) {
|
||||
logger.info("PullMessageTask_Interrupted!"
|
||||
log.info("PullMessageTask_Interrupted!"
|
||||
+ Thread.currentThread().getName()
|
||||
+ " QueueName is " + queueName);
|
||||
}
|
||||
@ -158,7 +160,7 @@ public class DefaultAlicomMessagePuller {
|
||||
if (debugLogOpen) {
|
||||
SimpleDateFormat format = new SimpleDateFormat(
|
||||
"yyyy-MM-dd HH:mm:ss");
|
||||
logger.info("PullMessageTask_popMessage:"
|
||||
log.info("PullMessageTask_popMessage:"
|
||||
+ Thread.currentThread().getName() + "-popDone at "
|
||||
+ "," + format.format(new Date()) + " msgSize="
|
||||
+ (popMsg == null ? 0 : popMsg.getMessageId()));
|
||||
@ -171,7 +173,7 @@ public class DefaultAlicomMessagePuller {
|
||||
else {
|
||||
if (setPolling(queueName)) {
|
||||
if (debugLogOpen) {
|
||||
logger.info("PullMessageTask_setPolling:"
|
||||
log.info("PullMessageTask_setPolling:"
|
||||
+ Thread.currentThread().getName() + " Polling!");
|
||||
}
|
||||
}
|
||||
@ -180,7 +182,7 @@ public class DefaultAlicomMessagePuller {
|
||||
}
|
||||
do {
|
||||
if (debugLogOpen) {
|
||||
logger.info("PullMessageTask_Keep_Polling"
|
||||
log.info("PullMessageTask_Keep_Polling"
|
||||
+ Thread.currentThread().getName()
|
||||
+ "KEEP Polling!");
|
||||
}
|
||||
@ -189,7 +191,7 @@ public class DefaultAlicomMessagePuller {
|
||||
}
|
||||
catch (ClientException e) {
|
||||
if (debugLogOpen) {
|
||||
logger.info(
|
||||
log.info(
|
||||
"PullMessageTask_Pop_Message:ClientException Refresh accessKey"
|
||||
+ e);
|
||||
}
|
||||
@ -200,7 +202,7 @@ public class DefaultAlicomMessagePuller {
|
||||
}
|
||||
catch (ServiceException e) {
|
||||
if (debugLogOpen) {
|
||||
logger.info(
|
||||
log.info(
|
||||
"PullMessageTask_Pop_Message:ServiceException Refresh accessKey"
|
||||
+ e);
|
||||
}
|
||||
@ -211,7 +213,7 @@ public class DefaultAlicomMessagePuller {
|
||||
}
|
||||
catch (Exception e) {
|
||||
if (debugLogOpen) {
|
||||
logger.info(
|
||||
log.info(
|
||||
"PullMessageTask_Pop_Message:Exception Happened when polling popMessage: "
|
||||
+ e);
|
||||
}
|
||||
@ -224,7 +226,7 @@ public class DefaultAlicomMessagePuller {
|
||||
if (dealResult) {
|
||||
// remember to delete message when consume message successfully.
|
||||
if (debugLogOpen) {
|
||||
logger.info("PullMessageTask_Deal_Message:"
|
||||
log.info("PullMessageTask_Deal_Message:"
|
||||
+ Thread.currentThread().getName() + "deleteMessage "
|
||||
+ popMsg.getMessageId());
|
||||
}
|
||||
@ -232,19 +234,19 @@ public class DefaultAlicomMessagePuller {
|
||||
}
|
||||
}
|
||||
catch (ClientException e) {
|
||||
logger.error("PullMessageTask_execute_error,messageType:"
|
||||
+ messageType + ",queueName:" + queueName, e);
|
||||
log.error("PullMessageTask_execute_error,messageType:" + messageType
|
||||
+ ",queueName:" + queueName, e);
|
||||
break;
|
||||
|
||||
}
|
||||
catch (ServiceException e) {
|
||||
if (e.getErrorCode().equals("AccessDenied")) {
|
||||
logger.error("PullMessageTask_execute_error,messageType:"
|
||||
log.error("PullMessageTask_execute_error,messageType:"
|
||||
+ messageType + ",queueName:" + queueName
|
||||
+ ",please check messageType and queueName", e);
|
||||
}
|
||||
else {
|
||||
logger.error("PullMessageTask_execute_error,messageType:"
|
||||
log.error("PullMessageTask_execute_error,messageType:"
|
||||
+ messageType + ",queueName:" + queueName, e);
|
||||
}
|
||||
break;
|
||||
@ -252,30 +254,30 @@ public class DefaultAlicomMessagePuller {
|
||||
}
|
||||
catch (com.aliyuncs.exceptions.ClientException e) {
|
||||
if (e.getErrCode().equals("InvalidAccessKeyId.NotFound")) {
|
||||
logger.error("PullMessageTask_execute_error,messageType:"
|
||||
log.error("PullMessageTask_execute_error,messageType:"
|
||||
+ messageType + ",queueName:" + queueName
|
||||
+ ",please check AccessKeyId", e);
|
||||
}
|
||||
if (e.getErrCode().equals("SignatureDoesNotMatch")) {
|
||||
logger.error("PullMessageTask_execute_error,messageType:"
|
||||
log.error("PullMessageTask_execute_error,messageType:"
|
||||
+ messageType + ",queueName:" + queueName
|
||||
+ ",please check AccessKeySecret", e);
|
||||
}
|
||||
else {
|
||||
logger.error("PullMessageTask_execute_error,messageType:"
|
||||
log.error("PullMessageTask_execute_error,messageType:"
|
||||
+ messageType + ",queueName:" + queueName, e);
|
||||
}
|
||||
break;
|
||||
|
||||
}
|
||||
catch (Exception e) {
|
||||
logger.error("PullMessageTask_execute_error,messageType:"
|
||||
+ messageType + ",queueName:" + queueName, e);
|
||||
log.error("PullMessageTask_execute_error,messageType:" + messageType
|
||||
+ ",queueName:" + queueName, e);
|
||||
try {
|
||||
Thread.sleep(sleepSecondWhenNoData);
|
||||
}
|
||||
catch (InterruptedException e1) {
|
||||
logger.error("PullMessageTask_execute_error,messageType:"
|
||||
log.error("PullMessageTask_execute_error,messageType:"
|
||||
+ messageType + ",queueName:" + queueName, e);
|
||||
}
|
||||
}
|
||||
|
@ -15,6 +15,15 @@
|
||||
*/
|
||||
package org.springframework.cloud.alicloud.sms.base;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.TimeZone;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.aliyun.mns.client.CloudAccount;
|
||||
import com.aliyun.mns.client.CloudQueue;
|
||||
import com.aliyun.mns.client.MNSClient;
|
||||
@ -27,21 +36,13 @@ import com.aliyuncs.http.MethodType;
|
||||
import com.aliyuncs.http.ProtocolType;
|
||||
import com.aliyuncs.profile.DefaultProfile;
|
||||
import com.aliyuncs.profile.IClientProfile;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.TimeZone;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
|
||||
/**
|
||||
* 获取接收云通信消息的临时token
|
||||
*
|
||||
*/
|
||||
public class TokenGetterForAlicom {
|
||||
private Log logger = LogFactory.getLog(TokenGetterForAlicom.class);
|
||||
private static final Logger log = LoggerFactory.getLogger(TokenGetterForAlicom.class);
|
||||
private String accessKeyId;
|
||||
private String accessKeySecret;
|
||||
private String endpointNameForPop;
|
||||
@ -100,7 +101,7 @@ public class TokenGetterForAlicom {
|
||||
return token;
|
||||
}
|
||||
else {
|
||||
logger.error("getTokenFromRemote_error,messageType:" + messageType + ",code:"
|
||||
log.error("getTokenFromRemote_error,messageType:" + messageType + ",code:"
|
||||
+ response.getCode() + ",message:" + response.getMessage());
|
||||
throw new ServerException(response.getCode(), response.getMessage());
|
||||
}
|
||||
@ -124,8 +125,8 @@ public class TokenGetterForAlicom {
|
||||
CloudAccount account = new CloudAccount(token.getTempAccessKeyId(),
|
||||
token.getTempAccessKeySecret(), mnsAccountEndpoint,
|
||||
token.getToken());
|
||||
// logger.warn("ak:"+token.getTempAccessKey());
|
||||
// logger.warn("token:"+token.getToken());
|
||||
// log.warn("ak:"+token.getTempAccessKey());
|
||||
// log.warn("token:"+token.getToken());
|
||||
MNSClient client = account.getMNSClient();
|
||||
CloudQueue queue = client.getQueueRef(queueName);
|
||||
token.setClient(client);
|
||||
|
@ -22,7 +22,7 @@ import java.util.Map;
|
||||
public class SmsEndpoint extends AbstractEndpoint<Map<String, Object>> {
|
||||
|
||||
public SmsEndpoint() {
|
||||
super("sms_info");
|
||||
super("sms");
|
||||
}
|
||||
|
||||
@Override
|
||||
|
Loading…
x
Reference in New Issue
Block a user