spring cloud中基於springboot開發的微服務,是基於http的rest接口,也能夠開發基於dubbo的rpc接口。web
一,建立goodsService模塊spring
1, 在建立的goodsService模塊中再建立goodsServiceApi和goodsServiceServer模塊apache
2,在oodsServiceApi模塊中定義接口 ,goodsServiceServer用於接口實現api
3,goodsServiceServer模塊中pom文件引入相關依賴springboot
<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中添加配置app
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編寫接口實現spring-boot
@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服務發現中心ui
二,建立調用dubbo服務的模塊spa
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服務返回的信息!