dubbo 是阿里的高性能RPC框架,是除spring cloud 之外的另一种 微服务选择。本篇文章,我们来利用spring boot +nacos +dubbo 来探讨下 dubbo 服务调用的基本实现。
简介
Apache Dubbo |ˈdʌbəʊ| 是一款高性能、轻量级的开源Java RPC框架,它提供了三大核心能力:面向接口的远程方法调用,智能容错和负载均衡,以及服务自动注册和发现。
易于构建云原生应用的动态服务发现、配置管理和服务管理平台,简单说是个注册中心。
程序构建
配置
在程序中引入dubbo-spring-boot-starter 和nacos-discovery-spring-boot-starter 的 mvn jar 包。
yml 配置文件:
server:
port: 9097
spring:
application:
name: user-service
nacos:
discovery:
server-addr: 127.0.0.1:8848
dubbo:
application:
name: ${spring.application.name}
registry:
address: nacos://${nacos.discovery.server-addr}
protocol:
name: dubbo
port: 20880
scan:
base-packages: com.magicdu.dubbo.back.service
consumer:
check: false # 启动时不检查 consumer
新增服务时,我们修改下上面的配置文件即可,我们配置每个服务即可为生产者,也可为消费者。为了共用service 接口,我们需要为所有项目提供公共的 service 层,来管理接口。
编写程序
我们首选在公共模块编写 接口
package com.magicdu.dubbo.back.service;
public interface UserService {
String sayHello(String userName);
}
生产者提供该接口的实现
@Service
@Slf4j
public class UserServiceImpl implements UserService {
@Override
public String sayHello(String userName) {
log.info("请求接口---->");
return "hello"+userName;
}
}
注意 这里的 @Service 注解 是 dubbo 的注解 org.apache.dubbo.config.annotation.Service 不是 sping 的注解
消费者,只需 调用该服务即可、
package com.magicdu.dubbo.dept.controller;
import com.magicdu.dubbo.back.service.UserService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DeptController {
@Reference
private UserService userService;
@RequestMapping("/sayHi/{name}")
public String sayHello(@PathVariable String name){
return userService.sayHello(name);
}
}
使用 org.apache.dubbo.config.annotation.Reference 注解 标注接口 为 RPC 服务,dubbo 就会根据配置来调用相关服务。
源码:spring boot-duubo-nacos-demo