tomcat真正做到零拷贝文件下载的使用方式及原理解析

2023-09-12  本文已影响0人  江江的大猪

前言

使用tomcat普通文件下载的正确姿势(性能差,容易oom)

    @PostMapping("download")
    public ResponseEntity<byte[]> download() throws IOException {
        String filePath = "xxx";
        String fileName = "xxx";
        Path file = Paths.get(filePath);
        byte[] bytes = FileUtils.readFileToByteArray(file.toFile());
        String contentType = Files.probeContentType(file);
        if (contentType == null) {
            contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType(contentType));
        headers.setContentDisposition(ContentDisposition.attachment().filename(fileName, Charsets.UTF_8).build());
        return ResponseEntity.ok().headers(headers).body(bytes);
    }

使用tomcat实现零拷贝文件下载的正确姿势

    @PostMapping("zeroCopyDownload")
    public void zeroCopyDownload(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String filePath = "xxx";
        String fileName = "xxx";
        if (!Boolean.parseBoolean(request.getAttribute(Constants.SENDFILE_SUPPORTED_ATTR).toString())) {
            throw new MyException("unsupported");
        }
        Path file = Paths.get(filePath);
        String contentType = Files.probeContentType(file);
        if (contentType == null) {
            contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
        }
        response.setContentType(contentType);
        response.setContentLengthLong(file.toFile().length());
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, ContentDisposition.attachment().filename(fileName, Charsets.UTF_8).build().toString());
        // 通过start/end可以实现零拷贝分片下载
        // 请求域attribute参数详见 https://tomcat.apache.org/tomcat-10.1-doc/api/org/apache/coyote/Constants.html
        request.setAttribute(Constants.SENDFILE_FILENAME_ATTR, filePath);
        request.setAttribute(Constants.SENDFILE_FILE_START_ATTR, 0L);
        request.setAttribute(Constants.SENDFILE_FILE_END_ATTR, file.toFile().length());
    }

    // tomcat源码Http11Processor.prepareSendfile如下,使用上面设置的attribute构建sendfileData
    private void prepareSendfile(OutputFilter[] outputFilters) {
        String fileName = (String) request.getAttribute(org.apache.coyote.Constants.SENDFILE_FILENAME_ATTR);
        if (fileName == null) {
            sendfileData = null;
        } else {
            // No entity body sent here
            outputBuffer.addActiveFilter(outputFilters[Constants.VOID_FILTER]);
            contentDelimitation = true;
            long pos = ((Long) request.getAttribute(org.apache.coyote.Constants.SENDFILE_FILE_START_ATTR)).longValue();
            long end = ((Long) request.getAttribute(org.apache.coyote.Constants.SENDFILE_FILE_END_ATTR)).longValue();
            sendfileData = socketWrapper.createSendfileData(fileName, pos, end - pos);
        }
    }

    // tomcat源码NioEndpoint.processSendfile简略版如下,调用transferTo将sendfileData传输到SocketChannel中
    public SendfileState processSendfile(SelectionKey sk, NioEndpoint.NioSocketWrapper socketWrapper, boolean calledByProcessor) {
        NioEndpoint.SendfileData sd = socketWrapper.getSendfileData();
        NioChannel sc = socketWrapper.getSocket();
        // TLS/SSL channel is slightly different,https因为一定要把数据读取到应用侧校验,所以无法使用零拷贝
        WritableByteChannel wc = ((sc instanceof SecureNioChannel) ? sc : sc.getIOChannel());
        long written = sd.fchannel.transferTo(sd.pos, sd.length, wc);
        if (written > 0) {
            sd.pos += written;
            sd.length -= written;
            socketWrapper.updateLastWrite();
        }
    }

使用tomcat文件下载的常见错误做法

Channels.newChannel()创建出来的是WritableByteChannelImpl对象,零拷贝传输并不支持该类型

    @PostMapping("download")
    public void download(HttpServletResponse response) throws IOException {
        String filePath = "xxx";
        String fileName = "xxx";
        Path file = Paths.get(filePath);
        String contentType = Files.probeContentType(file);
        if (contentType == null) {
            contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
        }
        try (FileChannel fileChannel = FileChannel.open(file)) {
            WritableByteChannel outChannel = Channels.newChannel(response.getOutputStream());
            long size = fileChannel.size();
            response.setContentType(contentType);
            response.setContentLengthLong(size);
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, ContentDisposition.attachment().filename(fileName, Charsets.UTF_8).build().toString());
            for (long position = 0; position < size; ) {
                position = position + fileChannel.transferTo(position, size - position, outChannel);
            }
        }
    }

FileChannel.transferTo的实现解析(sun.nio.ch.FileChannelImpl中实现)

就不详细看代码了,只看主体逻辑,这里也能解释为什么说上面那种调用fileChannel.transferTo的方法并不是零拷贝,因为目标channel是WritableByteChannelImpl,最终只会调用到transferToArbitraryChannel

transferTo方法中会依次尝试调用下面三个方法
// 仅支持目标channel是FileChannel和SelChImpl(SocketChannel、ServerSocketChannel)
// 最终调用native方法transferTo0,不同操作系统实现不一样
transferToDirectly();
// 仅支持目标channel是FileChannel
// 调用FileChannel的map方法最终调用native方法map0获得MappedByteBuffer,然后写入
transferToTrustedChannel();
// 最普通的做法,现在应用侧读取文件内容再写入,
transferToArbitraryChannel();

transferTo0的native实现解析(以jdk8为例)

可以看到linux和mac是支持的(也无法保证每个版本都支持),window不支持。这也体现了即使使用了正确的目标channel类型,可以最终调用到transferTo0的native方法也无法保证一定是零拷贝,还要看运行的操作系统是否支持

// *nux实现https://github.com/openjdk/jdk/blob/jdk8-b120/jdk/src/solaris/native/sun/nio/ch/FileChannelImpl.c
Java_sun_nio_ch_FileChannelImpl_transferTo0(JNIEnv *env, jobject this,
                                            jint srcFD,
                                            jlong position, jlong count,
                                            jint dstFD)
{
#if defined(__linux__)
    // 省略
    jlong n = sendfile64(dstFD, srcFD, &offset, (size_t)count);
#elif defined (__solaris__)
    // 省略
    result = sendfilev64(dstFD, &sfv, 1, &numBytes);
#elif defined(__APPLE__)
    // 省略
    result = sendfile(srcFD, dstFD, position, &numBytes, NULL, 0);
#else
    return IOS_UNSUPPORTED_CASE;
#endif
// windows实现https://github.com/openjdk/jdk/blob/jdk8-b120/jdk/src/windows/native/sun/nio/ch/FileChannelImpl.c
Java_sun_nio_ch_FileChannelImpl_transferTo0(JNIEnv *env, jobject this,
                                            jint srcFD,
                                            jlong position, jlong count,
                                            jint dstFD)
{
    return IOS_UNSUPPORTED;
}

总结

上一篇 下一篇

猜你喜欢

热点阅读