当前位置:   article > 正文

芋道源码yudao-cloud 二开笔记(Feign服务调用,如何定义一个 API 接口)_芋道 feign

芋道 feign

在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()));
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

第3步:
cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants定义异常信息,普通的异常处理也可以定义在这里,如下图:

在这里插入图片描述
第4步:
service类使用判断抛出异常,如下:

if(content == null){
   throw exception(FILE_NOT_EXISTS);
}
  • 1
  • 2
  • 3

在这里插入图片描述

第5步:
服务消费者yudao-module-system引入依赖,已经引入的不需要再添加。代码如下:

<dependency>
    <groupId>cn.iocoder.cloud</groupId>
    <artifactId>yudao-module-infra-api</artifactId>
    <version>${revision}</version>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5

第6步:
yudao-module-system-biz 模块,创建 RpcConfiguration (opens new window)配置类,注入 FileApi 接口,已经创建的不需要再创建。代码如下:

@Configuration(proxyBeanMethods = false)
@EnableFeignClients(clients = {FileApi.class}) // 如有多个可用,隔开添加 {FileApi.class,xxx.class}
public class RpcConfiguration {

}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

第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));
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

第8步:
嗯!!!!!不用写了,完成,重启测试。

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号