瀏覽代碼

Nacos的服务注册和服务调用范例,目前支持URL拼接形式的调用

huangbo 4 年之前
父節點
當前提交
529198186a

+ 6 - 11
ipu-nacos-demo/pom.xml

@ -43,14 +43,14 @@
43 43
	</repositories>
44 44
45 45
	<properties>
46
		<start-class>com.ai.ipu.server.IpuNacosDemoStart</start-class>
46
		<start-class>com.ai.ipu.server.NacosDemoStart</start-class>
47 47
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
48 48
		<mongo.java.driver>3.11.2</mongo.java.driver>
49 49
		<ipu>3.1-SNAPSHOT</ipu>
50 50
		<jdk>1.8</jdk>
51 51
		<junit>4.12</junit>
52 52
		<spring-session.version>1.3.2.RELEASE</spring-session.version>
53
		<nacos>0.1.1</nacos>
53
		<nacos>0.1.7</nacos>
54 54
	</properties>
55 55
56 56
	<dependencies>
@ -71,17 +71,12 @@
71 71
			<groupId>com.alibaba.boot</groupId>
72 72
			<artifactId>nacos-config-spring-boot-starter</artifactId>
73 73
			<version>${nacos}</version>
74
			<exclusions>
75
				<exclusion>
76
					<groupId>com.alibaba.nacos</groupId>
77
					<artifactId>nacos-client</artifactId>
78
				</exclusion>
79
			</exclusions>
80 74
		</dependency>
75
		<!-- 引入nacos服务注册中心 -->
81 76
		<dependency>
82
			<groupId>com.alibaba.nacos</groupId>
83
			<artifactId>nacos-client</artifactId>
84
			<version>0.6.2</version>
77
			<groupId>com.alibaba.boot</groupId>
78
			<artifactId>nacos-discovery-spring-boot-starter</artifactId>
79
			<version>${nacos}</version>
85 80
		</dependency>
86 81
	</dependencies>
87 82

+ 1 - 1
ipu-nacos-demo/src/main/java/com/ai/ipu/server/IpuNacosDemoStart.java

@ -7,7 +7,7 @@ import com.ai.ipu.restful.boot.IpuRestApplication;
7 7
 * @date 2019年11月21日下午3:11:12
8 8
 * @desc SpringBoot应用启动类
9 9
 */
10
public class IpuNacosDemoStart {
10
public class NacosDemoStart {
11 11
12 12
	public static void main(String[] args) {
13 13
		/*启动*/

+ 35 - 0
ipu-nacos-demo/src/main/java/com/ai/ipu/server/config/NacosServiceRegistry.java

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

3
import javax.annotation.PostConstruct;
4

5
import org.slf4j.Logger;
6
import org.slf4j.LoggerFactory;
7
import org.springframework.beans.factory.annotation.Value;
8
import org.springframework.context.annotation.Configuration;
9

10
import com.ai.ipu.server.util.IpUtil;
11
import com.alibaba.nacos.api.annotation.NacosInjected;
12
import com.alibaba.nacos.api.naming.NamingService;
13

14
@Configuration
15
public class NacosServiceRegistry {
16
    private static final Logger log = LoggerFactory.getLogger(NacosServiceRegistry.class);
17
    @Value("${server.port}")
18
    private int serverPort;
19

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

23
    @NacosInjected
24
    private NamingService namingService;
25

26
    @PostConstruct
27
    public void registerService() {
28
        try {
29
            // Nacos服务自动注册,有多块网卡时,取不是.1结尾并且IP地址排序最小的做为当前IP
30
            namingService.registerInstance(appName, IpUtil.getHostAddress(), serverPort, "DEFAULT");
31
        } catch (Exception e) {
32
            log.error(e.getMessage());
33
        }
34
    }
35
}

+ 49 - 0
ipu-nacos-demo/src/main/java/com/ai/ipu/server/control/NacosConsumerControl.java

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

3
import org.slf4j.Logger;
4
import org.slf4j.LoggerFactory;
5
import org.springframework.beans.factory.annotation.Autowired;
6
import org.springframework.beans.factory.annotation.Value;
7
import org.springframework.http.ResponseEntity;
8
import org.springframework.stereotype.Controller;
9
import org.springframework.web.bind.annotation.RequestMapping;
10
import org.springframework.web.bind.annotation.ResponseBody;
11
import org.springframework.web.client.RestTemplate;
12

13
import com.alibaba.nacos.api.annotation.NacosInjected;
14
import com.alibaba.nacos.api.exception.NacosException;
15
import com.alibaba.nacos.api.naming.NamingService;
16
import com.alibaba.nacos.api.naming.pojo.Instance;
17

18
@Controller
19
@RequestMapping("/nacos/consumer")
20
public class NacosConsumerControl {
21
    private static final Logger logger = LoggerFactory.getLogger(NacosConsumerControl.class);
22
    
23
    @Value("${spring.application.name}")
24
    private String appName;
25
    
26
    @NacosInjected
27
    private NamingService namingService;
28
    
29
    private RestTemplate restTemplate = new RestTemplate();
30
    
31
    @ResponseBody
32
    @RequestMapping(value = "/hello")
33
    public String hello() throws NacosException {
34
        String msg = "Hello World";
35
        // 选择服务的一个健康实例(可配置负载均衡策略)
36
        Instance instance = namingService.selectOneHealthyInstance(appName);
37
        // 拼接请求接口url并请求选取的实例
38
        StringBuilder buff = new StringBuilder();
39
        buff.append("http://");
40
        buff.append(instance.getIp()).append(":").append(instance.getPort());
41
        buff.append("/ipu/nacos/provider/hello?message=").append(msg);
42
        String url = buff.toString();
43
        
44
        logger.debug(String.format("请求URL:%s", url));
45
        ResponseEntity<String> entity = restTemplate.getForEntity(url, String.class);
46
        logger.debug(String.format("响应结果:%s", entity.getBody()));
47
        return entity.getBody();
48
    }
49
}

+ 18 - 0
ipu-nacos-demo/src/main/java/com/ai/ipu/server/service/NacosProviderControl.java

@ -0,0 +1,18 @@
1
package com.ai.ipu.server.service;
2

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

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

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

+ 58 - 0
ipu-nacos-demo/src/main/java/com/ai/ipu/server/util/IpUtil.java

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

3

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

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

+ 0 - 3
ipu-nacos-demo/src/main/resources/ipu-spring-mvc.xml

@ -11,7 +11,4 @@
11 11
		http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
12 12

13 13
    <context:component-scan base-package="com.ai.ipu.server" />
14
	<!-- <aop:aspectj-autoproxy proxy-target-class="true"/>
15
	<context:annotation-config />
16
	<bean id="transcationAspects" class="com.ai.ipu.nosql.aspect.TransactionAspect" /> -->
17 14
</beans>