Äú¿ÉÒÔ¾èÖú£¬Ö§³ÖÎÒÃǵĹ«ÒæÊÂÒµ¡£

1Ôª 10Ôª 50Ôª





ÈÏÖ¤Â룺  ÑéÖ¤Âë,¿´²»Çå³þ?Çëµã»÷Ë¢ÐÂÑéÖ¤Âë ±ØÌî



  ÇóÖª ÎÄÕ ÎÄ¿â Lib ÊÓÆµ iPerson ¿Î³Ì ÈÏÖ¤ ×Éѯ ¹¤¾ß ½²×ù Model Center   Code  
»áÔ±   
   
 
     
   
 ¶©ÔÄ
  ¾èÖú
NettyÔ­ÀíºÍʹÓÃ
 
  3226  次浏览      27
 2019-9-17
 
±à¼­ÍƼö:
±¾ÎÄÀ´×ÔÓÚ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();
}

}

 
   
3226 ´Îä¯ÀÀ       27
Ïà¹ØÎÄÕÂ

Java΢·þÎñÐÂÉú´úÖ®Nacos
ÉîÈëÀí½âJavaÖеÄÈÝÆ÷
JavaÈÝÆ÷Ïê½â
Java´úÂëÖÊÁ¿¼ì²é¹¤¾ß¼°Ê¹Óð¸Àý
Ïà¹ØÎĵµ

JavaÐÔÄÜÓÅ»¯
Spring¿ò¼Ü
SSM¿ò¼Ü¼òµ¥¼òÉÜ
´ÓÁ㿪ʼѧjava±à³Ì¾­µä
Ïà¹Ø¿Î³Ì

¸ßÐÔÄÜJava±à³ÌÓëϵͳÐÔÄÜÓÅ»¯
JavaEE¼Ü¹¹¡¢ Éè¼ÆÄ£Ê½¼°ÐÔÄܵ÷ÓÅ
Java±à³Ì»ù´¡µ½Ó¦Óÿª·¢
JAVAÐéÄâ»úÔ­ÀíÆÊÎö