限制Java的上传速度? [英] Limiting upload speed on Java?

查看:677
本文介绍了限制Java的上传速度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以编程方式限制Java中的上传或下载操作。我会假设我需要做的就是检查上传的速度,并相应地插入 Thread.sleep()

I'd like to programmatically limit an upload or download operation in Java. I would assume that all I'd need to do was do check how fast the upload is going and insert Thread.sleep() accordingly like so:

while (file.hasMoreLines()) {
    String line = file.readLine();
    for (int i = 0; i < line.length(); i+=128) {
        outputStream.writeBytes(line.substr(i, i+128).getBytes());
        if (isHittingLimit())
            Thread.sleep(500);
    }
}

以上代码是否有效?如果没有,有更好的方法吗?是否有一个描述该理论的教程?

Will the above code work? If not, is there a better way to do this? Is there a tutorial which describes the theory?

推荐答案

令牌桶算法是一种限制上载或下载带宽的方法。
你应该阅读这篇文章:它解释了这种算法的使用。

Token Bucket Algorithm is a way to limit an upload or a download's bandwidth. You should read this article : it explains the use of this algorithm.

使用 Guava RateLimiter

// rate = 512 permits per second or 512 bytes per second in this case
final RateLimiter rateLimiter = RateLimiter.create(512.0); 

while (file.hasMoreLines()) {
    String line = file.readLine();
    for (int i = 0; i < line.length(); i+=128) {
        byte[] bytes = line.substr(i, i+128).getBytes();
        rateLimiter.acquire(bytes.length);
        outputStream.writeBytes(bytes);
    }
}

如Guava文档中所述:
<重要的是要注意,请求的许可数量永远不会影响请求本身的限制(对acquire(1)的调用和对acquire(1000)的调用将导致完全相同的限制,如果有的话),但是它会影响下一个请求的限制。即,如果一个昂贵的任务到达空闲的RateLimiter,它将立即被授予,但它是下一个将经历额外限制的请求,从而支付昂贵任务的成本。

As explained in Guava docs: It is important to note that the number of permits requested never affects the throttling of the request itself (an invocation to acquire(1) and an invocation to acquire(1000) will result in exactly the same throttling, if any), but it affects the throttling of the next request. I.e., if an expensive task arrives at an idle RateLimiter, it will be granted immediately, but it is the next request that will experience extra throttling, thus paying for the cost of the expensive task.

这篇关于限制Java的上传速度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆