前提
当然,搭建分布式系统之前,你要搞清楚dubbo和Zookeeper的关系,先安装启动Zookeeper
搭建工程,新建maven工程,什么都不需要勾选
或者创建空工程
创建公共接口spring-dubbo-api(即公共调用模块)
file->new->module
选择maven或springboot都可以,我创建的是springboot,
定义接口方法(随便定义了一个)
创建服务提供者spring-dubbo-provider
- 创建springboot 选择web工程,这个不在截图了
- 添加pom依赖
添加公共api模块
<dependency>
<groupId>com.wonder</groupId>
<artifactId>spring-dubbo-api</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
引入dubbo依赖和Zookeeper以及Zookeeper客户端
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
<version>2.7.3</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo</artifactId>
<version>2.7.3</version>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-framework</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.13</version>
<type>pom</type>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.101tec</groupId>
<artifactId>zkclient</artifactId>
<version>0.10</version>
</dependency>
- 配置application.properties
#spring项目名
spring.application.name=dubbo_auto_configuration_provider_demo
#Dubbo provider configuration
dubbo.application.name=dubbo_provider
dubbo.registry.protocol=zookeeper
dubbo.registry.address=zookeeper://127.0.0.1:2181
dubbo.protocol.name=dubbo
dubbo.protocol.port=20880
#扫描注解包通过该设置将服务注册到zookeeper
dubbo.scan.base-packages=com.wonder.provider.service
- 实现api中接口方法
import org.apache.dubbo.config.annotation.Service;
@Service //dubbo中的服务注解
public class UserServiceImpl implements UserService {
@Override
public String getUsername(String id) {
System.out.println("调用provider成功。。。。。");
return "success";
}
}
创建spring-dubbo-consumer项目
- 项目创建同上spring-dubbo-provider的创建
- 配置application.properties
dubbo.application.name=dubbo_consumer
dubbo.registry.protocol=zookeeper
dubbo.registry.address=zookeeper://127.0.0.1:2181
#避免端口冲突
server.port=8085
- 调用
@RestController
public class UserController {
@Reference
UserService userService;
@GetMapping("hello")
public String sayHello(String name){
String result = userService.getUsername("1");
return result;
}
}
两个服务项目调用
- 修改配置dubbo.protocol.port=20881
dubbo.protocol.name=dubbo
dubbo.protocol.port=20881
#扫描注解包通过该设置将服务注册到zookeeper
dubbo.scan.base-packages=com.wonder.provider.service
- 设置Reference 中 设置 check 为 false.
OrderService orderService;