我需要限制netty服务器每秒在websocket频道上收到的消息。 无法找到任何想法。
任何想法都将不胜感激
谢谢
答案 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;
}
}