亲宝软件园·资讯

展开

Feign实现跨服务文件上传下载

人气:2

1、跨服务文件上传,目前feign不支持调用文件上传接口,需要自行配置来满足feign的调用方式

①.首先需要在pom文件里添加feign依赖

<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>

②.上传的接口

@FeignClient(value = "fdn-storage", configuration = {FileFeignConfig.class})
public interface FileClient {

 String PREFIX_PATH = "/oss/files";
 /**
  * 上传存储文件
  * @param file
  * @return
  * @throws IOException
  */
 @PostMapping(value = PREFIX_PATH + "/", consumes = MULTIPART_FORM_DATA_VALUE)
 FeignResult<FileEntity> save(@RequestPart(value = "file") MultipartFile file) throws IOException;
 }

③.添加配置来满足feign的调用

@Configuration
public class FileFeignConfig {
 @Autowired
 private ObjectFactory<HttpMessageConverters> messageConverters;

 @Bean
 @Primary
 @Scope("prototype")
 public Encoder feignEncoder() {
  return new SpringFormEncoder(new SpringEncoder(messageConverters));
 }

 @Bean
 public feign.Logger.Level multipartLoggerLevel() {
  return feign.Logger.Level.FULL;
 }
}

④.外部服务的controller层调用

public class TestController extends BaseRestController {
 @Autowired
 FileClient client;
 /**
  * 上传文件
  **/
 @PostMapping(value = "/" , consumes = MULTIPART_FORM_DATA_VALUE)
 public FileEntity save(@RequestPart(value = "file") MultipartFile file) throws IOException {
  FileEntity fileEntity = client.save(file).getData();
  return fileEntity;
 }
} 

到此位置就可以上传成功了

2、跨服务的文件下载

①.下载的接口(也是写在public interface FileClient),是用feign.Response来作为返回值的

/**
  * 下载文件
  * @param id
  * @return
  * @throws IOException
  */
 @GetMapping(value = PREFIX_PATH + "/{id}/data")
 Response download(@PathVariable("id") String id) throws IOException;

②.外部服务的controller层调用

 /**
  *由id下载存储的文件
  */
 @GetMapping(value = "/{id}/data")
 public void downloadFile(@PathVariable String id, HttpServletResponse servletResponse) throws IOException {
  Response response = client.download(id);
  Response.Body body = response.body();
  for(Object key : response.headers().keySet()){
   List<String> kList = (List)response.headers().get(key);
   for(String val : kList){
    servletResponse.setHeader(StringUtils.toString(key), val);
   }
  }
  try(InputStream inputStream = body.asInputStream();
   OutputStream outputStream = servletResponse.getOutputStream()
  ){
   byte[] b = new byte[inputStream.available()];
   inputStream.read(b);
   outputStream.write(b);
   outputStream.flush();
  }catch (IOException e){
   throw new RestException("IO流异常", e);
  }
 }

至此,下载文件完成。

您可能感兴趣的文章:

加载全部内容

相关教程
猜你喜欢
用户评论