码迷,mamicode.com
首页 > 编程语言 > 详细

Java服务端限制下载速度

时间:2015-06-06 09:16:56      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:java   限速   存储   

没有资源取之不尽用之不竭。服务器带宽有限,能限制一点算一点。最近在使用云存储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%左右的浮动。

Java服务端限制下载速度

标签:java   限速   存储   

原文地址:http://blog.csdn.net/ray891010/article/details/46382409

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!