前言
监控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);