1. 程式人生 > >Feign實現微服務間檔案下載

Feign實現微服務間檔案下載

在使用Feign做服務間呼叫的時候,當下載大的檔案會出現堆疊溢位的情況。另外,檔案管理服務(服務提供者)檔案下載介面無返回值,是通過HttpServletRespoonse傳輸的流資料來響應,那麼服務消費者該如何接受下載的資料呢?

一. 示例介紹

服務名 埠號 角色
feign_upload_first 8100 feign服務提供者
feign_upload_second 8101 feign服務消費者

我們呼叫feign_upload_second的下載檔案介面下載檔案,feign_upload_second內部使用feign呼叫feign_upload_first實現檔案下載。

二、feign_upload_first服務提供者

  • 服務提供者下載檔案介面
@RequestMapping(value = "/downloadFile",method = RequestMethod.GET,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public void downloadFile(HttpServletResponse response){
      String filePath = "D://1.txt";
      File file = new File(filePath);
      InputStream in = null
; if(file.exists()){ try { OutputStream out = response.getOutputStream(); in = new FileInputStream(file); byte buffer[] = new byte[1024]; int length = 0; while ((length = in.read(buffer)) >= 0){ out.write(buffer,0,length); } } catch
(IOException e) { e.printStackTrace(); } finally { if(in != null){ try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } } }

三、feign_upload_second服務消費者

  • 服務提供者遠端呼叫介面
@RequestMapping(value = "/downloadFile",method = RequestMethod.GET,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
  Response downloadFile();

用feign.Response來接收

  • 服務提供者下載檔案介面
@RequestMapping(value = "/download",method = RequestMethod.GET)
  public ResponseEntity<byte[]> downFile(){
    ResponseEntity<byte[]> result=null ;
    InputStream inputStream = null;
    try {
      // feign檔案下載
      Response response = uploadService.downloadFile();
      Response.Body body = response.body();
      inputStream = body.asInputStream();
      byte[] b = new byte[inputStream.available()];
      inputStream.read(b);
      HttpHeaders heads = new HttpHeaders();
      heads.add(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=123.txt");
      heads.add(HttpHeaders.CONTENT_TYPE,MediaType.APPLICATION_JSON_VALUE);

      result = new ResponseEntity <byte[]>(b,heads, HttpStatus.OK);
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if(inputStream != null){
        try {
          inputStream.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    return result;
  }