日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

Java带宽限速器、Springboot限速器

發布時間:2023/12/18 java 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Java带宽限速器、Springboot限速器 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Java限速器,設計思路
1.假設下載或上傳速度上限是: m(KB/s),那么發送一個固定的字節數據[假設是n字節(Bytes)]
時間花費 -> 單位:毫秒 == 1000 * n/(m*1024)
2.假設發送n字節的數據只花費了t毫秒,
那么發送線程就應該睡眠(毫秒): 1000 * n/(m*1024)- t毫秒

java實現代碼

public class SpeedLimiter {/** 速度上限(KB/s), 0=不限速 */private int maxRate = 1024;private long getMaxRateBytes(){return this.maxRate * 1024;}private long getLessCountBytes() {long lcb = getMaxRateBytes() / 10;if (lcb < 10240) lcb = 10240;return lcb;//return 1024l * 20;}public SpeedLimiter(int maxRate) {this.setMaxRate(maxRate);}public synchronized void setMaxRate(int maxRate){this.maxRate = maxRate < 0 ? 0 : maxRate;}private long totalBytes = 0;private long tmpCountBytes = 0;private long lastTime = System.currentTimeMillis();/*** @author Ethan* @date 2022-11-18* @param len send bytes* @description 計算線程延時* sendTime(Ms) = nowTime - lastTime;* workTime(Ms) = (totalBytes*1000)/(maxRate*1024)* delayTime(Ms) = workTime-sendTime**/public synchronized void delayNextBytes(int len) {if (maxRate <= 0) return;totalBytes += len;tmpCountBytes += len;//未達到指定字節數跳過...if (tmpCountBytes < getLessCountBytes()) {return;}long nowTime = System.currentTimeMillis();long sendTime = nowTime - lastTime;long workTime = (totalBytes * 1000) / getMaxRateBytes();long delayTime = workTime - sendTime;if (delayTime > 0) {try {Thread.sleep(delayTime);} catch (InterruptedException e) {e.printStackTrace();}tmpCountBytes = 0;}} }

集成到Springboot進行下載測試

?DownloadController代碼

@RestController @RequestMapping(value = "/api/v1/download") public class DownloadController {//設置一個本地文件用于下載測試, 大小約幾百MBfinal String localFile = "E:/tmp/A2.tar.gz";/*** @author Ethan* @date 2022-11-18* @description 普通下載測試, 不限速!**/@GetMapping("getFile")public void getFile(HttpServletResponse response) {File file = this.getLocalFile(response, localFile);if (file == null || !file.exists()) {return;}InputStream is = null;OutputStream out = null;try {is = new FileInputStream(file);out = response.getOutputStream();IOUtils.copyLarge(is, out);} catch (Exception e) {e.printStackTrace();} finally {IOUtils.closeQuietly(is);IOUtils.closeQuietly(out);}}/*** @author Ethan* @date 2022-11-18* @description 限速下載測試, xxx KB/s**/@GetMapping("limit")public void limit(@RequestParam(value = "speed", defaultValue = "500", required = false) int speed,HttpServletResponse response) {File file = this.getLocalFile(response, localFile);if (file == null || !file.exists()) {return;}BufferedInputStream bis = null;OutputStream out = null;try {bis = new BufferedInputStream(new FileInputStream(file));out = response.getOutputStream();byte[] buffer = new byte[1024];int length;SpeedLimiter speedLimiter = new SpeedLimiter(speed);while ((length = bis.read(buffer)) != -1) {out.write(buffer, 0, length);if (speedLimiter != null) {speedLimiter.delayNextBytes(length);}}} catch (Exception e) {e.printStackTrace();} finally {IOUtils.closeQuietly(bis);IOUtils.closeQuietly(out);}}private File getLocalFile(HttpServletResponse response, String fullPath){File file = new File(fullPath);if (file.exists()) {String fileName = file.getName();response.setHeader("Content-Length", String.valueOf(file.length()));response.setHeader("Content-Type", "application/x-zip-compressed");response.setHeader("Content-Disposition", "attachment; filename=" + fileName);} else {String noteMsg = "本地測試文件[" + file + "]不存在";System.err.println(noteMsg);this.setResponse(response, noteMsg);}return file;}private final static String CharacterEncoding = "UTF-8";private final static String MediaType = "application/json";private void setResponse(HttpServletResponse res, String noteMsg) {try {int httpStatus = HttpStatus.OK.value();res.setCharacterEncoding(CharacterEncoding);res.setContentType(MediaType);res.setStatus(httpStatus);res.getWriter().write(noteMsg);} catch (Exception e) {e.printStackTrace();}} }


啟動Springboot

使用firefox瀏覽器分別測試
限速下載(500KB/s) ? http://127.0.0.1:8080/api/v1/download/limit

限速下載(900KB/s) ? http://127.0.0.1:8080/api/v1/download/limit?speed=900

經過測試,可以滿足需求!

完整demo下載地址
https://download.csdn.net/download/tianbbs2008/87126141

總結

以上是生活随笔為你收集整理的Java带宽限速器、Springboot限速器的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。