流数据以响应Spring MVC 4.3使用Java 8,Tomcat 7

问题描述 投票:0回答:1

下面是在使用Java 8在tomcat 7中运行xyz.war时导致OutOfMemory问题的代码段。

在下面的代码中,我创建了一个CSV响应,通过游标从MongoDB获取数据。

@RequestMapping(value = "/elements/{elementname}/records", method = RequestMethod.GET)
public ModelAndView getAllRecords(
  HttpServletRequest request, HttpServletResponse response,
  @RequestParam(value = "customerid", required = true) long customerId,
  @RequestParam(value = "userid", required = true) long userId,
  @RequestParam(value = "query", required = false) String query,
  throws Exception {
    Map < String, Object > model = new HashMap < String, Object > ();
    JsonObject records = elementService.searchRecords(query);
    ModelAndViewData msvd = elementService.commonRestService
                                .getModelAndView("dataObject", "streamingView");
    return new ModelAndView(msvd.getViewName(), handleCsvReportTypeRequest(records, customerId, userId));
}

public Map < String, Object > handleCsvReportTypeRequest(JsonObject records,
        String elementName, long customerId, long userId) throws Exception {
    StringBuffer csvData = new StringBuffer();
    // create csv data
    ModelAndViewData modelAndStreamingViewData = commonRestService.getModelAndView(
    "dataObject", "streamingView");
    byte[] byteArray = String.valueOf(csvData).getBytes();
    InputStream byteArrayInputStream = new ByteArrayInputStream(byteArray);
    model.put(modelAndStreamingViewData.getModelAttributeName(), byteArrayInputStream);

    model.put(DownloadConstants.CONTENT_TYPE, DownloadConstants.CSV_CONTENT_TYPE);
    model.put(DownloadConstants.FILENAME, "XYZ.csv");
    model.put(DownloadConstants.LAST_MODIFIED, new Date(System.currentTimeMillis()));
    model.put(DownloadConstants.CONTENT_LENGTH, Integer.valueOf(byteArray.length));
    return model;
}

如何在不在内存中创建大量数据然后传递给用户的情况下将CSV数据流回用户?

spring spring-mvc java-8 tomcat7
1个回答
0
投票

使用缓冲读取并在HttpResponse对象中写入响应。

试试这种方式:Spring MVC : large files for download, OutOfMemoryException

© www.soinside.com 2019 - 2024. All rights reserved.