0

我正在使用 Java Spring 和 Hibernate 构建一个网站,并使用 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使用的内存,但似乎不起作用;也许我做错了什么。

你能帮我解决这个问题吗?

非常感谢您!

4

2 回答 2

1

I can't put this in a comment because I don't have enough cred, so...

While it may be something you can fix with the Tomcat configuration, what code you have will not scale for any image. You should declare the byte[] to be a fixed size and then read and write until you've consumed all of the file bytes:

// 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();

FYI: I wrote this here, not in an IDE and have not compiled it, so my apologies if isn't perfect. Hopefully you get the gist.

于 2013-10-25T13:17:42.010 回答
0

如何IOUtils.copy()从 Apache Commons IO 包中使用 - 它将输入流复制到输出流并在内部缓冲,因此您不必这样做。

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/

于 2013-10-25T13:33:03.927 回答