Netty in Action筆記(Chpater1 ~ 2) First Netty application

【Chapter 1 Netty and Java NIO APIs】
The entire Netty API is asynchronous.安全

Asynchronous processing encourages you to use your resources more efficiently by allowing you to start a task and get notified when it's done rather than waiting for it to complete. You're free to do something else while the task is running.app

實現異步的兩種方法:異步

  1. 回調(實現接口的方法,即監聽器)
  2. Future(A Future object either holds the result of a computation or, in the case of a failed computation, an exception.)。能夠取消、檢查是否完成,阻塞直到完成

On Linux-like OSs the selector makes use of the epoll- IO event notification facility. This is a high-performance technique in which the OS works asynchronously with the networking stack.Unfortunately, even today the famous epoll- bug can lead to an invalid state in the
selector, resulting in 100% CPU-usage and spinning.async

【Chapter 2 Your first Netty application】ide

Handler能夠被多個Channel共享,這時Handler必須被@Sharable註解且必須是線程安全的this

ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)        //writeAndFlush是異步操做,返回ChannelFuture
    .addListener(ChannelFutureListener.CLOSE);  //經過ChannelFuture.addListener()註冊監聽器,當Future.isDone()等於true時會執行監聽器

對於一個Channel,其pipeline中至少要有一個Handler可以處理異常線程

Next, override the channelRead0() method. The method is called once data is received.Note that the bytes may be fragmented, which means that if the server writes 5 bytes it s not guaranteed that all 5 bytes will be received at once. For 5 bytes, the channelRead0() method could be called twice, for example. The first time it may be called with a ByteBuf that holds 3 bytes and the second time with a ByteBuf that holds 2 bytes. The only guarantee is that the bytes will be received in the same order as they re sent. But this is only true for TCP or other stream-orientated protocols.code

SimpleChannelInboundHandler與ChannelInboundHandlerAdapter的區別:orm

  • ChannelInboundHandlerAdapter的channelRead(ctx,
    msg)須要釋放msg,若是msg是ByteBuf類型,則須要調用ByteBuf.release()方法(由於Netty默認使用支持池的Buf,不release的會發生內存泄露,即這個BUf在JVM退出以前永遠不會被GC回收);
  • 而SimpleChannelInboundHandler呢,it will release the message once the
    channelRead0(...) method completes. This is done by Netty to handle
    all messages that are implement ReferenceCounted.
  • But why not do the same in the EchoServerHandler? The reason for this is that we want to echo back the message, which means we can not release it yet as the write operation may completes after channelRead(...) returns (remember write is asynchronous). Once the write completes Netty will automatically release the message.
相關文章
相關標籤/搜索