場景:項目拆分微服務,由於歷史遺留原因,需進行一個報表下載的轉發
例:訪問接口1:http://localhost:8084/biReport/download進行報表下載,但是接口1需要去接口2:http://localhost:18091/biReport/download獲取文件流。
思路:使用Feign.Response接收接口2的返回,把文件流寫入到接口1的HttpServletResponse中。
代碼如下
接口1:
@RequestMapping(value = "/biReport/download",
produces = {"application/json;charset=UTF-8"},
method = RequestMethod.POST)
public void biReportDownload(HttpServletRequest request,
HttpServletResponse response,
@RequestBody String json) throws Exception {
OutputStream outputStream = response.getOutputStream();
response.setContentType("application/x-msdownload/vnd.ms-excel");
response.setHeader("Content-disposition","attachment;filename=excel-file.xlsx");
Response response1 = biReportService.download(json);
InputStream inputStream =null;
try {
Response.Body body = response1.body();
inputStream = body.asInputStream();
byte[] bytes = new byte[1024];
int len = 0;
while ((len = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, len);
}
}catch (Throwable e){
e.printStackTrace();
}finally {
inputStream.close();
outputStream.flush();
outputStream.close();
}
}
biReportService代碼:
import feign.Response;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;
@FeignClient(value = "PLUSMICROSERVICE-BI-REPORT")
public interface IBiReportService {
@PostMapping(value = "/biReport/query")
String query( String json);
@PostMapping(value = "/biReport/download")
Response download(String json);
}
接口2代碼:
@PostMapping("/download")
public void bidownload(HttpServletRequest request, HttpServletResponse response, @RequestBody String json) throws IOException {
reportService.reportDownLoad(request, response, json);
}
z
重點提醒!!!!!
接口1中獲取inputstream的代碼不需要DeBug運行,會報錯java.io.IOException: stream is closed。
個人拙見,如果有更方便的方法請不吝賜教,多謝多謝~
