springcloud如何使用dubbo開發rpc服務及呼叫
阿新 • • 發佈:2020-01-30
這篇文章主要介紹了springcloud如何使用dubbo開發rpc服務及呼叫,文中通過示例程式碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
spring cloud中基於springboot開發的微服務,是基於http的rest介面,也可以開發基於dubbo的rpc介面。
一,建立goodsService模組
1, 在建立的goodsService模組中再建立goodsServiceApi和goodsServiceServer模組
2,在oodsServiceApi模組中定義介面 ,goodsServiceServer用於介面實現
3,goodsServiceServer模組中pom檔案引入相關依賴
<dependencies> <dependency> <groupId>net.biui</groupId> <artifactId>goods-service-api</artifactId> <version>1.0-SNAPSHOT</version> </dependency> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-dubbo</artifactId> </dependency> </dependencies>
4,goodsServiceServer中新增配置
spring: application: name: goods-service cloud: nacos: discovery: server-addr: 127.0.0.1:8848 namespace: c22e5019-0bee-43b1-b80b-fc0b9d847501 dubbo: registry: address: nacos://127.0.0.1:8848 scan: base-packages: net.biui.impl protocol: port: 20881 name: dubbo
5,goodsServiceServer編寫介面實現
@org.apache.dubbo.config.annotation.Service public class GoodsImpl implements GoodsApi { public String getGoodsName() { return "商品一"; } }
6,goodsServiceServer編寫啟動類
@SpringBootApplication @EnableDiscoveryClient public class GoodsServiceServerApplication { public static void main(String[] args) { SpringApplication.run(GoodsServiceServerApplication.class,args); } }
啟動後,dubbo服務會自動註冊到nacos服務發現中心
二,建立呼叫dubbo服務的模組
1,new -> module -> 填寫資訊 -> finish
2,新增pom依賴
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-dubbo</artifactId> </dependency> <dependency> <groupId>net.biui</groupId> <artifactId>goods-service-api</artifactId> <version>1.0-SNAPSHOT</version> </dependency> </dependencies>
3,新增配置
spring: application: name: demo-dubbo cloud: nacos: discovery: server-addr: 127.0.0.1:8848 namespace: c22e5019-0bee-43b1-b80b-fc0b9d847501
4,編寫controller呼叫dubbo服務
@RestController @RequestMapping("/demo") public class demoController { @org.apache.dubbo.config.annotation.Reference GoodsApi goodsApi; @GetMapping("/test") public String test(){ return "test " + goodsApi.getGoodsName(); } }
5,編寫啟動類
@SpringBootApplication @EnableDiscoveryClient public class demoDubboApplication { public static void main(String[] args) { SpringApplication.run(demoDubboApplication.class,args); } }
啟動後,demo-dubbo服務也會自動註冊到nacos(因為nacos.register.enable預設為true,即代表自動註冊,可以只訂閱,不註冊),對應介面返回了dubbo服務返回的資訊!
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。