Spring Boot + Dubbo整合
阿新 • • 發佈:2019-01-10
首先,啟zookeeper
然後,搭服務提供者:
pom.xml
<dependency> <groupId>com.alibaba.boot</groupId> <artifactId>dubbo-spring-boot-starter</artifactId> <version>0.2.0</version> </dependency> <dependency> <groupId>com.alibaba.boot</groupId> <artifactId>dubbo-spring-boot-actuator</artifactId> <version>0.2.0</version> </dependency> <dependency> <groupId>com.alibaba.boot</groupId> <artifactId>dubbo-spring-boot-autoconfigure</artifactId> <version>0.2.0</version> </dependency>
如果maven報錯下載不到對應的jar包,則手工配一下公共倉庫:
<repositories> <repository> <id>sonatype-nexus-snapshots</id> <url>https://oss.sonatype.org/content/repositories/snapshots</url> <releases> <enabled>false</enabled> </releases> <snapshots> <enabled>true</enabled> </snapshots> </repository> </repositories>
配application.properties或application.yml
# 服務提供者的版本號 demo.service.version=1.0.0 # 服務提供者的實現類的包路徑 dubbo.scan.basePackages =com.example.demo.provider dubbo.application.id=dubbo-provider-demo dubbo.application.name=dubbo-provider-demo dubbo.application.qos.port=22222 dubbo.application.qos.enable=true # 協議 dubbo.protocol.id=dubbo dubbo.protocol.name=dubbo dubbo.protocol.port=20880 dubbo.protocol.status=server ## 動物管理員的地址 dubbo.registry.id=my-registry dubbo.registry.address=zookeeper://10.100.14.54:2181
服務提供者的實現類:
@Service(
version = "${demo.service.version}",
application = "${dubbo.application.id}",
protocol = "${dubbo.protocol.id}",
registry = "${dubbo.registry.id}"
)
public class DemoServiceImpl implements DemoService {
@Override
public String sayHello() {
return "歡迎使用Dubbo,DemoServiceImpl say: Hello Dubbo!";
}
}
至此,基於Spring Boot的dubbo服務提供者就完成了。
再看dubbo消費者的工程:
pom檔案和起動配置檔案基本一樣。
消費者的引用如下:
@RestController
@RequestMapping("/consumer")
public class ConsumerController {
@Reference(version = "${demo.service.version}",
application = "${dubbo.application.id}",
url = "dubbo://localhost:20880")
private DemoService demoService;
@RequestMapping("hello")
public String hello() {
String str = demoService.sayHello();
return str;
}
}
注:DemoService是介面類,可以通過公共引用工程,也可以建立同名同package和方法名的介面類。
然後訪問地址:http://localhost:10087/consumer/hello
能得到提供者實現類裡的類容,容表示訪問成功。