使用Feign實現(xiàn)微服務(wù)間文件下載
在使用Feign做服務(wù)間調(diào)用的時候,當(dāng)下載大的文件會出現(xiàn)堆棧溢出的情況。另外,文件管理服務(wù)(服務(wù)提供者)文件下載接口無返回值,是通過HttpServletRespoonse傳輸?shù)牧鲾?shù)據(jù)來響應(yīng),那么服務(wù)消費者該如何接受下載的數(shù)據(jù)呢?
一. 示例介紹
我們調(diào)用feign_upload_second的下載文件接口下載文件,feign_upload_second內(nèi)部使用feign調(diào)用feign_upload_first實現(xiàn)文件下載。
二、feign_upload_first服務(wù)提供者
服務(wù)提供者下載文件接口
@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服務(wù)消費者
服務(wù)提供者遠程調(diào)用接口
@RequestMapping(value = "/downloadFile",method = RequestMethod.GET,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE) Response downloadFile();
用feign.Response來接收
服務(wù)提供者下載文件接口
@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; }
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot 監(jiān)控管理模塊actuator沒有權(quán)限的問題解決方法
這篇文章主要介紹了SpringBoot 監(jiān)控管理模塊actuator沒有權(quán)限的問題解決方法,需要的朋友可以參考下2017-12-12JDBC數(shù)據(jù)庫連接過程及驅(qū)動加載與設(shè)計模式詳解
這篇文章主要介紹了JDBC數(shù)據(jù)庫連接過程及驅(qū)動加載與設(shè)計模式詳解,需要的朋友可以參考下2016-10-10Java使用IOC控制反轉(zhuǎn)的三種設(shè)計模式詳解
這篇文章主要為大家詳細介紹了Java使用IOC控制反轉(zhuǎn)的三種設(shè)計模式,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-10-10java搭建一個Socket服務(wù)器響應(yīng)多用戶訪問
本篇文章主要介紹了java搭建一個Socket服務(wù)器響應(yīng)多用戶訪問,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-02-02