一、将Dubbo集成至SpringCloud主要是替换Ribbo或者Feign实现远程调用
引入依赖版本是2.2.3RELEASE
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-dubbo</artifactId>
</dependency>
二、接口及实现
public interface UserService {
User selectUser(String userId);
}
@DubboService
//@DubboService(version = “2.0.0”)可指定版本
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
public User selectUser(String userId) {
return userMapper.selectUser(userId);
}
}
注意实现类添加服务提供者@DubboService!@DubboService!!@DubboService!!!对外暴露dubbo服务。
三、application.yml中添加配置
pring:
datasource:
url: jdbc:mysql://localhost:3306/dubbo-test?useSSL=false
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
application:
name: user-service
cloud:
nacos:
discovery:
server-addr: localhost:8848
#配置dubbo,注册中心,暴露的端口和协议,dubbo注解的包扫描
dubbo:
protocol:
name: dubbo
port: 20881
registry:
address: spring-cloud://localhost #使用SpringCloud中的注册中心
cloud:
subscribed-services: 'service-product,...' #服务提供方的服务名称(spring.application.name),需要调用多个服务用,隔开。
scan:
base-packages: com.test.user.service #dubbo中包扫描
四、服务消费者
@RestController
@RequestMapping("userI")
public class UserController {
@DubboReference
private UserService userService;
@GetMapping("{orderId}")
public User selectUser(@PathVariable("userId") String userId) {
//查询用户
User user = userService.selectUser(userId);
return user;
}
}
注意@DubboReference开启服务消费!服务启动的时候要先启动生产者服务,否则需要提供相应配置