NIO文件复制+RateLimiter限流

/**
 * 平衡工具类
 *
 * @author lucky
 * @date 2022-09-29
 */
@Slf4j
public class BalanceUtil {
      /**
     * 最大传输字节数 4MB
     */
    final static int MAX_COUNT = 4 * 1024 * 1024;

    /**
     * 最大传输速度 150MB/s
     */
    final static double MAX_SPEED = 150.0d * 1024 * 1024;

    private static final RateLimiter RATE_LIMITER = RateLimiter.create(MAX_SPEED / MAX_COUNT);
  
  
  /**
     * 复制文件
     * NIO是一种基于通道和缓冲区的io方式,它可以使用native函数直接分配堆外内存,然后通过一个存储在java堆里面的DirectByteBuffer
     * 对象作为这块内存的直接引用进行操作。这样能在一些场景显著提高性能,因为避免了在java堆和native堆中来回复制数据。
     *
     * @param source 源
     * @param target 目标
     * @param flag   标志
     */
    public static void copyFile(String source, String target, Boolean flag) throws IOException {
        long l = 0;
        if (flag) {
            log.info("正在复制:{} -----> {}", source, target);
            l = System.currentTimeMillis();
        }

        try (FileChannel from = new RandomAccessFile(source, "rw").getChannel();
             FileChannel to = new RandomAccessFile(target, "rw").getChannel()) {

            long size = from.size();
            long position = 0;
            while (position < size) {
                if (RATE_LIMITER.tryAcquire()) {
                    position += from.transferTo(position, MAX_COUNT, to);
                }
            }
        }

        if (flag) {
            log.info("用时: {}", (System.currentTimeMillis() - l) + "ms");
        }
    }
}
posted @ 2022-10-17 19:56  Zm-Lucky  阅读(26)  评论(0)    收藏  举报