Browse Source

nacos-client0.6.2解决了0.2.1无法注册服务的bug;nacos使用logback,因此需要引入logback配置文件,否则缺省只输出info和error的日志;实现服务注册。

weihf 5 years ago
parent
commit
d676dd67d4

+ 11 - 23
ipu-rest-scaffold/pom.xml

@ -63,34 +63,17 @@
63 63
			<artifactId>mongo-java-driver</artifactId>
64 64
			<version>${mongo.java.driver}</version>
65 65
		</dependency>
66
		<dependency>
67
			<groupId>org.springframework.boot</groupId>
68
			<artifactId>spring-boot-starter-test</artifactId>
69
			<scope>test</scope>
70
			<exclusions>
71
				<exclusion>
72
					<groupId>org.mockito</groupId>
73
					<artifactId>mockito-core</artifactId>
74
				</exclusion>
75
			</exclusions>
76
		</dependency>
77
		<!-- 提供http接口以便停止springboot应用 -->
78
		<dependency>
79
			<groupId>org.springframework.boot</groupId>
80
			<artifactId>spring-boot-starter-actuator</artifactId>
81
		</dependency>
82
		<!--devtools热部署  -->
83
		<dependency>
84
			<groupId>org.springframework.boot</groupId>
85
			<artifactId>spring-boot-devtools</artifactId>
86
			<optional>true</optional>
87
			<scope>runtime</scope>
88
		</dependency>
89 66
		<!-- 引入nacos服务配置中心 -->
90 67
		<dependency>
91 68
			<groupId>com.alibaba.boot</groupId>
92 69
			<artifactId>nacos-config-spring-boot-starter</artifactId>
93 70
			<version>${nacos.version}</version>
71
			<exclusions>
72
				<exclusion>
73
					<groupId>com.alibaba.nacos</groupId>
74
					<artifactId>nacos-client</artifactId>
75
				</exclusion>
76
			</exclusions>
94 77
		</dependency>
95 78
		<!-- 引入nacos服务注册中心 -->
96 79
		<dependency>
@ -98,6 +81,11 @@
98 81
			<artifactId>nacos-discovery-spring-boot-starter</artifactId>
99 82
			<version>${nacos.version}</version>
100 83
		</dependency>
84
		<dependency>
85
		<groupId>com.alibaba.nacos</groupId>
86
                    <artifactId>nacos-client</artifactId>
87
                    <version>0.6.2</version>
88
                    </dependency>
101 89
	</dependencies>
102 90
103 91
	<build>

+ 1 - 1
ipu-rest-scaffold/src/main/java/com/ai/ipu/server/config/NacosListenerConfiguration.java

@ -36,7 +36,7 @@ public class NacosListenerConfiguration {
36 36
        };
37 37

38 38
        //添加事件监听
39
        configService.addListener("com.ai.ipu.nacos", DEFAULT_GROUP, listener);
39
        configService.addListener("example", DEFAULT_GROUP, listener);
40 40
        
41 41
        //取消事件监听
42 42
        //configService.removeListener("com.ai.ipu.nacos", DEFAULT_GROUP, listener);

+ 47 - 0
ipu-rest-scaffold/src/main/java/com/ai/ipu/server/config/NacosRegisterConfiguration.java

@ -0,0 +1,47 @@
1
package com.ai.ipu.server.config;
2

3
import com.ai.ipu.server.util.IpUtil;
4
import com.alibaba.nacos.api.annotation.NacosInjected;
5
import com.alibaba.nacos.api.naming.NamingService;
6
import com.alibaba.nacos.api.naming.pojo.Instance;
7

8
import org.springframework.beans.factory.annotation.Value;
9
import org.springframework.context.annotation.Configuration;
10

11
import javax.annotation.PostConstruct;
12

13
@Configuration
14
public class NacosRegisterConfiguration {
15

16
	@Value("${server.port}")
17
	private int serverPort;
18

19
	@Value("${spring.application.name}")
20
	private String applicationName;
21

22
	@NacosInjected
23
	private NamingService namingService;
24

25
	@PostConstruct
26
	public void registerInstance() {
27
		try {
28
			//完全自己注册,用于定位问题、解决问题
29
//			Instance instance = new Instance();
30
//			instance.setIp("10.1.40.130");//IP
31
//			instance.setPort(serverPort);//端口
32
//			instance.setHealthy(true);//健康状态
33
//			instance.setWeight(1.0);//权重
34
//			instance.setInstanceId("10.1.40.130#8082#DEFAULT#DEFAULT_GROUP@@ipu-nacos-provider");
35
//			instance.addMetadata("nacos-sdk-java-discovery", "true");//元数据
36
//			instance.setClusterName("DEFAULT");
37
//			namingService.registerInstance(applicationName, instance);
38
			
39
			//利用nacos自动注册
40
			//ipu-basic里的IpUtil.getInet4Ip()只适用于只有1块网卡的场合
41
			//IpUtil.getHostAddress()在有多块网卡时,取不是.1结尾并且ip地址排序最小的做为当前ip
42
			namingService.registerInstance(applicationName, IpUtil.getHostAddress(), serverPort, "DEFAULT");
43
		} catch (Exception e) {
44
			e.printStackTrace();
45
		}
46
	}
47
}

+ 4 - 4
ipu-rest-scaffold/src/main/java/com/ai/ipu/server/control/NacosConfigController.java

@ -17,7 +17,7 @@ import com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource;
17 17

18 18
@Controller
19 19
@RequestMapping("/nacos/config")
20
@NacosPropertySource(dataId = "com.ai.ipu.nacos", autoRefreshed = true)
20
@NacosPropertySource(dataId = "example", autoRefreshed = true)
21 21
public class NacosConfigController {
22 22
	private static final Logger logger = LoggerFactory.getLogger(NacosConfigController.class);
23 23
	
@ -28,7 +28,7 @@ public class NacosConfigController {
28 28
	//如果配置中心没有dataId以及sql的配置,则取defaultValue
29 29
	//autoRefreshed:是否动态刷新。如果是动态刷新,则配置中心dataId以及sql的配置发生变动,则取配置中心的数据;
30 30
	//如果不是动态刷新,则在应用启动时去配置中心获取一次dataId以及sql的配置
31
	@NacosValue(value = "${sql:defaultValue}", autoRefreshed = true)
31
	@NacosValue(value = "${sql:\"defaultValue\"}", autoRefreshed = true)
32 32
    private String sql;
33 33
	
34 34
	 @ResponseBody
@ -42,7 +42,7 @@ public class NacosConfigController {
42 42
	 public boolean setSql(JMap params) throws Exception {
43 43
		 try {
44 44
			    //将select * from display.tab_page_info发布到配置中心,dataId=com.ai.ipu.nacos,变量名=sql
45
	            configService.publishConfig("com.ai.ipu.nacos", DEFAULT_GROUP, "sql = select * from display.tab_page_info");
45
	            configService.publishConfig("example", DEFAULT_GROUP, "sql = select * from display.tab_page_info");
46 46
	            return true;
47 47
	        } catch (NacosException e) {
48 48
//	            e.printStackTrace();
@ -56,7 +56,7 @@ public class NacosConfigController {
56 56
	 public boolean removeSql(JMap params) throws Exception {
57 57
		 try {
58 58
			    //从配置中心删除配置,dataId=com.ai.ipu.nacos
59
	            configService.removeConfig("com.ai.ipu.nacos", DEFAULT_GROUP);
59
	            configService.removeConfig("example", DEFAULT_GROUP);
60 60
	            return true;
61 61
	        } catch (NacosException e) {
62 62
	            logger.error("从配置中心删除配置失败", e);

+ 4 - 3
ipu-rest-scaffold/src/main/java/com/ai/ipu/server/control/NacosConsumerControl.java

@ -31,11 +31,12 @@ public class NacosConsumerControl {
31 31
		try {
32 32
			if (namingService != null) {
33 33
				// 选择user_service服务的一个健康的实例(可配置负载均衡策略)
34
				Instance instance = namingService.selectOneHealthyInstance("ipu-nacos_cloud");
34
				Instance instance = namingService.selectOneHealthyInstance("ipu-rest-scaffold");
35 35
				// 拼接请求接口url并请求选取的实例
36
				String url = "http://" + instance.getIp() + ":" + instance.getPort() + "/provider/echo?message=" + appName;
36
				String url = "http://" + instance.getIp() + ":" + instance.getPort() + "/ipu/nacos/discovery/provider/echo?message=" + appName;
37
				logger.debug(String.format("请求URL:%s", url));
37 38
				ResponseEntity<String> entity = restTemplate.getForEntity(url, String.class);
38
		        System.out.println(String.format("请求URL:%s,响应结果:%s", url, entity.getBody()));
39
				logger.debug(String.format("响应结果:%s", entity.getBody()));
39 40
				return entity.getBody();
40 41
			}
41 42
		} catch (Exception e) {

+ 19 - 0
ipu-rest-scaffold/src/main/java/com/ai/ipu/server/control/NacosProviderControl.java

@ -0,0 +1,19 @@
1
package com.ai.ipu.server.control;
2

3

4
import org.springframework.stereotype.Controller;
5
import org.springframework.web.bind.annotation.GetMapping;
6
import org.springframework.web.bind.annotation.RequestMapping;
7
import org.springframework.web.bind.annotation.ResponseBody;
8

9
@Controller
10
@RequestMapping("/nacos/discovery/provider")
11
public class NacosProviderControl {
12

13
    @ResponseBody
14
	@GetMapping(value = "/echo")
15
    public String hello(String message) {
16
        return "Hello Nacos " + message;
17
    }
18
	
19
}

+ 59 - 0
ipu-rest-scaffold/src/main/java/com/ai/ipu/server/util/IpUtil.java

@ -0,0 +1,59 @@
1
package com.ai.ipu.server.util;
2

3

4
import java.net.Inet4Address;
5
import java.net.InetAddress;
6
import java.net.InetSocketAddress;
7
import java.net.NetworkInterface;
8
import java.net.SocketException;
9
import java.util.ArrayList;
10
import java.util.Collections;
11
import java.util.Enumeration;
12
import java.util.List;
13

14
/**
15
 * 地址工具类
16
 * 
17
 * @author Administrator
18
 *
19
 */
20
public class IpUtil {
21
	private static String hostAddress = null;
22
	
23
	/**
24
	 * 获取本机ip地址<BR/>
25
	 * 不会将.1结尾的ip作为合法地址</BR>
26
	 * 如果有多块网卡,将返回地址最小的那个<BR/>
27
	 * 可以在程序启动入口参数中指定本机地址
28
	 * 
29
	 * @return
30
	 * @throws SocketException
31
	 */
32
	public static String getHostAddress() throws SocketException {
33
		if(hostAddress!=null){
34
			return hostAddress;
35
		}
36
		
37
		InetAddress ip = null;
38
		List<String> addressList = new ArrayList<String>();
39
		Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
40
		while (allNetInterfaces.hasMoreElements())
41
		{
42
			NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
43
			Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
44
			while (addresses.hasMoreElements())
45
			{
46
				ip = (InetAddress) addresses.nextElement();
47
				if (ip != null && ip instanceof Inet4Address)
48
				{
49
					if (!ip.getHostAddress().endsWith(".1"))
50
							addressList.add(ip.getHostAddress());
51
				} 
52
			}
53
		}
54
		Collections.sort(addressList);
55
		hostAddress = (String)addressList.get(0);
56
		return hostAddress;
57
	}
58
	
59
}

+ 2 - 2
ipu-rest-scaffold/src/main/resources/dev/application.properties

@ -38,10 +38,10 @@ management.address=127.0.0.1
38 38
management.security.enabled=false
39 39

40 40
###配置nacos配置中心
41
nacos.config.server-addr=10.1.40.130:8848
41
nacos.config.server-addr=10.1.40.132:8848
42 42

43 43
###配置nacos注册中心
44
nacos.discovery.server-addr=10.1.40.130:8848
44
nacos.discovery.server-addr=10.1.40.132:8848
45 45

46 46
#设置开启热部署
47 47
spring.devtools.restart.enabled=true

+ 25 - 0
ipu-rest-scaffold/src/main/resources/dev/logback.xml

@ -0,0 +1,25 @@
1
<?xml version="1.0" encoding="UTF-8"?>
2
<configuration>
3
	<include resource="org/springframework/boot/logging/logback/base.xml" /> <!-- logback 提供的基本配置 -->
4
5
	<!-- 控制台 -->
6
	<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
7
		<encoder charset="UTF-8">
8
			<!-- <pattern>[%d{yyyy-MM-dd HH:mm:ss.SSS}] %5p %m%n</pattern> -->
9
			<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} {%thread} %-5level %logger{50}-%msg%n</pattern>
10
			<charset>UTF-8</charset> <!-- 解决中文乱码问题 -->
11
		</encoder>
12
	</appender>
13
14
	<!-- <root level="DEBUG"> -->
15
	<root level="ERROR"> <appender-ref ref="CONSOLE" /> </root> 
16
17
	<!-- 将上面两个 appender 关联到我们的项目 -->
18
	<logger name="com.ai.ipu" level="DEBUG"
19
		additivity="false"> <!-- name 是项目包名,为了方便调试,输出 DEBUG 级别及其以上的log -->
20
		<appender-ref ref="CONSOLE" />
21
	</logger>
22
        
23
	<logger name="org.springframework" level="INFO" />   <!-- spring 包下的 logger, 只输出 INFO 级别的 -->
24
25
</configuration>