【Java小功能】SFTP上传限速

文章目录


前言

监控sftp上传的速率,根据限定的上传速率,对线程采用睡眠的方式进行限速。


代码逻辑

//定义限速10Mbps
long limitBytesPerSecond = 10;
//是否限速
boolean limit = true;
// 上传文件
out = channelSftp.put(dstPath + ".w", new SFTPProcessMonitor(Files.size(Paths.get(outputFileName)), outputFileName), ChannelSftp.OVERWRITE);
uploadResult = false;
//根据业务需求合理定义大小
byte[] buffer = new byte[4096];
long sleep_time_ms = 100;
int read;
long totalBytesWritten = 0;
long starTime = System.currentTimeMillis();
if (out != null) {
    in = new FileInputStream(outputFileName);
    do {
        read = in.read(buffer, 0, buffer.length);
        if (read > 0) {
            out.write(buffer, 0, read);
        }
        out.flush();
        //限速逻辑
        if (limit){
            totalBytesWritten += read;
            long currentTime = System.currentTimeMillis();
            long elapsedTime = currentTime - starTime;
            if (elapsedTime > 0){
                long allBytes = (long) (elapsedTime * limitBytesPerSecond / 1000.0);
                if(totalBytesWritten > allBytes){
                    logger.info("当前已经被限速!");
                    long delay = (totalBytesWritten -allBytes) * 1000 / limitBytesPerSecond;
                    Thread.sleep(Math.max(delay,sleep_time_ms));
                    starTime = System.currentTimeMillis();//重置计时器
                    totalBytesWritten = 0;
                }
            }
        }
    } while (read >= 0);
}
logger.info("文件{}上传至FTP成功", dstPath);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值