原文: http://www.itmuch.com/spring-cloud-sum/spring-cloud-feign-upload/ 采用 CC BY 3.0 CN 許可協定。可自由轉載、引用,但需署名作者且注明文章出處。如轉載至微信公衆号,請在文末添加作者公衆号二維碼。
最近經常有人問Spring Cloud Feign如何上傳檔案。有團隊的新成員,也有其他公司的兄弟。本文簡單做個總結——
早期的Spring Cloud中,Feign本身是沒有上傳檔案的能力的(1年之前),要想實作這一點,需要自己去編寫
Encoder
去實作上傳。現在我們幸福了很多。因為Feign官方提供了子項目
feign-form,其中實作了上傳所需的
Encoder
。
注:筆者測試的版本是Edgware.RELEASE。Camden、Dalston同樣适應本文所述。
加依賴
<dependency>
<groupId>io.github.openfeign.form</groupId>
<artifactId>feign-form</artifactId>
<version>3.0.3</version>
</dependency>
<dependency>
<groupId>io.github.openfeign.form</groupId>
<artifactId>feign-form-spring</artifactId>
<version>3.0.3</version>
</dependency>
編寫Feign Client
@FeignClient(name = "ms-content-sample", configuration = UploadFeignClient.MultipartSupportConfig.class)
public interface UploadFeignClient {
@RequestMapping(value = "/upload", method = RequestMethod.POST,
produces = {MediaType.APPLICATION_JSON_UTF8_VALUE},
consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@ResponseBody
String handleFileUpload(@RequestPart(value = "file") MultipartFile file);
class MultipartSupportConfig {
@Bean
public Encoder feignFormEncoder() {
return new SpringFormEncoder();
}
}
}
如代碼所示,在這個Feign Client中,我們引用了配置類
MultipartSupportConfig
,在
MultipartSupportConfig
中,我們執行個體化了
SpringFormEncoder
。這樣這個Feign Client就能夠上傳啦。
注意點
-
中的@RequestMapping(value = "/upload", method = RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_UTF8_VALUE}, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
、produeces
不能少;consumes
- 接口定義中的注解
不能寫成@RequestPart(value = "file")
@RequestParam(value = "file"
- 最好将Hystrix的逾時時間設長一點,例如5秒,否則可能檔案還沒上傳完,Hystrix就逾時了,進而導緻用戶端側的報錯。