Feign調用傳輸文件異常的解決

1. Current request is not a multipart request

feign接口參數使用 @RequestPart 而非 @RequestParam, 同時需要指定consumes,比如這樣:

@PostMapping(value = "/upload",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    Result<FileStorage> upload(@RequestPart(value = "file") MultipartFile file);

2. Feign failed and no fallback

這是hystrix導致,關閉feign熔斷,或者延長熔斷的超時時間,我簡單粗暴的直接關瞭

3.Read timed out executing POST for “xxx”

配置瞭hystrix還不行,或者延長ribbon的超時時間,參考瞭Feign超時問題的辦法,簡單來說就是feign經過瞭ribbonn和hystrix兩級調用,而且都有一個默認的超時時間,延長超時時間就好瞭

spring:
  servlet:
    context-path: /farm
  application:
    name: farm
  profiles:
    active: dev
  main:
    allow-bean-definition-overriding: true
eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:7001/eureka
  instance:
    prefer-ip-address: true
#關閉feign熔斷
feign:
  hystrix:
    enabled: false
#開啟熔斷,關閉熔斷超時或延長調用超時時間
#hystrix:
#  command:
#    default:
#      execution:
#        timeout:
#          enabled: false
#        isolation:
#          thread:
#            timeoutInMilliseconds: 30000
#延長ribbon超時時間
ribbon:
  ReadTimeout: 30000
  ConnectTimeout: 30000

通過Feign上傳文件(踩坑)

引入依賴:

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

服務提供者:

@RestController
@RequestMapping("/file")
public interface FileUploadService {
 
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST, consumes = MULTIPART_FORM_DATA_VALUE)
    CommonResult<String> uploadFile(@RequestPart("file") MultipartFile file,
                                    @RequestParam(value = "containerName", required = false) String containerName
}

具體實現不是重點……根據你的實際情況去完成……

服務調用者:

@RestController
@FeignClient(value = "XXXXXXXX", configuration = FileUploadServiceFeign.ClientConfiguration.class)
@RequestMapping("/file")
public interface FileUploadServiceFeign extends FileUploadService {
     
    /**
     * 配置類
     */
    class ClientConfiguration {
        /**
         * 此處註入的是: ObjectFactory<HttpMessageConverters>
         */
        @Autowired
        private ObjectFactory<HttpMessageConverters> messageConverters;
 
        @Bean
        public Encoder feignEncoder() {
            return new SpringFormEncoder(new SpringEncoder(messageConverters));
        }
    }
}

這樣就行瞭……

需要註意的是:

在服務調用者那層的MultipartFile的value要跟服務提供者的@RequestPart中的value值一樣。不然它會拋出400異常!!!

成功案例:

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: