java web 下载文件带宽限制_Java服务器下载速度的限制

没有取之不尽,用之不竭的资源。server有限的带宽。运营商可以限制一点点。近期使用云存储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%左右浮动。

版权声明:本文博主原创文章,博客,未经同意不得转载。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值