其他分享
首页 > 其他分享> > ES中的流量控制

ES中的流量控制

作者:互联网

/**
 * Rate limiting wrapper for InputStream
 */
public class RateLimitingInputStream extends FilterInputStream {

    private final RateLimiter rateLimiter;

    private final Listener listener;

    private long bytesSinceLastRateLimit;

    public interface Listener {
        void onPause(long nanos);
    }

    public RateLimitingInputStream(InputStream delegate, RateLimiter rateLimiter, Listener listener) {
        super(delegate);
        this.rateLimiter = rateLimiter;
        this.listener = listener;
    }

    private void maybePause(int bytes) throws IOException {
        bytesSinceLastRateLimit += bytes;
        if (bytesSinceLastRateLimit >= rateLimiter.getMinPauseCheckBytes()) {
            long pause = rateLimiter.pause(bytesSinceLastRateLimit);
            bytesSinceLastRateLimit = 0;
            if (pause > 0) {
                listener.onPause(pause);
            }
        }
    }

    @Override
    public int read() throws IOException {
        int b = super.read();
        maybePause(1);
        return b;
    }

    @Override
    public int read(byte[] b, int off, int len) throws IOException {
        int n = super.read(b, off, len);
        if (n > 0) {
            maybePause(n);
        }
        return n;
    }
}

每读一个字节都会检测是否要pause

标签:控制,pause,rateLimiter,bytesSinceLastRateLimit,int,流量,listener,public,ES
来源: https://blog.csdn.net/chuanyangwang/article/details/120586525