赞
踩
在yudao-cloud如何定义一个Api接口,提供给另一个服务去调用?下面是 yudao-module-syetem系统服务
调用 yudao-module-infra文件服务
的示例:
首先需要在服务提供者yudao-module-infra
定义好对应的api,
第1步:
cn.iocoder.yudao.module.infra.enums.ApiConstants
查看该文件是否已创建,如下:
第2步:
定义接口和对应的实现类cn.iocoder.yudao.module.infra.api.file.FileApi
,如下:
// Feign接口 @FeignClient(name = ApiConstants.NAME) @Tag(name = "RPC 服务 - 文件") public interface FileApi { @PostMapping(PREFIX + "/create") @Operation(summary = "保存文件,并返回文件的访问路径") CommonResult<String> createFile(@Valid @RequestBody FileCreateReqDTO createReqDTO); } // 实现 @RestController // 提供 RESTful API 接口,给 Feign 调用 @Validated public class FileApiImpl implements FileApi { @Resource private FileService fileService; @Override public CommonResult<String> createFile(FileCreateReqDTO createReqDTO) { // 实现类直接调用文件service类 return success(fileService.createFile(createReqDTO.getName(), createReqDTO.getPath(), createReqDTO.getContent())); } }
第3步:
cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants
定义异常信息,普通的异常处理也可以定义在这里,如下图:
第4步:
service类
使用判断抛出异常,如下:
if(content == null){
throw exception(FILE_NOT_EXISTS);
}
第5步:
服务消费者yudao-module-system
引入依赖,已经引入的不需要再添加。代码如下:
<dependency>
<groupId>cn.iocoder.cloud</groupId>
<artifactId>yudao-module-infra-api</artifactId>
<version>${revision}</version>
</dependency>
第6步:
在 yudao-module-system-biz
模块,创建 RpcConfiguration (opens new window)配置类,注入 FileApi 接口,已经创建的不需要再创建。代码如下:
@Configuration(proxyBeanMethods = false)
@EnableFeignClients(clients = {FileApi.class}) // 如有多个可用,隔开添加 {FileApi.class,xxx.class}
public class RpcConfiguration {
}
第7步:
在需要使用到的地方,引入调用即可:
@Service
public class AdminUserServiceImpl implements AdminUserService {
@Resource
private AdminUserApi adminUserApi;
@Override
public void updateUserAvatar(Long id, InputStream avatarFile) {
// ... 省略非关键代码
String avatar = fileApi.createFile(IoUtil.readBytes(avatarFile));
}
}
第8步:
嗯!!!!!不用写了,完成,重启测试。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。