ZooKeeper和Dubbo是两个在分布式系统中常用的开源框架,它们可以协同工作,提供服务注册与发现、分布式协调等功能。
- 服务注册与发现:
- Dubbo服务提供者将自己的信息(如IP地址、端口、服务名等)注册到ZooKeeper上,作为服务的提供者。
- Dubbo服务消费者从ZooKeeper上获取服务提供者的信息,实现服务的发现。
公共依赖包common接口
public interface UserService {
String getUser();
}
生产者和消费者(Springboot版本这里都为2.7.2)都导入公共依赖包,另外都在服务启动类上添加@EnableDubbo注解,导入依赖如下:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
<version>3.0.7</version>
</dependency>
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-rpc-dubbo</artifactId>
<version>3.0.7</version>
</dependency>
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-registry-zookeeper</artifactId>
<version>3.0.7</version>
</dependency>
<dependency>
<groupId>org.example</groupId>
<artifactId>common</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.9.1</version>
</dependency>
消费者代码如下:
application.yaml如下:文章来源:https://www.toymoban.com/news/detail-797329.html
dubbo:
application:
name: consumer
protocol:
name: dubbo
port: 20880
registry:
address: zookeeper://127.0.0.1:2181
server:
port: 9090
@RestController
public class TestController {
//UserService接口
@DubboReference(version = "1.0")
private UserService userService;
@RequestMapping("/test")
public String test(){
return userService.getUser();
}
}
生产者代码如下:
application.yaml如下:
server:
port: 8082
dubbo:
application:
name: provider
protocol:
name: dubbo
port: 20880
registry:
address: zookeeper://127.0.0.1:2181
@DubboService(version = "1.0")
public class UserServiceImpl implements UserService {
public String getUser(){
return "hello world";
}
}
通过访问localhost:9090/test可以访问到8082端口的hello world数据。由此Dubbo可以基本的实现远程服务调用。文章来源地址https://www.toymoban.com/news/detail-797329.html
到了这里,关于Dubbo 3.x结合Zookeeper实现远程服务基本调用的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!