【问题标题】:Tomcat 8 file download speed issueTomcat 8 文件下载速度问题
【发布时间】:2015-06-30 06:14:52
【问题描述】:

我正在使用 Tomcat 8,并且我具有从上下文 docbase 文件夹中的 tomcat 服务器位置下载大文件的功能。 下面是我使用文件下载的一段代码:

PrintWriter out = response.getWriter();   
response.setContentType("APPLICATION/OCTET-STREAM");   
response.setHeader("Content-Disposition",
                   "attachment; filename=filename);  
FileInputStream fileInputStream = new FileInputStream("filepath");  
int i;   
while ((i=fileInputStream.read()) != -1) {  
    out.write(i);   
}   
fileInputStream.close();   
out.close();

当我下载文件时,它的下载速度为 65KB/秒 从存档服务器。如果我将同一个文件放在 Apache 服务器中并尝试下载,下载速度是 135KB/秒。

有人可以帮我加快从 Tomcat 下载文件的速度吗?

【问题讨论】:

    标签: java performance file tomcat download


    【解决方案1】:

    问题是一次读取和写入一个字节到无缓冲的流是非常低效的。查看this previous answer 并将其调整为您的代码,我们可以使用:

    // Assume ServletResponse response
    ServletOutputStream servletOutputStream = response.getOutputStream();
    response.setContentType("APPLICATION/OCTET-STREAM");   
    response.setHeader("Content-Disposition",
                       "attachment; filename=filename);  
    FileInputStream fileInputStream = new FileInputStream("filepath");  
    
    // Choose a bigger value if you want
    byte[] buffer = new byte[4096];
    int n;
    while ((n = fileInputStream.read(buffer) != -1)
    {
        servletOutputStream.write(buffer, 0, n);
    }
    fileInputStream.close();
    servletOutputStream.close();
    

    以上内容应该非常高效,并且有望等于或超过您报告的 Apache 速度。

    【讨论】:

    • 感谢您的回复,我尝试实施您建议的方式,但仍然没有看到下载速度有任何提高。
    猜你喜欢
    • 2013-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    相关资源
    最近更新 更多