Java带宽限速器、Springboot限速器
Java限速器,設(shè)計(jì)思路
1.假設(shè)下載或上傳速度上限是: m(KB/s),那么發(fā)送一個(gè)固定的字節(jié)數(shù)據(jù)[假設(shè)是n字節(jié)(Bytes)]
時(shí)間花費(fèi) -> 單位:毫秒 == 1000 * n/(m*1024)
2.假設(shè)發(fā)送n字節(jié)的數(shù)據(jù)只花費(fèi)了t毫秒,
那么發(fā)送線程就應(yīng)該睡眠(毫秒): 1000 * n/(m*1024)- t毫秒
java實(shí)現(xiàn)代碼
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 計(jì)算線程延時(shí)* 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;//未達(dá)到指定字節(jié)數(shù)跳過...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進(jìn)行下載測(cè)試
?DownloadController代碼
@RestController @RequestMapping(value = "/api/v1/download") public class DownloadController {//設(shè)置一個(gè)本地文件用于下載測(cè)試, 大小約幾百M(fèi)Bfinal String localFile = "E:/tmp/A2.tar.gz";/*** @author Ethan* @date 2022-11-18* @description 普通下載測(cè)試, 不限速!**/@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 限速下載測(cè)試, 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 = "本地測(cè)試文件[" + 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();}} }
啟動(dòng)Springboot
使用firefox瀏覽器分別測(cè)試
限速下載(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
經(jīng)過測(cè)試,可以滿足需求!
完整demo下載地址
https://download.csdn.net/download/tianbbs2008/87126141
總結(jié)
以上是生活随笔為你收集整理的Java带宽限速器、Springboot限速器的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: N2N内网穿透
- 下一篇: 飞桨领航团武汉长沙 | AI如何1秒记笔