Netty:如何每秒限制websocket频道消息?

时间:2018-04-02 11:34:01

标签: java websocket netty

我需要限制netty服务器每秒在websocket频道上收到的消息。 无法找到任何想法。

任何想法都将不胜感激

谢谢

1 个答案:

答案 0 :(得分:2)

您需要向管道添加简单的ChannelInboundHandlerAdapter处理程序,并将简单计数器添加到channelRead(ChannelHandlerContext ctx, Object msg)方法。我建议你为此目的使用一些CodaHale Metrics类。

伪代码:

private final QuotaLimitChecker limitChecker;

public MessageDecoder() {
    this.limitChecker = new QuotaLimitChecker();
}


@Override 
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (limitChecker.quotaReached(100)) { //assume limit is 100 req per sec
        return;
    }
}

其中QuotaLimitChecker是一个增加计数器并检查是否达到限制的类。

public class QuotaLimitChecker {

    private final static Logger log = LogManager.getLogger(QuotaLimitChecker.class);

    private final int userQuotaLimit;
    //here is specific implementation of Meter for your needs
    private final InstanceLoadMeter quotaMeter;

    public QuotaLimitChecker(int userQuotaLimit) {
        this.userQuotaLimit = userQuotaLimit;
        this.quotaMeter = new InstanceLoadMeter();
    }

    public boolean quotaReached() {
        if (quotaMeter.getOneMinuteRate() > userQuotaLimit) {
            log.debug("User has exceeded message quota limit.");
            return true;
        }
        quotaMeter.mark();
        return false;
    }

}

Here is我使用CodaHale Metrics库的简化版Meter类的QuotaLimitChecker实现。