Dubbo使用Nacos作为注册中心

如下示例均基于Spring Boot框架环境实现。

启动Nacos

参考[Nacos官方文档]部署并启动实例。

依赖及配置

在服务提供者和服务消费者项目中添加依赖。

1
2
3
4
5
<!-- 使用nacos作为注册中心 -->
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-registry-nacos</artifactId>
</dependency>

同时,在服务提供者和服务消费者项目配置文件(application.yml)中添加如下配置。

服务提供者配置:

1
2
3
4
5
6
7
8
dubbo:
application:
name: dubbo-springboot-demo-provider
protocol:
name: dubbo
port: -1
registry:
address: nacos://192.168.100.232:8848

同时在启动类中添加@EnableDubbo注解,在接口实现类上添加@DubboService注解。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@SpringBootApplication
@EnableDubbo
public class DemoServiceProviderApplication {
public static void main(String[] args) {
SpringApplication.run(DemoServiceProviderApplication.class, args);
}
}

@DubboService
public class DemoServiceImpl implements DemoService {
@Override
public String sayHello(String name) {
return "Hello, " + name;
}
}

服务消费者配置:

1
2
3
4
5
6
7
8
9
10
dubbo:
application:
name: dubbo-springboot-demo-consumer
protocol:
name: dubbo
port: -1
registry:
address: nacos://192.168.100.232:8848
provider:
timeout: 3000

同时在启动类中添加@EnableDubbo注解,再通过@DubboReference注解引用接口实现类。

1
2
3
4
5
6
7
8
9
10
11
12
13
@SpringBootApplication
@EnableDubbo
public class DemoServiceConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(DemoServiceConsumerApplication.class, args);
}
}

@Component
public class Task implements CommandLineRunner {
@DubboReference
DemoService demoService;
}

管理控制台

在使用Nacos作为Dubbo注册中心时,既可以使用dubbo-admin作为注册中心控制台,还可以直接使用Nacos自带的管理控制台。

【参考】
Nacos集群搭建部署(超详细)
听句劝! Nacos集群搭建可以看看这篇教程