標籤:app tin primary nts eve requests stp method obj
feign傳檔案
- 檔案微服務負責管理檔案,具體的檔案上傳下載邏輯都在此模組。
- openAPI負責向app使用者提供頭像上傳的介面,實現具體商務邏輯。
- zuul是網關,負責路由轉寄。使用者直接存取網關。
頭像檔案==》zuul==》openAPI==》檔案微服務
<dependency> <groupId>io.github.openfeign.form</groupId> <artifactId>feign-form</artifactId> <version>2.1.0</version> </dependency> <dependency> <groupId>io.github.openfeign.form</groupId> <artifactId>feign-form-spring</artifactId> <version>2.1.0</version> </dependency>
@Configurationpublic class FeignConfiguration { @Autowired private ObjectFactory<HttpMessageConverters> messageConverters; @Bean public Retryer retryer(){ return new Retryer.Default(1000,10000,3); } @Bean Request.Options feignOptions() { return new Request.Options(5 * 1000, 10 * 1000); } // 主要是這個地方 @Bean @Primary @Scope("prototype") public Encoder multipartFormEncoder() { return new SpringFormEncoder(new SpringEncoder(messageConverters)); } @Bean public Logger.Level feignLoggerLevel() { return Logger.Level.FULL; } @Bean public ErrorDecoder errorDecoder(){ return new FeignErrorDecoder(); }}
異常處理類
public class FeignErrorDecoder implements feign.codec.ErrorDecoder { private static final Logger logger = LoggerFactory.getLogger(FeignErrorDecoder.class); @Override public Exception decode(String methodKey, Response response) { if(response.status() >= 400 && response.status() <= 499){ return new HystrixBadRequestException("微服務之間調用失敗!"); } return feign.FeignException.errorStatus(methodKey, response); }}
在啟動類上加註解@Import(FeignConfiguration.class),匯入配置類
@Import(FeignConfiguration.class)
至此可實現feign中檔案傳遞
feignclient
@ApiOperation(value = "使用者修改頭像", notes = "使用者修改頭像") @RequestMapping(value = "/v1/user/avatar", method = RequestMethod.PUT) public CommonResponse editAvatar(@RequestHeader(value = "openId") String openId, @RequestPart(value = "file") MultipartFile avatarFile);
- RequestPart中的name要和上傳時一致,否則調用失敗。
- feign中@RequestHeader傳遞null時,會自動轉為{fileLength},需要手動處理。
zuul
微服務上傳檔案成功後,通過zuul網關上傳又出現問題,檔案傳不到微服務中。
org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part ‘file‘ is not present
解決方案:
在調用地址前加上/zuul(/zuul/v1/user/avatar),繞過spring mvc,使用zuul servlet去上傳檔案。
參考:https://my.oschina.net/kmnztech/blog/1618636
或者在網關的application.properties中設定servlet-path屬性
zuul.servlet-path=/
官方文檔:
http://cloud.spring.io/spring-cloud-static/Dalston.SR1/#_uploading_files_through_zuul
The Zuul ServletZuul is implemented as a Servlet. For the general cases, Zuul is embeddedinto the Spring Dispatch mechanism. This allows Spring MVC to be in controlof the routing. In this case, Zuul is configured to buffer requests. Ifthere is a need to go through Zuul without buffering requests (e.g. forlarge file uploads), the Servlet is also installed outside of the SpringDispatcher. By default, this is located at /zuul. This path can be changedwith the zuul.servlet-path property.
zuul feign微服務間檔案上傳