【发布时间】:2019-01-02 06:55:24
【问题描述】:
我在一个 Spring 项目上工作以制作一个 Web 应用程序,因此有一个 Tomcat 服务器允许我使用我的 Web 应用程序午餐。
我在这个网络应用程序上有 2 个功能,第一个允许我在 Postgresql 数据库上上传文件(它工作正常)。但在那之后,我希望能够下载这个文件。
这是我的服务方法。
public byte[] download(Integer id){
Line line = getById(Line.class, id);
int blobLenght;
byte[] fileToReturn = null;
Blob file = line.getFile();
blobLenght = (int)file.length();
fileToReturn = file.getBytes(1,blobLenght);
return fileToReturn;
}
在我的 RestController 上,我有一个带有 @RequestMapping 注释的方法。 并且此方法返回一个 ResponseEntity。在之后的方法中,lineService 在我的类的顶部注入(@Autowired)。
@RequestMapping(value = "/download", method = RequestMethod.GET)
public ResponseEntity<?> download(@RequestParam("id" Integer id)
{
byte[] fileToDownload = lineService.download(id);
return new ResponseEntity<byte[]>(fileToDownload,HttpStatus.OK);
}
我已尽力简化方法。
这是我的问题。确实,我意识到一种方法,当我一个一个地提出一些请求时,它就可以工作。但是,服务器必须能够支持同时接收大量请求。现在,当我同时测试多个请求时,我得到了 OutOfMemoryError : Java heap space。
我试图在“下载”方法上实现 Stream,但我得到了同样的错误。我对流的实现做得不好。
我尝试了许多在互联网上找到的解决方案,这是我实施的最后一个:
public ResponseEntity<byte[]> download(Integer id){
Line line = getById(Line.class, id);
HttpHeaders headers = new HttpHeaders();
InputStream is = line.getFile().getBinaryStream;
byte[] fileToReturn = IOUtils.toByteArray(is);
headers.setCacheControl(CacheControl.noCache().getHeaderValue());
ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(fileToDownload,HttpStatus.OK);
return responseEntity;
}
你知道我可以如何更新我的程序来回答项目的要求吗?
如果我在好的路上,你能告诉我我的错误在哪里,或者你有什么建议吗?
感谢您的帮助!
下午。
【问题讨论】:
标签: java spring postgresql stream blob