一、说明:
EmbeddedChannel: 把netty中的 EmbeddedChannel 当作链式调用。
二、代码:
package netty;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
public class EmbeddedChannelTest {
public static void main(String[] args) {
EmbeddedChannelDemo demo = new EmbeddedChannelDemo();
demo.execDemo();
}
}
class EmbeddedChannelDemo {
private final EmbeddedChannel channel = new EmbeddedChannel();
private final ByteBuf byteBuf = ByteBufAllocator.DEFAULT.heapBuffer(8);
private final byte[] defaultBytes = "12345678".getBytes();
public void execDemo() {
channel.pipeline().addLast(new CreateMessageHandler());
channel.pipeline().addLast(new HandMessageHandler());
for (int i = 0; i < 10; i++) {
byteBuf.clear();
byteBuf.writeBytes(defaultBytes);
channel.writeInbound(byteBuf);
channel.readInbound();
}
}
public static class CreateMessageHandler extends ChannelInboundHandlerAdapter {
private InternalLogger logger = InternalLoggerFactory.getInstance(CreateMessageHandler.class);
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
logger.info("ChannelInboundHandler: {}", this.getClass().getSimpleName());
logger.info("msg: {}", msg);
ctx.fireChannelRead(msg);
}
}
public static class HandMessageHandler extends ChannelInboundHandlerAdapter {
private InternalLogger logger = InternalLoggerFactory.getInstance(CreateMessageHandler.class);
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
logger.info("ChannelInboundHandler: {}", this.getClass().getSimpleName());
ctx.fireChannelRead(msg);
}
}
}
三、运行结果:
EmbeddedChannel.png