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%左右浮动。

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

posted @ 2015-10-13 14:59  lcchuguo  阅读(1451)  评论(0编辑  收藏  举报