使用Feign进行远程调用文件下载

场景:项目拆分微服务,由于历史遗留原因,需进行一个报表下载的转发

例:访问接口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。

个人拙见,如果有更方便的方法请不吝赐教,多谢多谢~

posted @ 2020-12-28 17:44  alwaysFly  阅读(3389)  评论(0编辑  收藏  举报