用Nacos作为Dubbo的注册中心

什么是 Nacos

Nacos 是一个微服务管理平台,支持几乎所有主流类型的“服务”的发现、配置和管理。

什么是Dubbo

Dubbo是一款高性能、轻量级的开源Java RPC框架,它提供了三大核心能力:面向接口的远程方法调用,智能容错和负载均衡,以及服务自动注册和发现。

Maven依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<!-- Apache Dubbo Begin -->
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
</exclusion>
<exclusion>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
</exclusion>
<exclusion>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>dubbo-registry-nacos</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-client</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.spring</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-serialization-kryo</artifactId>
<exclusions>
<exclusion>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-common</artifactId>
</exclusion>
</exclusions>
</dependency>

配置注册中心

1
2
3
4
5
6
7
8
9
dubbo:
registry:
address: nacos://127.0.0.1:8848
scan:
base-packages: com.example.admin.service
protocol:
name: dubbo
port: -1
serialization: kryo

示例接口与实现

1
2
3
4
5
public interface DemoService {

String sayName(String name);

}

实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Service(version = "${demo.service.version}")
public class DefaultService implements DemoService {

@Value("${demo.service.name}")
private String serviceName;

public String sayName(String name) {
RpcContext rpcContext = RpcContext.getContext();
return String.format("Service [name :%s , port : %d] %s(\"%s\") : Hello,%s",
serviceName,
rpcContext.getLocalPort(),
rpcContext.getMethodName(),
name,
name);
}
}

消费

1
2
3
4
5
6
7
8
@Reference(version = "1.0.0")
private DemoService demoService;

@GetMapping("/test")
private ResponseResult<UserDTO> validateReg() {
UserDO user = userService.sayName("admin");
return new ResponseResult(200, "成功", user);
}

接口和实现可以拆分成不同的模块,实现解耦