问题描述
我想以编程方式限制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?
推荐答案
是一种限制上载或下载带宽的方法。
你应该阅读:
// 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文档中所述:
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的上传速度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!