Netty4.x
asynchronous event-driven network application framework
김대성
http://gmind7.github.io
Java Software Developer
Contents
✔ 네티란?
✔ 이벤트모델
✔ 스레드모델
✔ 개발구성요소
✔ 개발구현
✔ 개발테스트
네티란?
✔ 간략소개
✔ 구성요소
✔ 핵심컴포넌트
- 이벤트루프
- 파이프라인
✔ 자바 네트워크 어플리케이션 프레임워크
✔ 비동기 이면서 이벤트 기반
• tomcat < 10,000 (connection) VS netty < 100,000 ~ 1,000,000 (connection)
✔ I/O 처리를 위한 추상화 API 제공
• NIO, OIO, AIO… 처리에 대해 쉽게 쉽게 바꿀 수 있게 Netty I/O API 단에서 제공
✔ 잘 정의된 이벤트 모델과 스레드 모델 제공
• 접속을 맺고, 데이터를 보내고 받고, 접속을 끊을 때 어떤 이벤트가 발생할지 Netty가 잘 정의하여 제공
• 사용자의 코드가 어느 스레드에서 언제 실행 될 지, 불필요한 동기화 방지..등등 Netty가 잘 정의하여 제공
✔ 유연한 이벤트 처리 위한 bi-directional chain of responsibility pattern
✔ 직접 구현한 버퍼풀을 이용한 성능 이점 제공
• Buffer Zero-file-copy, Buffer Automatic Capacity Extession…
네티란?
✔ 구성요소
- I/O 레이어 (Netty), 프로토콜 코덱 (Netty or User), 비지니스로직 (User)
Buffers
I/O Abstraction – Channels, Event Loops, and Pilelines
TCP UDP In-VM
Event Handlers
Codec Framework
HTTP
Custom EventHandlers & Codecs
Business Logic
Handler
Core
Transports
SSL SPDY
User Code
네티란?
✔ 핵심컴포넌트(eventloop, pipeline)
•eventloop (Windows event dispatcher, Swing event loop, Reactor)
Is Eventloop ?
(single thread)
tasks
User I/O
taskYES
NO
task
Queue
(Scheduling)
Execute
(pipeline call)
네티란?
✔ 핵심컴포넌트(eventloop, pipeline)
•pipeline (이벤트루프에서 이벤트를 받아 핸들러에 전달하는 역할)
eventloop 2
protocol
decoder
protocol
encoder
business
logic
3 4
⇐ 수신 : 1 > 2 > 4
⇒ 송신 : 4 > 3 > 1
1
pipeline
(bi-directional chain of responsibility pattern)
* inbound event
- 이벤트 루프가 발생 시킨 이벤트 (소켓연결, 데이터수신 등)를 작성한 inbound event handler에게 전달
* outbound event
- 사용자가 요청한 동작 (쓰기, 읽기 일시중단 등)을 작성한 outbound event handler에게 전달
- 최종적으로 이벤트 루프에 전달되어 I/O가 수행되도록 함.
네티란?
✔ 핵심플로우
네티란?
eventloop
1 2
pipeline context
3 4
handler
1 1 1 n 1 n
이벤트
모델
✔ 기존 이벤트 모델
✔ 새 이벤트 모델
✔ 기존 이벤트 모델 (객체호출)
이벤트모델
✔ 새 이벤트 모델 (메서드호출)
Channel DisConnectedChannel UnboundChannel Closed
Message Event(in,out)
Channel ConnectedChannel boundChannel Open
Flush (Messag Event대체)Channel InActiveChannel Unregistered
InboundBufferUpdatedChannel ActiveChannel Registered
버퍼에 데이터를 다 채운 후
Flush 요청시 실제 I/O수행
통신가능상태
통신불가상태
* UserEventTriggered 메서드 추가
스레드모델
✔ 이벤트 루프는 항상 싱글 스레드로 실행 되어짐
✔ 비동기 요청에 대한 결과 통보는 이벤트 루프 스레드에서 이루어짐
✔ 핸들러 메소드를 호출할 때 각 호출 사이에는 happens-before 관계 성립
✔ @Sharable 가 붙어 있지 않은 경우 핸들러 메서드를 동시 호출 하지 않음
스레드모델
eventloop
(single thread) pipeline handler
method
method
happens-before
volatile (필요없음)
ChannelFuture<T> handler 동시 호출(X)
개발
구성요소
✔ 핵심컴포넌트
✔ 클래스다이어그램
✔ API 패키지 구성
✔ 바이트버프
✔ Bootstrap
• Bootstrap : Client-side Channel를 생성 해 주고 새로운 연결을 시도 하는 Helper Class
• ServerBootstrap : Server-side Channel를 생성 해 주고 새로운 연결을 시도 하는 Helper Class
부모채널은 연결을 받아주고, 성공적으로 bound 되어진 client연결은 자식채널임
✔ EventLoop
•EventLoop : SingleThread Channel Seletor (OioEventLoop, Nio…, Epoll..)
•EventLoopGroup : MultiThread Channel Seletor (OioEvnetLoopGroup, Nio…, Epoll…)
✔ Channel
•NioSocketChannel, OioSocketChannel, EpollSocketChannel
NioServerSocketChannel, OioServerSocketChannel, EpollServerSocketChannel
✔ ChannelOption
•SO_KEEPALIVE, SO_SNDBUF, SO_RCVBUF, SO_TIMEOUT, SO_BACKLOG….
✔ ChannelFuture
• Channel I/O Operations이 완료 되었을 때 결과를 받을 수 있는 Future 객체
개발구성요소 (핵심컴포넌트)
✔ ChannelHandler
• …InboundHandler, …OutBoundHandler 지원
• Channel I/O Operations의 Event 처리를 위한 Handler Method를 지원
✔ ByteBuf (dynamic buffer)
• UnPooledDirectByteBuf, UnPooledHeapByteBuf, UnPooledUnsafeDirectByteBuf,
PooledDirectByteBuf, PooledHeapByteBuf, PooledUnsafeDirectByteBuf,
CompositeByteBuf….
개발구성요소 (핵심컴포넌트)
✔ EventLoop And EventExecutor
개발구성요소 (클래스다이어그램)
✔ NIO,OIO Channel
개발구성요소 (클래스다이어그램)
✔ Bytebuf
개발구성요소 (클래스다이어그램)
개발구성요소 (API 패키지구조)
개발구현
✔ ChannelHandler (event, codec)
✔ Client Run (bootstrap)
✔ Server Run (ServerBootstrap)
✔ Bytebuf
✔ ChannelHandler (event)
Flush
Channel InActive
Channel Unregistered
InboundBufferUpdated
Channel Active
Channel Registered
개발구현
✔ ChannelHandler (decoder, encoder)
개발구현
✔ Client Run
개발구현
✔ Sever Run
개발구현
✔ Bytebuf
개발구현
✔ Bytebuf
개발구현
테스트 ✔ EmbeddedChannel
✔ EmbeddedChannel
개발테스트
Reference Site
✔ http://deview.kr/2012/xe/index.php?mid=track&document_srl=379&time_srl=276
✔ http://normanmaurer.me/presentations/2014-facebook-eng-netty/slides.html
✔ http://www.youtube.com/watch?v=_GRIyCMNGGI
✔ http://hongweiyi.com/2014/01/

Netty4.x

  • 1.
    Netty4.x asynchronous event-driven networkapplication framework 김대성 http://gmind7.github.io Java Software Developer
  • 2.
    Contents ✔ 네티란? ✔ 이벤트모델 ✔스레드모델 ✔ 개발구성요소 ✔ 개발구현 ✔ 개발테스트
  • 3.
    네티란? ✔ 간략소개 ✔ 구성요소 ✔핵심컴포넌트 - 이벤트루프 - 파이프라인
  • 4.
    ✔ 자바 네트워크어플리케이션 프레임워크 ✔ 비동기 이면서 이벤트 기반 • tomcat < 10,000 (connection) VS netty < 100,000 ~ 1,000,000 (connection) ✔ I/O 처리를 위한 추상화 API 제공 • NIO, OIO, AIO… 처리에 대해 쉽게 쉽게 바꿀 수 있게 Netty I/O API 단에서 제공 ✔ 잘 정의된 이벤트 모델과 스레드 모델 제공 • 접속을 맺고, 데이터를 보내고 받고, 접속을 끊을 때 어떤 이벤트가 발생할지 Netty가 잘 정의하여 제공 • 사용자의 코드가 어느 스레드에서 언제 실행 될 지, 불필요한 동기화 방지..등등 Netty가 잘 정의하여 제공 ✔ 유연한 이벤트 처리 위한 bi-directional chain of responsibility pattern ✔ 직접 구현한 버퍼풀을 이용한 성능 이점 제공 • Buffer Zero-file-copy, Buffer Automatic Capacity Extession… 네티란?
  • 5.
    ✔ 구성요소 - I/O레이어 (Netty), 프로토콜 코덱 (Netty or User), 비지니스로직 (User) Buffers I/O Abstraction – Channels, Event Loops, and Pilelines TCP UDP In-VM Event Handlers Codec Framework HTTP Custom EventHandlers & Codecs Business Logic Handler Core Transports SSL SPDY User Code 네티란?
  • 6.
    ✔ 핵심컴포넌트(eventloop, pipeline) •eventloop(Windows event dispatcher, Swing event loop, Reactor) Is Eventloop ? (single thread) tasks User I/O taskYES NO task Queue (Scheduling) Execute (pipeline call) 네티란?
  • 7.
    ✔ 핵심컴포넌트(eventloop, pipeline) •pipeline(이벤트루프에서 이벤트를 받아 핸들러에 전달하는 역할) eventloop 2 protocol decoder protocol encoder business logic 3 4 ⇐ 수신 : 1 > 2 > 4 ⇒ 송신 : 4 > 3 > 1 1 pipeline (bi-directional chain of responsibility pattern) * inbound event - 이벤트 루프가 발생 시킨 이벤트 (소켓연결, 데이터수신 등)를 작성한 inbound event handler에게 전달 * outbound event - 사용자가 요청한 동작 (쓰기, 읽기 일시중단 등)을 작성한 outbound event handler에게 전달 - 최종적으로 이벤트 루프에 전달되어 I/O가 수행되도록 함. 네티란?
  • 8.
  • 9.
    이벤트 모델 ✔ 기존 이벤트모델 ✔ 새 이벤트 모델
  • 10.
    ✔ 기존 이벤트모델 (객체호출) 이벤트모델 ✔ 새 이벤트 모델 (메서드호출) Channel DisConnectedChannel UnboundChannel Closed Message Event(in,out) Channel ConnectedChannel boundChannel Open Flush (Messag Event대체)Channel InActiveChannel Unregistered InboundBufferUpdatedChannel ActiveChannel Registered 버퍼에 데이터를 다 채운 후 Flush 요청시 실제 I/O수행 통신가능상태 통신불가상태 * UserEventTriggered 메서드 추가
  • 11.
  • 12.
    ✔ 이벤트 루프는항상 싱글 스레드로 실행 되어짐 ✔ 비동기 요청에 대한 결과 통보는 이벤트 루프 스레드에서 이루어짐 ✔ 핸들러 메소드를 호출할 때 각 호출 사이에는 happens-before 관계 성립 ✔ @Sharable 가 붙어 있지 않은 경우 핸들러 메서드를 동시 호출 하지 않음 스레드모델 eventloop (single thread) pipeline handler method method happens-before volatile (필요없음) ChannelFuture<T> handler 동시 호출(X)
  • 13.
  • 14.
    ✔ Bootstrap • Bootstrap: Client-side Channel를 생성 해 주고 새로운 연결을 시도 하는 Helper Class • ServerBootstrap : Server-side Channel를 생성 해 주고 새로운 연결을 시도 하는 Helper Class 부모채널은 연결을 받아주고, 성공적으로 bound 되어진 client연결은 자식채널임 ✔ EventLoop •EventLoop : SingleThread Channel Seletor (OioEventLoop, Nio…, Epoll..) •EventLoopGroup : MultiThread Channel Seletor (OioEvnetLoopGroup, Nio…, Epoll…) ✔ Channel •NioSocketChannel, OioSocketChannel, EpollSocketChannel NioServerSocketChannel, OioServerSocketChannel, EpollServerSocketChannel ✔ ChannelOption •SO_KEEPALIVE, SO_SNDBUF, SO_RCVBUF, SO_TIMEOUT, SO_BACKLOG…. ✔ ChannelFuture • Channel I/O Operations이 완료 되었을 때 결과를 받을 수 있는 Future 객체 개발구성요소 (핵심컴포넌트)
  • 15.
    ✔ ChannelHandler • …InboundHandler,…OutBoundHandler 지원 • Channel I/O Operations의 Event 처리를 위한 Handler Method를 지원 ✔ ByteBuf (dynamic buffer) • UnPooledDirectByteBuf, UnPooledHeapByteBuf, UnPooledUnsafeDirectByteBuf, PooledDirectByteBuf, PooledHeapByteBuf, PooledUnsafeDirectByteBuf, CompositeByteBuf…. 개발구성요소 (핵심컴포넌트)
  • 16.
    ✔ EventLoop AndEventExecutor 개발구성요소 (클래스다이어그램)
  • 17.
    ✔ NIO,OIO Channel 개발구성요소(클래스다이어그램)
  • 18.
  • 19.
  • 20.
    개발구현 ✔ ChannelHandler (event,codec) ✔ Client Run (bootstrap) ✔ Server Run (ServerBootstrap) ✔ Bytebuf
  • 21.
    ✔ ChannelHandler (event) Flush ChannelInActive Channel Unregistered InboundBufferUpdated Channel Active Channel Registered 개발구현
  • 22.
    ✔ ChannelHandler (decoder,encoder) 개발구현
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
    Reference Site ✔ http://deview.kr/2012/xe/index.php?mid=track&document_srl=379&time_srl=276 ✔http://normanmaurer.me/presentations/2014-facebook-eng-netty/slides.html ✔ http://www.youtube.com/watch?v=_GRIyCMNGGI ✔ http://hongweiyi.com/2014/01/