上次的那个springboot和dubbo的整合版本中,dubbo的版本是2.5.3,它的Service注解和事务不能同时使用,会造成扫描失效,2.6.2的dubbo版本已经纠正了此不便,官方也给出了与springboot整合的quick start ,但是又缺少与zk的整合部分,所以我在这里只讲述在dubbo-spring-boot-starter依赖里,需要添加的zk依赖,只拿服务提供者来举例。
1、安装 Zookeeper 环境
Zookeeper 环境搭建&zk命令详解
2、服务提供者实现
大概给下项目架构:
2.1 导入依赖
<dependency> <groupId>com.alibaba.boot</groupId> <artifactId>dubbo-spring-boot-starter</artifactId> <version>0.1.0</version> </dependency>
dubbo-spring-boot-starter版本和springboot版本的相关性:
当然,这只是dubbo的,我们还需要添加 zookeeper的依赖
<dependency> <groupId>com.101tec</groupId> <artifactId>zkclient</artifactId> <version>0.2</version> </dependency>
为了方便,我用的springboot data jpa做持久性框架。如果不会jpa,请先看我springboot jpa整合。
2.2 SchoolRepository .java
/** * Created by Fant.J. */ @Repository public interface SchoolRepository extends JpaRepository<School,Integer> { }
2.3 SchoolService.java 略(一个正常的借口)
2.4 实现类SchoolServiceImpl .java核心代码
@Service(version = "2.0.1") public class SchoolServiceImpl implements SchoolService { @Autowired private SchoolRepository schoolRepository;
这里的@Service注解是dubbo的注解,不是springframework下的注解。该注解就是向zk注册服务。
2.5 application.properties
# Spring boot application spring.application.name = user-server management.port = 9091 # Base packages to scan Dubbo Components (e.g., @Service, @Reference) # 需要扫描的包 dubbo.scan.basePackages = com.tyut.user.service # Dubbo Config properties ## ApplicationConfig Bean dubbo.application.id = user-server dubbo.application.name = user-server ## ProtocolConfig Bean dubbo.protocol.id = dubbo dubbo.protocol.name = dubbo dubbo.protocol.port = 20880 ## RegistryConfig Bean dubbo.registry.id = my-registry # 这里是zk的连接配置 dubbo.registry.address = zookeeper://47.xxx.2xx.xx:2181
4、服务消费者
为了和服务提供者解耦,我们需要把Service接口类单独拿出来放到client模块里,这里不贴详细代码了。
4.1 pom.xml
这里略,根据controller类里的需要来填充相关依赖
<dependency> <groupId>com.xxxx.school</groupId> <artifactId>ip-school-client</artifactId> <version>1.0-SNAPSHOT</version> </dependency>
4.2 SchoolController
@RestController @RequestMapping("/sch") public class SchoolController { @Reference(version = "2.0.1") private SchoolService schoolService; @RequestMapping("/all") public ServerResponse getAll(){ return schoolService.selectAll(); } }
注意与@Service注解的version属性值一一对应。
4.3 application.properties
dubbo.scan.basePackages = com.xxx.web.controller dubbo.application.id = web-server dubbo.application.name = web-server dubbo.protocol.id = web-server dubbo.protocol.name = web-server dubbo.consumer.timeout=2000 ## RegistryConfig Bean dubbo.registry.id = web-server dubbo.registry.address = zookeeper://xxx.xx.xx.xx:2181 dubbo.protocol.port = 20890
成功截图:
apache 官方文档:
github.com/apache/incubator-dubbo-spring-boot-project