springcloud如何使用dubbo开发rpc服务及调用
这篇文章主要介绍了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服务返回的信息!
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
上一篇: JS原型对象、隐式原型与原型链
下一篇: 前端的cookie
推荐阅读