版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/x7418520/article/details/83894185
使用 feign 上传文件
在这里我使用了consul作为服务注册中心,使用feign来上传文件。
由于发现feignclient直接调用上传接口时不行的,所以需要加入下面的依赖。
首先在pom中加入
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>io.github.openfeign.form</groupId>
<artifactId>feign-form-spring</artifactId>
<version>3.2.2</version>
</dependency>
<dependency>
<groupId>io.github.openfeign.form</groupId>
<artifactId>feign-form</artifactId>
<version>3.2.2</version>
</dependency>
然后在启动类上加上@EnableFeignClients
@SpringBootApplication
@EnableFeignClients
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
之后新建一个接口,加入@FeignClient
,name为服务名,fallback为hystrix熔断,configuration为配置。
@FeignClient(name = "servicename", fallback = UploadFallback.class, configuration = FeignMultipartSupportConfig.class)
public interface UploadClient {
}
这是还需要加入Encoder
@Configuration
public class FeignMultipartSupportConfig {
@Bean
@Primary
@Scope("prototype")
public Encoder multipartFormEncoder() {
return new SpringFormEncoder(new SpringEncoder(new ObjectFactory<HttpMessageConverters>() {
@Override
public HttpMessageConverters getObject() throws BeansException {
return new HttpMessageConverters(new RestTemplate().getMessageConverters());
}
}));
}
@Bean
Logger.Level feignLoggerLevel() {
return Logger.Level.FULL;
}
}
在上传接口中,一定是@RequestPart
,而不是@RequestParam
。
@PostMapping(value = "file/upload/part",produces = {MediaType.APPLICATION_JSON_UTF8_VALUE},consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
Object upload(@RequestPart("file") MultipartFile file);
最后如果要加入熔断机制的话,只需要继承client接口,在方法中自定义即可。
有一点需要注意,openfeign底层使用的是ribbon,所以需要对ribbon设置超时时间。因为feign它的默认超时时间是1s,所以还未上传成功就会遭到熔断,所以我们需要在yml文件中加入如下代码。
feign:
hystrix:
enabled: true
ribbon:
ReadTimeout: 10000
ConnectTimeout: 10000
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 20000