Dubbo使用ZooKeeper作为注册中心

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

启动ZK

启动ZK实例或者集群。

依赖及配置

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

1
2
3
4
5
6
7
8
9
10
11
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-dependencies-zookeeper-curator5</artifactId>
<type>pom</type>
<exclusions>
<exclusion>
<artifactId>slf4j-reload4j</artifactId>
<groupId>org.slf4j</groupId>
</exclusion>
</exclusions>
</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: zookeeper://${zookeeper.address:127.0.0.1}:2181

同时在启动类中添加@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: zookeeper://${zookeeper.address:127.0.0.1}:2181
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;
}

使用dubbo-admin管理

在使用ZooKeeper作为注册中心时,可以使用dubbo-admin作为注册中心的管理控制台。

【参考】
dubbo知识点之管理工具dubbo-admin分享
dubbo-admin-server项目报8080端口被占用错误