问题及代码示例:
客户端发送消息给服务端。服务端处理时,用的addLast()指定了DefaultEventLoopGroup多线程去执行serverhandler。然后定时去打印此handler的QPS。
预期和结果不符合。QPS打印是个位数。
用visualVM 查看服务端线程:发现DefaultEventLoopGroup就只有一个线程运行。
public class MyServer {
public static void main(String[] args) throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
DefaultEventLoopGroup eventLoopGroup = new DefaultEventLoopGroup(100);
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(eventLoopGroup, new ServerHandler());
}
});
//绑定端口号,启动服务端
ChannelFuture channelFuture = bootstrap.bind(6666).sync();
//对关闭通道进行监听
channelFuture.channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
class ServerHandler extends ChannelInboundHandlerAdapter {
ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
AtomicInteger integer = new AtomicInteger(0);
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
scheduledExecutorService.scheduleAtFixedRate(() -> {
int andSet = integer.get();
System.out.println("SERVER HANDLER QPS IS :" + andSet);
}, 0,1000, TimeUnit.MILLISECONDS);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
try {
System.out.println("server handler start to process");
// 模拟业务运行时间
Thread.sleep(2000);
integer.getAndAdd(1);
} catch (Exception e) {
e.printStackTrace();
} finally {
((ByteBuf)msg).release();
}
}
}
public class MyClient {
public static void main(String[] args) throws Exception {
NioEventLoopGroup eventExecutors = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(eventExecutors)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
//添加客户端通道的处理器
ch.pipeline().addLast(new ClientSendHandler());
}
});
ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 6666).sync();
channelFuture.channel().closeFuture().sync();
} finally {
eventExecutors.shutdownGracefully();
}
}
}
class ClientSendHandler extends ChannelInboundHandlerAdapter {
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
executorService.scheduleAtFixedRate(() -> {
for (int i = 0; i < 100; i++) {
try {
ByteBuf buffer = ctx.alloc().buffer(20);
// 模拟业务操作
Thread.sleep(new Random().nextInt(1000));
// 数据发送
buffer.writeBytes("hello, i am client".getBytes());
ctx.writeAndFlush(buffer);
System.out.println("client send success" + i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},0, 1000, TimeUnit.MILLISECONDS);
}
}
分析
进入addlast方法:
找到 newCtx = newContext(group, filterName(name, handler), handler);
其里面childExecutor(group)就是绑定的处理逻辑。可以看到就是从group里面取出的一个线程,然后将其与context绑定。而context包含handler,其实就是与handler绑定。后续的该handler的执行,都是用的同一个线程。
所以用该方法控制多线程执行handler根本上就是错误的。
private EventExecutor childExecutor(EventExecutorGroup group) {
...
// SINGLE_EVENTEXECUTOR_PER_GROUP,与本次无关。下文有介绍
Boolean pinEventExecutor = channel.config().getOption(ChannelOption.SINGLE_EVENTEXECUTOR_PER_GROUP);
if (pinEventExecutor != null && !pinEventExecutor) {
return group.next();
}
...
EventExecutor childExecutor = childExecutors.get(group);
if (childExecutor == null) {
childExecutor = group.next();
childExecutors.put(group, childExecutor);
}
return childExecutor;
}
解决
- 服务器端自定义线程池执行业务逻辑
class ServerHandler extends ChannelInboundHandlerAdapter {
ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
AtomicInteger integer = new AtomicInteger(0);
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(100);
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
scheduledExecutorService.scheduleAtFixedRate(() -> {
int andSet = integer.get();
System.out.println("SERVER HANDLER QPS IS :" + andSet);
}, 0,1000, TimeUnit.MILLISECONDS);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
fixedThreadPool.submit(() -> {
try {
System.out.println("server handler start to process");
// 模拟业务运行时间
Thread.sleep(2000);
integer.getAndAdd(1);
} catch (Exception e) {
e.printStackTrace();
} finally {
((ByteBuf)msg).release();
}
});
}
下图的poo1-2-thread-x就是执行的线程
- 客户端建立多次连接
一个TPC连接对应一个socket、一个channel、一个pipeline。
之前代码是一个客户端1s发100次,可以让客户端连服务端100次,每个TCP连接1s只发一个,貌似也达到了之前的效果。netty线程池
SINGLE_EVENTEXECUTOR_PER_GROUP 参数
每一个 channel 都会对应一个独立的 pipeline。该参数默认为true, 表示在一个 channel 对应的 pipeline 中,如果我们为多个 ChannelHandler 指定了同一个 EventExecutorGroup ,那么这多个 channelHandler 只能绑定到 EventExecutorGroup 中的同一个 EventExecutor 上。
总结
ChannelPipeline addLast(EventExecutorGroup group, ChannelHandler... handlers);
group不是 为每个handler分配一个新的线程去执行。
而是对pipeline来讲的。
- 假设SINGLE_EVENTEXECUTOR_PER_GROUP为true,
有A和B 两个pipeline,那么调用该方法后,A中的每个handler,都是同一个线程thread1去执行的。B中的每个handler都是由thread2去执行的 - SINGLE_EVENTEXECUTOR_PER_GROUP 为false,
有A和B 两个pipeline,那么调用该方法后,A中的每个handler,都是不同的线程去执行,thread1、thread2。B中的每个handler也是由不同的线程thread3、thread4执行的。
注意,这里只是举个例子,执行的线程到底是不是同一个,还要看group.next()逻辑。
参考:netty进阶之路-李林峰
作者:WKP9418
原文地址:https://blog.csdn.net/qq_43179428/article/details/140561346