没有资源取之不尽用之不竭。服务器带宽有限,能限制一点算一点。最近在使用云存储openstack swift做文件存储下载。如题先上限速code:
private Long writeResponse(HttpServletResponse response,InputStream stream, Long speed, Long startTime, MessageDigest md5) {
byte[] b = null;
b = new byte[SwiftFileDownload.Download_Read_Unit];
try {
OutputStream os = null;
os = response.getOutputStream();
long count = 0;
int j;
while ((j = stream.read(b)) != -1) {
if (count + j > speed) {
int need = (int) (speed - count);
// 剩下的数
int left = (int) (j + count - speed);
byte[] temp = new byte[need];
byte[] leftTemp = new byte[left];
System.arraycopy(b, 0, temp, 0, need);
System.arraycopy(b, need, leftTemp, 0, left);
os.write(temp);
md5.update(temp);
os.flush();
long endTime = System.currentTimeMillis();
long sleepTime = startTime + 1000 - endTime;
if (sleepTime > 0) {
Thread.sleep(sleepTime);
}
startTime = System.currentTimeMillis();
count = 0;
os.write(leftTemp);
md5.update(leftTemp);
os.flush();
count += left;
continue;
}
if (count + j < speed) {
count += j;
byte[] temp = new byte[j];
System.arraycopy(b, 0, temp, 0, j);
os.write(temp);
md5.update(b);
os.flush();
continue;
}
if (count + j == speed) {
byte[] temp = new byte[j];
System.arraycopy(b, 0, temp, 0, j);
os.write(temp);
md5.update(b);
os.flush();
long endTime = System.currentTimeMillis();
long sleepTime = startTime + 1000 - endTime;
if (sleepTime > 0) {
Thread.sleep(sleepTime);
}
// 重置计数器
startTime = System.currentTimeMillis();
count = 0;
continue;
}
}
} catch (IOException e1) {
log.warn("writeResponse() - response=" + response + ", IOException",e1);
throw new BusinessSwiftException(e1);
} catch (InterruptedException e) {
log.warn("writeResponse() - response=" + response + ", IOException",e);
throw new BusinessSwiftException(e);
} finally {
try {
stream.close();
} catch (IOException e) {
log.warn("writeResponse() - 关闭swift对象流出错", e);
throw new BusinessSwiftException(e);
}
}
return startTime;
}
主要的思想:一段时间内写一段数据流,暂停1秒减去读取与写出的所有操作的时间。实测在10%左右的浮动。