Reputation: 1334
I have a question about netty server monitoring. I want to see how many open connections to the server are there, so to do that we have a code that has an atomic integer counter that is increased by 1 on ChannelInitializer.initChannel(..) method and decremented by 1 in closeFuture listener for that SocketChannel channel. For some reason that I can't figure out, it doesn't go to zero and stays positive under heavy load. I was hoping that maybe there is some better way of tracking these open channels?
@Override
protected void initChannel(SocketChannel channel) throws Exception {
currentConnections.incrementAndGet();
channel.closeFuture().addListener(f -> currentConnections.decrementAndGet());
}
UPDATE: So the number stays positive after clients stop sending traffic and disconnect.
Upvotes: 0
Views: 1876
Reputation: 2365
One way is to add a ChannelInboundHandler
and override the channelRegistered
and channelUnregistered
like so:
@Override
public void channelRegistered(final ChannelHandlerContext ctx) {
if (ctx.channel().remoteAddress() != null) {
connections.inc();
}
}
@Override
public void channelUnregistered(final ChannelHandlerContext ctx) {
currentConnections.dec();
}
Another way is to only add the channel to a ChannelGroup
when it's registered, and use ChannelGroup#size
when you want to query the current connection count.
I guess the former incurs less overhead, but the later allows you to performs actions on all active channels if you need this sort of functionality anyway.
Upvotes: 1