Spring Cloud OpenFeign 上传文件

Feign是一个声明式的伪Http客户端,它使得写Http客户端变得更简单。

Spring Cloud OpenFeignSpring Could服务间调用的基础组件,将Feign进行了封装,更便于使用,本文使用Spring Cloud OpenFeign进行文件上传。

spring-cloud-openfeign版本2.1.1.RELEASE

声明使用Form表单形式提交

public class MultipartSupportConfig {
    
    @Bean
    public Encoder feignFormEncoder() {
        return new SpringFormEncoder();
    }
    
    /**
     * @return 日志级别
     */
    @Bean
    Logger.Level feignLoggerLevel(){
        return Logger.Level.FULL;
    }
}

consumes指定MediaTypemultipart/form-data

@FeignClient(name = "test", url = "http://localhost:8141", path = "p/c", configuration = MultipartSupportConfig.class)
public interface UploadFileClient {

    @RequestMapping(path = "uploadPrintedCodesFile", consumes = MULTIPART_FORM_DATA_VALUE)
    Object uploadPrintedCodesFile(UploadData uploadData);

}

url也支持使用注入的方式${jdl.base_url}

将文件放在对象中作为form表单中的一部分进行提交

@Autowired
   private UploadFileClient uploadFileClient;

   @Test
   public void test(){

       File file = new File("./mock.xls");

       MultipartFile result = new MockMultipartFile(file.getName(),
               Files.toByteArray(file));

       UploadData uploadData = new UploadData();
       uploadData.setFactoryNo("test");
       uploadData.setFile(result);
       uploadFileClient.uploadPrintedCodesFile(uploadData);

   }

如果只是想提交文件,方法可以这样写,将MultipartFile传入即可

@FeignClient(name = "test", url = "http://localhost:8141", path = "p/c", configuration = MultipartSupportConfig.class)
public interface UploadFileClient {

    @RequestMapping(path = "uploadPrintedCodesFile", consumes = MULTIPART_FORM_DATA_VALUE)
    Object uploadPrintedCodesFile(MultipartFile file);

}

多个client使用相同name报错

Caused by: org.springframework.beans.factory.support.BeanDefinitionOverrideException: Invalid bean definition with name 'XXX.FeignClientSpecification' defined in null:

Spring Bean定义冲突导致服务不能启动,可以添加如下配置

spring.main.allow-bean-definition-overriding=true

如果不想更改整体Spring配置的话,可以手动指定contextId,优先使用contextId作为ClientName

@FeignClient(value = "admin",contextId = "aTest")

Spring Cloud OpenFeign 上传文件
https://blog.yjll.blog/post/4c4b951a.html
作者
简斋
发布于
2020年5月8日
许可协议