Feign 文件上传背景说明
Spring Cloud 官方封装的 Feign 组件原生并未内置对文件传输的支持,但借助社区提供的扩展库可以顺利实现该功能。本文将详细阐述具体的集成步骤与代码实现。
服务提供方接收文件实现
首先介绍服务提供方(即接收文件的一方)的处理逻辑。
服务提供方的开发无需特殊处理,遵循 Spring MVC 的标准规范即可。具体控制器实现如下所示:
@RestController
public class UploadController {
@PostMapping(value = "/uploadFile", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public String handleFileUpload(@RequestPart(value = "file") MultipartFile file) {
return file.getName();
}
}
服务消费方依赖与接口配置
接下来关注服务消费方(即发起文件请求的一方)。
由于消费方将使用 Feign 客户端进行调用,必须额外引入支持表单提交的依赖库。具体的 Maven 依赖配置如下:
io.github.openfeign.form
feign-form
3.0.3
io.github.openfeign.form
feign-form-spring
3.0.3
commons-fileupload
commons-fileupload
定义 FeignClient 接口,假设目标服务的名称为 upload-server。
@FeignClient(value = "upload-server", configuration = TestServiceClient.MultipartSupportConfig.class)
public interface UploadService {
@PostMapping(value = "/uploadFile", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
String handleFileUpload(@RequestPart(value = "file") MultipartFile file);
@Configuration
class MultipartSupportConfig {
@Bean
public Encoder feignFormEncoder() {
return new SpringFormEncoder();
}
}
}
在服务提供方启动后,可在消费方编写单元测试,利用上述定义的 Feign 客户端执行文件上传操作。测试代码如下:
@Test
@SneakyThrows
public void testHandleFileUpload() {
File file = new File("files/aaa.txt");
DiskFileItem fileItem = (DiskFileItem) new DiskFileItemFactory().createItem("file",
MediaType.TEXT_PLAIN_VALUE, true, file.getName());
try (InputStream input = new FileInputStream(file); OutputStream os = fileItem.getOutputStream()) {
IOUtils.copy(input, os);
} catch (Exception e) {
throw new IllegalArgumentException("Invalid file: " + e, e);
}
MultipartFile multi = new CommonsMultipartFile(fileItem);
log.info(testServiceClient.handleFileUpload(multi));
}
以上内容涵盖了 Spring Cloud Feign 文件上传的核心实现细节,希望能为开发者提供参考与支持。