±à¼ÍƼö: |
±¾ÎÄÀ´×ÔÓÚjdon£¬±¾ÎÄÖ÷Òª½éÉÜÁËNettyÊÇʲô£¬Ê¹ÓÃNetty½¨Á¢Ò»¸ö·þÎñÆ÷µÄ´úÂëÑÝʾµÈÄÚÈÝ
£¬Ï£Íû¶ÔÄúÄÜÓÐËù°ïÖú¡£ |
|
NettyÊÇÒ»¸ö¸ßÐÔÄÜ Ê¼þÇý¶¯µÄÒì²½µÄ·Ç¶ÂÈûµÄIO(NIO)¿ò¼Ü£¬ÓÃÓÚ½¨Á¢TCPµÈµ×²ãµÄÁ¬½Ó£¬»ùÓÚNetty¿ÉÒÔ½¨Á¢¸ßÐÔÄܵÄHttp·þÎñÆ÷¡£Ö§³ÖHTTP¡¢
WebSocket ¡¢Protobuf¡¢ Binary TCP |ºÍUDP£¬NettyÒѾ±»ºÜ¶à¸ßÐÔÄÜÏîÄ¿×÷ΪÆäSocketµ×²ã»ù´¡£¬ÈçHornetQ
Infinispan Vert.x
Play Framework FinangleºÍ Cassandra¡£Æä¾ºÕù¶ÔÊÖÊÇ£ºApache MINAºÍ
Grizzly¡£
´«Í³¶ÂÈûµÄIO¶ÁÈ¡ÈçÏ£º
InputStream
is = new FileInputStream("input.bin");
int byte = is.read(); // µ±Ç°Ï̵߳ȴý½á¹ûµ½´ïÖ±ÖÁ´íÎó |
¶øÊ¹ÓÃNIOÈçÏ£º
while (true)
{
¡¡selector.select(); // ´Ó¶à¸öͨµÀÇëÇóʼþ
¡¡Iterator it = selector.selectedKeys().iterator();
¡¡while (it.hasNext()) {
¡¡¡¡SelectorKey key = (SelectionKey) it.next();
¡¡¡¡handleKey(key);
¡¡¡¡it.remove();
¡¡}
£ý |
¶ÂÈûÓë·Ç¶ÂÈûÔÀí
´«Í³Ó²¼þµÄ¶ÂÈûÈçÏ£¬´ÓÄÚ´æÖжÁÈ¡Êý¾Ý£¬È»ºóдµ½´ÅÅÌ£¬¶øCPUÒ»Ö±µÈµ½´ÅÅÌдÍê³É£¬´ÅÅ̵Äд²Ù×÷ÊÇÂýµÄ£¬Õâ¶Îʱ¼äCPU±»¶ÂÈû²»ÄÜ·¢»ÓЧÂÊ¡£

ʹÓ÷ǶÂÈûµÄDMAÈçÏÂͼ£ºCPUÖ»ÊÇ·¢³öд²Ù×÷ÕâÑùµÄÖ¸Á×öһЩ³õʼ»¯¹¤×÷£¬DMA¾ßÌåÖ´ÐУ¬´ÓÄÚ´æÖжÁÈ¡Êý¾Ý£¬È»ºóдµ½´ÅÅÌ£¬µ±Íê³Éдºó·¢³öÒ»¸öÖжÏʼþ¸øCPU¡£Õâ¶Îʱ¼äCPUÊÇ¿ÕÏеģ¬¿ÉÒÔ×ö±ðµÄÊÂÇé¡£Õâ¸öÔÀí³ÆÎªZero.copyÁ㿽±´¡£

Nettyµ×²ã»ùÓÚÉÏÊöJava NIOµÄÁ㿽±´ÔÀíʵÏÖ£º

±È½Ï
TomcatÊÇÒ»¸öWeb·þÎñÆ÷£¬ËüÊDzÉȡһ¸öÇëÇóÒ»¸öỊ̈߳¬µ±ÓÐ1000¿Í»§¶Ëʱ£¬»áºÄ·ÑºÜ¶àÄڴ档ͨ³£Ò»¸öÏ߳̽«»¨·Ñ
256kbµ½1mbµÄstack¿Õ¼ä¡£
Node.jsÊÇÒ»¸öÏ̷߳þÎñÓÚËùÓÐÇëÇó£¬ÔÚ´íÎó´¦ÀíÉÏÓÐÏÞÖÆ
NettyÊÇÒ»¸öÏ̷߳þÎñÓںܶàÇëÇó£¬ÈçÏÂͼ£¬µ±´ÓJava NIO»ñµÃÒ»¸öSelectorʼþ£¬½«¼¤»îͨµÀChannel¡£

ÑÝʾ
NettyµÄʹÓôúÂëÈçÏ£º
Channel channel
= ...
ChannelFuture cf = channel.write(data);
cf.addListener(
¡¡¡¡new ChannelFutureListener() {
¡¡¡¡¡¡@Override
¡¡¡¡¡¡public void operationComplete(ChannelFuture
future)¡¡throws Exception {
¡¡¡¡¡¡¡¡¡¡if(!future.isSuccess() {
¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡future.cause().printStacktrace();
¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡...
¡¡¡¡¡¡¡¡¡¡}
¡¡¡¡¡¡¡¡¡¡...
¡¡¡¡¡¡}
});
...
cf.sync(); |
ͨ¹ýÒýÈë¹Û²ìÕß¼àÌý£¬µ±ÓÐÊý¾Ýʱ£¬½«×Ô¶¯¼¤»î¼àÌýÕßÖеĴúÂëÔËÐС£
ÎÒÃÇʹÓÃNetty½¨Á¢Ò»¸ö·þÎñÆ÷´úÂ룺
public class
EchoServer {
private final int port;
public EchoServer(int port) {
this.port = port;
}
public void run() throws Exception {
// Configure the server.
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup).channel (NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 100)
.handler(new LoggingHandler(LogLevel.INFO)).childHandler(new
ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws
Exception {
ch.pipeline().addLast(
// new LoggingHandler(LogLevel.INFO),
new EchoServerHandler());
}
});
// Start the server.
ChannelFuture f = b.bind(port).sync();
// Wait until the server socket is closed.
f.channel().closeFuture().sync();
} finally {
// Shut down all event loops to terminate all
threads.
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
} |
Õâ¶Î´úÂëµ÷ÓãºÔÚ9999¶Ë¿ÚÆô¶¯
new EchoServer(9999).run(); |
ÎÒÃÇÐèÒªÍê³ÉµÄ´úÂëÊÇEchoServerHandler£º
public class
EchoServerHandler extends ChannelInboundHandlerAdapter
{
private static final Logger logger = Logger.getLogger(EchoServerHandler.class.getName());
@Override
public void channelRead(ChannelHandlerContext
ctx, Object msg) throws Exception {
ctx.write(msg);
}
@Override
public void channelReadComplete(ChannelHandlerContext
ctx) throws Exception {
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext
ctx, Throwable cause) {
// Close the connection when an exception is
raised.
logger.log(Level.WARNING, "Unexpected exception
from downstream.", cause);
ctx.close();
}
} |
ÔÀí
Ò»¸öNetty·þÎñÆ÷µÄÔÀíÈçÏ£º

ͼÖÐÿ´ÎÇëÇóµÄ¶ÁÈ¡ÊÇͨ¹ýUpStreamÀ´ÊµÏÖ£¬È»ºó¼¤»îÎÒÃǵķþÎñÂß¼ÈçEchoServerHandler£¬¶ø·þÎñÆ÷ÏòÍâдÊý¾Ý£¬Ò²¾ÍÊÇÏìÓ¦ÊÇͨ¹ýDownStreamʵÏֵġ£Ã¿¸öͨµÀChannel°üº¬Ò»¶ÔUpStreamºÍDownStream£¬ÒÔ¼°ÎÒÃǵÄhandlers£¨EchoServerHandler£©£¬ÈçÏÂͼ£¬ÕâЩ¶¼ÊÇͨ¹ýchannel
pipeline·â×°ÆðÀ´µÄ£¬Êý¾ÝÁ÷ÔڹܵÀÀïÁ÷¶¯£¬Ã¿¸öSocket¶ÔÓ¦Ò»¸öChannelPipeline¡£

CHANNELPIPELINEÊǹؼü£¬ËüÀàËÆUnixµÄ¹ÜµÀ£¬ÓÐÒÔÏÂ×÷Óãº
Ϊÿ¸öChannel ±£Áô ChannelHandlers £¬ÈçEchoServerHandler
ËùÓеÄʼþ¶¼ÒªÍ¨¹ýËü
²»¶ÏµØÐ޸ģºÀàËÆunixµÄSH¹ÜµÀ£º echo "Netty is shit...."
| sed -e 's/is /is the /'
Ò»¸öChannel¶ÔÓ¦Ò»¸ö ChannelPipeline
°üº¬ÐÒé±àÂë½âÂë °²È«ÑéÖ¤SSL/TLSºÍÓ¦ÓÃÂß¼
¿Í»§¶Ë´úÂë
Ç°ÃæÎÒÃÇÑÝʾÁË·þÎñÆ÷¶Ë´úÂ룬ÏÂÃæÊǿͻ§¶Ë´úÂ룺
public class
EchoClient {
private final String host;
private final int port;
private final int firstMessageSize;
public EchoClient(String host, int port, int
firstMessageSize) {
this.host = host;
this.port = port;
this.firstMessageSize = firstMessageSize;
}
public void run() throws Exception {
// Configure the client.
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true).handler(new
ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws
Exception {
ch.pipeline().addLast(
// new LoggingHandler(LogLevel.INFO),
new EchoClientHandler(firstMessageSize));
}
});
// Start the client.
ChannelFuture f = b.connect(host, port).sync();
// Wait until the connection is closed.
f.channel().closeFuture().sync();
} finally {
// Shut down the event loop to terminate all
threads.
group.shutdownGracefully();
}
}
} |
¿Í»§¶ËµÄÓ¦ÓÃÂß¼EchoClientHandler£º
public class
EchoClientHandler extends ChannelInboundHandlerAdapter
{
private static final Logger logger = Logger.getLogger(EchoClientHandler.class.getName());
private final ByteBuf firstMessage; /**
* Creates a client-side handler.
*/
public EchoClientHandler(int firstMessageSize)
{
if (firstMessageSize <= 0) {
throw new IllegalArgumentException("firstMessageSize:
" + firstMessageSize);
}
firstMessage = Unpooled.buffer(firstMessageSize);
for (int i = 0; i < firstMessage.capacity();
i++) {
firstMessage.writeByte((byte) i);
}
} @Override
public void channelActive(ChannelHandlerContext
ctx) {
ctx.writeAndFlush(firstMessage);
System.out.print("active");
} @Override
public void channelRead(ChannelHandlerContext
ctx, Object msg) throws Exception {
ctx.write(msg);
System.out.print("read");
} @Override
public void channelReadComplete(ChannelHandlerContext
ctx) throws Exception {
ctx.flush();
System.out.print("readok");
} @Override
public void exceptionCaught(ChannelHandlerContext
ctx, Throwable cause) {
// Close the connection when an exception is
raised.
logger.log(Level.WARNING, "Unexpected exception
from downstream.", cause);
ctx.close();
}
} |
|