1. 安裝 Zookeeper 環(huán)境
2. 服務(wù)提供者
因?yàn)橛昧烁腹こ痰陌姹竟芾砀娼常赃@里沒有顯示版本稻扬,我把用到的版本給大家分享下蒸痹。
- jdk 1.8
- springboot 1.5.8
- spring-boot-starter-dubbo 1.0.0
閑余之際我會(huì)把demo源碼分享崭添。
2.1 pom依賴
<dependencies>
<!-- Spring Boot Web 依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Boot Test 依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--spring data jpa -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.8-dmr</version>
<scope>compile</scope>
</dependency>
<!--dubbo 依賴-->
<dependency>
<groupId>io.dubbo.springboot</groupId>
<artifactId>spring-boot-starter-dubbo</artifactId>
</dependency>
<!--junit 測(cè)試工具-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
2.2. Service填寫
大概給下項(xiàng)目架構(gòu):
為了方便,我用的springboot data jpa做持久性框架。如果不會(huì)jpa,請(qǐng)先看我springboot jpa整合。
- SchoolRepository .java
/**
* Created by Fant.J.
*/
@Repository
public interface SchoolRepository extends JpaRepository<School,Integer> {
}
- SchoolService.java 略(一個(gè)正常的借口)
- 實(shí)現(xiàn)類SchoolServiceImpl .java核心代碼
@Service(version = "2.0.1")
public class SchoolServiceImpl implements SchoolService {
@Autowired
private SchoolRepository schoolRepository;
這里的@Service注解是dubbo的注解佑附,不是springframework下的注解。該注解就是向zk注冊(cè)服務(wù)仗考。
2.3. application.properties
server.port=9002
## Dubbo 服務(wù)提供者配置
spring.dubbo.application.name=school-server
spring.dubbo.registry.address=zookeeper://xxx.xxx.xxx.xxx:2181
spring.dubbo.protocol.name=dubbo
spring.dubbo.protocol.port=20882
spring.dubbo.scan=com.xxx.school.service
spring.datasource.url=jdbc:mysql://xxxxxxxxxx
spring.datasource.username=xxxx
spring.datasource.password=xxxx
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
注意: 每一個(gè)服務(wù)都需要一個(gè)未被使用的dubbo端口 音同。
3. 服務(wù)消費(fèi)
為了和服務(wù)提供者解耦,我們需要把Service接口類單獨(dú)拿出來放到client模塊里秃嗜,這里不貼詳細(xì)代碼了权均。
3.1 pom.xml
這里略,根據(jù)controller類里的需要來填充相關(guān)依賴
3.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屬性值一一對(duì)應(yīng)锅锨。
3.3 application.properties
## Dubbo 服務(wù)消費(fèi)者配置
spring.dubbo.application.name=xxx
spring.dubbo.registry.address=zookeeper://xxxx.xxx.xxx.xxx
spring.dubbo.scan=com.xxx.web.controller
成功截圖:
有疑問請(qǐng)?jiān)谙旅媪粞浴?/p>