我正在使用Java Spring和Hibernate构建一个Web站点,并使用Tomcat 7作为服务器。 我有一个这个网站的页面,一旦用户点击图像,其他两个图像被加载。工作流程如下:
图片点击 - >计算(弹簧方法) - >以jpg格式保存在服务器上的图像 - >图像从服务器更新并显示给客户端。
图像加载如下:
response.setContentType("image/jpg");
OutputStream out = response.getOutputStream();
FileInputStream in = new FileInputStream(xzCrossUrl);
int size = in.available();
byte[] content = new byte[size];
in.read(content);
out.write(content);
in.close();
out.close();
我知道这可能不是最好的方法,但我还没有多少经验。
在本地它可以正常工作,但当我将.war放在tomcat目录并连接到服务器时,会出现Java outOfMemory堆空间问题,并且加载的图像比本地慢得多。
我试图增加tomcat使用的内存,但似乎没有用;也许我做错了什么。
你能帮我解决这个问题吗?
非常感谢你!
答案 0 :(得分:1)
我无法将其置于评论中,因为我没有足够的信誉,所以......
虽然您可以使用Tomcat配置修复此问题,但您拥有的代码不会针对任何图像进行缩放。您应该将byte[]
声明为固定大小,然后读取和写入,直到您消耗了所有文件字节为止:
// as a class scoped constant
private static final int BUFFERSIZE = 1024 << 8;
BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream(), BUFFERSIZE);
BufferedInputStream in = new BufferedInputStream(new FileInputStream(xzCrossUrl));
int bytesRead = 0;
byte[] content = new byte[BUFFERSIZE];
while((bytesRead = in.read(content) != -1){
out.write(content,0,bytesRead);
}
// Don't forget appropriate exception handling with a try/finally!
in.close();
out.close();
BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream(), BUFFERSIZE);
BufferedInputStream in = new BufferedInputStream(new FileInputStream(xzCrossUrl));
int bytesRead = 0;
byte[] content = new byte[BUFFERSIZE];
while((bytesRead = in.read(content) != -1){
out.write(content,0,bytesRead);
}
// Don't forget appropriate exception handling with a try/finally!
in.close();
out.close();
仅供参考:我在这里写的不是在IDE中编写的,也没有编译它,所以我很抱歉,如果不是完美的话。希望你得到要点。
答案 1 :(得分:0)
如何使用Apache Commons IO软件包中的IOUtils.copy()
- 它会将输入流复制到输出流,并在内部进行缓冲,因此您不必这样做。
response.setContentType("image/jpg");
OutputStream out = response.getOutputStream();
FileInputStream in = new FileInputStream(xzCrossUrl);
IOUtils.copy(in, out);
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
对于较大的文件,您可以使用IOUtils.copyLarge()
有关Commons IO的更多信息,请参阅http://commons.apache.org/proper/commons-io/