dubbo服务更多是相对于服务器端的服务来用的,即服务A调用服务B使用dubbo服务,restful服务更多是相对于前端使用的,即前端调用restful服务的接口来获取数据。
1、首先创建一个api maven模块,用于写接口
public interface Service2Api {
public String dubboService2();
}
2、再创建一个server maven模块,用来实现api中的接口
@org.apache.dubbo.config.annotation.Service // 注意这个导入的service包名,别导错了
public class Service2ApiImpl implements Service2Api {
public String dubboService2() {
return "dubboService2";
}
}
3、在server模块中的pom.xml中引入如下两个依赖
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-dubbo</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
4、在bootstrap.yml文件中配置如下内容:包括启动端口,nacos服务地址和服务名,以及dubbo服务配置
server:
port: 56040
spring:
application:
name: dubbo-service2
main:
allow-bean-definition-overriding: true
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
dubbo:
scan:
base-packages: com.itheima.microservice.service2.service
protocol:
name: dubbo
port: 20891
registry:
address: nacos://127.0.0.1:8848
application:
qos-enable: false
consumer:
check: false
logging:
level:
root: "error"
5、在restful服务中调用dubbo中的服务
5.1、首先需要在restful服务中引入api中的groupid和dubbo服务依赖:
<dependency>
<groupId>com.itheima.nacos</groupId>
<artifactId>service2-api</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-dubbo</artifactId>
</dependency>
5.2、在restful中调用dubbo接口
@org.apache.dubbo.config.annotation.Reference
private Service2Api service2Api;
@GetMapping(value = "/service2")
public String service2(){
String service2 = service2Api.dubboService2();
return "consumer 123 invode|"+service2;
}