如何限制Java中的带宽? [英] How can I limit bandwidth in Java?

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

问题描述

我写了一个Java调度程序,每小时使用:

I wrote a Java scheduler, every hour using:

new SAXBuilder().build(new URL(xxx));

HttpConnection.connect(new URL(xxx)); // jsoup library code

获取大型XML / HTML文件。

to get a big XML/HTML file.

我的服务器最大带宽限制是2Mbits。

My server maximum bandwidth limit is 2Mbits.

当这个Java调度代码运行时,我使用超过2Mbits的带宽。 (查看

When this Java schedule code runs, I use over 2Mbits of bandwidth. (check it out)

所以每次用户访问我的服务器时都会太慢。

So every time a user visits my server it is too slow.

如何限制我的Java计划使用较低的带宽?
(例如500Kbits)

How do I limit my Java schedule to use lower bandwidth? (ex. 500Kbits)

我正在使用Ubuntu服务器。

I am using Ubuntu server.

推荐答案

没有优雅的方法可以做到这一点。

There's no elegant way to do this.

一种简单但不优雅的方法是编写一个Java流包装器来限制读取字节的速率来自包裹的溪流。例如,如果要限制为每秒1000字节,则可以按如下方式实现 int read()方法:

A simple but inelegant way would be to write a Java stream wrapper that limits the rate at which bytes are read from the wrapped Stream. For instance, if you wanted to limit to 1000 bytes per second, the int read() method could be implemented as follows:

Stream in;
long timestamp = System.currentTimeInMillis();
int counter = 0;
int INTERVAL = 1000; // one second
int LIMIT = 1000; // bytes per INTERVAL

...

/**
 * Read one byte with rate limiting
 */
@Override
public int read() {
    if (counter > LIMIT) {
        long now = System.currentTimeInMillis();
        if (timestamp + INTERVAL >= now) {
            Thread.sleep(timestamp + INTERVAL - now);  
        }
        timestamp = now;
        counter = 0;
    }
    int res = in.read();
    if (res >= 0) {
        counter++;
    }
    return res;
}






值得注意的是像这样的节流率可能有负面影响和积极影响。在消极方面:


It is worth noting that throttling rates like this can have negative as well as positive effects. On the negative side:


  • 它将服务器端的资源关联更长时间。在这种情况下,我们讨论的是处理下载的Java线程,内核空间中的内存用于缓冲接收到的网络数据包,直到应用程序读取它们为止。

  • It ties down resources on the server side for longer. In this case, we are talking about the Java thread that is handling the download, and memory in kernel space is used to buffer received network packets until the application reads them.

它还可能导致更多网络流量。问题是这种限制会破坏数据包的顺畅流动。服务器只缓冲相对较少数量的数据包,当超过该数量时,它必须告诉客户端暂时停止。这需要额外的信令包(ACK),并且可能在该过程中丢弃数据包。最终,需要重新传输这些数据包。

It may also lead to more network traffic. The problem is that this kind of throttling will disrupt the smooth flow of packets. The server will only buffer a relatively small number of packets, and when that number is exceeded, it has to tell the client to STOP for now. This requires extra signalling packets (ACKs) and there will probably be data packets dropped in the process. Eventually, those data packets will need to be retransmitted.

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

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