spring-boot-start-dubbo,是spring-boot與dubbo有機(jī)結(jié)合的橋梁,根據(jù)spring-boot規(guī)范實(shí)現(xiàn),使dubbo的使用變得及其簡(jiǎn)單快捷,容易上手,而且省去了xml的配置。讓dubbo小白正常使用dubbo,只需一盞茶的功夫。
一、引入依賴
dependency>
<groupId>com.gitee.reger</groupId>
<artifactId>spring-boot-starter-dubbo</artifactId>
<version>1.1.1</version>
</dependency>
二、定義服務(wù)接口,在api項(xiàng)目中添加如下
package com.my;
/**
* hello service
* @author mk
*/
public interface HelloService {
/**
* dubbo測(cè)試接口
* @param param param
* @return result
*/
String hello(String param);
}
三、設(shè)置provider,在provider項(xiàng)目執(zhí)行如下操作
1. 修改application.yml,添加如下內(nèi)容
#dubbo provider
spring:
dubbo:
application:
name: demo-provider
base-package: com.my.provider # dubbo服務(wù)發(fā)布者所在的包
registry:
address: 127.0.0.1 # zookeeper注冊(cè)中心的地址
port: 2181 # zookeeper注冊(cè)中心的端口
protocol:
name: dubbo
serialization: hessian2
provider:
retries: 0 # 服務(wù)調(diào)用重試次數(shù),服務(wù)發(fā)布者不給重試,讓服務(wù)調(diào)用者自己重試
2. 修改實(shí)現(xiàn),在實(shí)現(xiàn)類上引入dubbo的service注解
package com.my.provider;
import com.alibaba.dubbo.config.annotation.Service;
import com.my.HelloService;
/**
* hello service
* @author mk
*/
@Service
public class HelloServiceImpl implements HelloService{
@Override
public String hello(String param) {
return "provider get param success,param is " + param;
}
}
四、設(shè)置consumer,在consumer項(xiàng)目上執(zhí)行如下操作
1. 修改application.yml,添加如下內(nèi)容
#dubbo
spring:
dubbo:
application:
name: demo-consumer
base-package: com.my # dubbo服務(wù)調(diào)用者所在的包
registry:
address: 127.0.0.1 # zookeeper注冊(cè)中心的地址
port: 2181 # zookeeper注冊(cè)中心的端口
consumer:
timeout: 1000
check: true # 服務(wù)啟動(dòng)時(shí)檢查被調(diào)用服務(wù)是否可用
retries: 2 # 服務(wù)調(diào)用重試次數(shù)
2. 調(diào)用代碼示例,通過Reference或Inject注解,注入對(duì)象
package com.my.controller;
import com.alibaba.dubbo.config.annotation.Reference;
import com.my.HelloService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* hello controller
* @author mk
*/
@RestController
public class HelloController {
@Reference
private HelloService helloService;
@RequestMapping("/hello")
public String hello(HttpServletRequest request, HttpServletResponse response){
String result = helloService.hello("consumer params...");
return result;
}
}
四、測(cè)試
分別啟動(dòng)provider和consumer,完畢后調(diào)用consumer的hello接口返回如下

image.png
五、注意事項(xiàng)
1. provider的接口實(shí)現(xiàn)的@service注解一定要引用dubbo的注解,不要寫成spring的
2. consumer中引入對(duì)象,需要用到dubbo的@Inject或@Reference
文章參考:
1. spring-boot-start-dubbo
2. 原來dubbo發(fā)布服務(wù)如此簡(jiǎn)單