SlideShare a Scribd company logo
Netty
from the trenches
June 2015
@jordi9
Netty…?
Netty is an
asynchronous
event-driven
network
application
framework
for rapid
development of
maintainable high
performance
protocol servers &
clients.
Netty from the trenches
Netty is a NIO
client server
framework which
enables quick and
easy development
of network
applications such
as protocol servers
and clients. It
greatly simplifies
and streamlines
network
network
programming such
as TCP and UDP
socket server.
OH, MY
The Freaking
Basics
You’ve heard of:
Async apps
You’ve heard of:
Event driven
frameworks
You’ve heard of:
non-blocking
operations
You’ve heard of:
Node is
cooler
because...
I/O
I/O is
everywhere
I/O, approx:
CPU
Memory
Device
read()
read()
//wait...
read()
//wait...
keepWorkingBro()
Our program
BLOCKS
Resources
WASTED
You know what
I’m talking
about
Webserver
Request
Database
//wait...
OH,
Parallelism!
new Thread();
Webserver
Request
Database
//wait...
Webserver
Request
Database
//wait...
Request
Database
//wait...
Webserver
Request
Database
//wait...
Request
Database
//wait...
Request
Database
//wait.
A mess
We can
do better
read()
read()
keepWorkingBro()
read()
keepWorkingBro()
//I’m
//done!
You (kinda) did this:
Listeners
You (kinda) did this:
Guava’s
EventBus
You (kinda) did this:
Javascript
callbacks
Hollywood principle
“Don’t call us,
we’ll call you”
Keep working,
instead of
waiting
Hi,
Async I/O
NIO
with Java
java.nio
since 1.4, 2002
java.nio
since 1.7: NIO2
more goodies
Hi,
Complexity
Netty
to the Rescue
Built on top of:
java.nio
Built on top of:
java.net
Dependecy-haters:
Just
JDK 1.6+
ONE
big difference
All Netty APIs
are async
It’s can be one
more tool!
What the hell
is Netty for?
Think...
HTTP
everywhere
Really
BRO?
Maybe, you’re
trying to
implement a
protocol
Finally, hello
Netty!
Netty:
Tool to
implement network
applications
Netty:
Both from server
and client side
Netty:
NIO
everywhere
Why
Netty?
Netty has been
designed carefully
with the
experiences
earned from the
implementation of
a lot of protocols
such as FTP,
SMTP, HTTP, and
various binary and
text-based legacy
protocols. As a
protocols. As a
result, Netty has
succeeded to find
a way to achieve...
Ease of
development
Performance
Stability
Flexibility
Without a
compromise
IT’S TRUE
“Implementing
a protocol”
NOT THAT HARD
Most common
protocols:
out-of-the-box
Boring Protocols:
HTTP
Boring Protocols:
SSL
Boring Protocols:
UDP
Cooler Protocols:
SPDY
Cooler Protocols:
HTTP/2
Cooler Protocols:
Protobuf
Even Protocols:
Memcache
Not only I/O
Powerful
Thread model
But, where’s
the downside?
Downers:
Constant API
changes*
Downers:
Constant API
changes*
*For the best
Downers:
Learning
curve...
Downers:
Learning
curve...
Buy Netty in Action :P
Downers:
Join the
mailing list
Downers:
Join the
mailing list
You’ll see how
STUPID you are
Downers:
Join the
mailing list
But you’ll learn ALOT ;)
Netty,
The Code
Daytime
Protocol
Netty from the trenches
The
Server
class SimpleDaytimeHandler extends
ChannelInboundHandlerAdapter {
}
The Hand e
class SimpleDaytimeHandler extends
ChannelInboundHandlerAdapter {
// Handler = Business Logic
}
The Hand e
class SimpleDaytimeHandler extends
ChannelInboundHandlerAdapter {
// ChannelHandler: handles operations
// for that Channel, duh
}
The Hand e
class SimpleDaytimeHandler extends
ChannelInboundHandlerAdapter {
// Inbound handler: incoming traffic,
// dispatch events to next handler
// If we have inbound...
}
The Hand e
class SimpleDaytimeHandler extends
ChannelInboundHandlerAdapter {
// Outbound handler: same, but the
// other direction. Yeah, there’s some
// flow between Handlers (eg: Pipeline)
}
The Hand e
class SimpleDaytimeHandler extends
ChannelInboundHandlerAdapter {
// Inbound + Outbound...
}
The Hand e
class SimpleDaytimeHandler extends
ChannelInboundHandlerAdapter {
// Inbound + Outbound..
// 5.0: DEPRECATED!
// [NOTE: Insert a grumpy cat here]
}
The Hand e
Hand e me hod
@Override
public void channelRead(
ChannelHandlerContext ctx, Object msg) {
// Will trigger when we receive
// some data
}
Hand e me hod
@Override
public void channelActive(
ChannelHandlerContext ctx, Object msg) {
// Will a Channel is opened, this
// method will be called
}
Hand e me hod
@Override
public void channelActive(ChannelHandlerContext ctx, Object msg) {
String date = DATE_TIME.print(new DateTime());
// Get the date
}
Hand e wo
@Override
public void channelActive(ChannelHandlerContext ctx, Object msg) {
String date = DATE_TIME.print(new DateTime());
ctx.writeAndFlush(ByteBufUtil.encodeString(
ctx.alloc(), CharBuffer.wrap(date),
CharsetUtil.US_ASCII));
}
Hand e wo
It’s clear,
right? :D
Network
standard way of
working?
byte[]
You said this
was fun?
Meet
ByteBuf
ByteBufUtil
@Override
public void channelActive(ChannelHandlerContext ctx, Object msg) {
String date = DATE_TIME.print(new DateTime());
ctx.writeAndFlush(ByteBufUtil.encodeString(
ctx.alloc(), CharBuffer.wrap(date),
CharsetUtil.US_ASCII));
// We need to encode the String
}
Hand e wo
@Override
public void channelActive(ChannelHandlerContext ctx, Object msg) {
String date = DATE_TIME.print(new DateTime());
ctx.writeAndFlush(ByteBufUtil.encodeString(
ctx.alloc(), CharBuffer.wrap(date),
CharsetUtil.US_ASCII));
// We allocate some space
// +Netty: Keeps internal pools
}
Hand e wo
@Override
public void channelActive(ChannelHandlerContext ctx, Object msg) {
String date = DATE_TIME.print(new DateTime());
ctx.writeAndFlush(ByteBufUtil.encodeString(
ctx.alloc(), CharBuffer.wrap(date),
CharsetUtil.US_ASCII));
// Write the message
// Request to actually flush the data
// back to the Channel
}
Hand e wo
We have our
Handler in place
Let’s Bootstrap
the server
Ma n ass
public class DaytimeServer {
void run() throws Exception {
// fun stuff
}
public static void main(String[] args) throws Exception {
DaytimeServer daytimeServer = new DaytimeServer();
daytimeServer.run();
}
}
java -jar daytimeserver-fat.jar
un()
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
E en LoopG oup
Netty’s way to
handle threads
E en LoopG oup
EventLoopGroup
contains some
EventLoops
E en Loop
EventLoop
handles many
Channels
About to die
BRO?
E en LoopG oup
E en Loop
hanne
hanne
hanne
hanne
hanne hanne
hanne
hanne
hanne
hanne
hanne hanne
E en Loop
E en LoopG oup
E en Loop
hanne
hanne
hanne
hanne
hanne hanne
hanne
hanne
hanne
hanne
hanne hanne
E en Loop
This immutable
assignment is
the key
un()
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
un()
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
// Boss group accepts connections
// Work group handles the work
Se e Boo s ap
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.localAddress(8080)
.option(ChannelOption.SO_BACKLOG, 100)
Se e Boo s ap
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.localAddress(8080)
.option(ChannelOption.SO_BACKLOG, 100)
// We assign both event loops
Se e Boo s ap
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.localAddress(8080)
.option(ChannelOption.SO_BACKLOG, 100)
// We use a ServerSocketChannel
// to accept TCP/IP connections
// as the RFC says
Se e Boo s ap
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.localAddress(8080)
.option(ChannelOption.SO_BACKLOG, 100)
// Simply bind the local address
Se e Boo s ap
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.localAddress(8080)
.option(ChannelOption.SO_BACKLOG, 100)
// Set some Socket options... why not?
// Just remember: This is not handled
// by Netty or the JVM, it’s the OS
We’re
almost there!
hanne P pe ne
b.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch)
throws Exception {
ChannelPipeline p = ch.pipeline();
p.addLast(new LoggingHandler(LogLevel.INFO));
p.addLast(new SimpleDaytimeHandler());
}
});
hanne P pe ne
b.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch)
throws Exception {
ChannelPipeline p = ch.pipeline();
p.addLast(new LoggingHandler(LogLevel.INFO));
p.addLast(new SimpleDaytimeHandler());
}
});
// ChannelPipeline to define your
// application workflow
hanne P pe ne
b.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch)
throws Exception {
ChannelPipeline p = ch.pipeline();
p.addLast(new LoggingHandler(LogLevel.INFO));
p.addLast(new SimpleDaytimeHandler());
}
});
// Append our handlers
// ProTip: use LoggingHandler to
// understand Netty
hanne P pe ne
b.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch)
throws Exception {
ChannelPipeline p = ch.pipeline();
p.addLast(new LoggingHandler(LogLevel.INFO));
p.addLast(new SimpleDaytimeHandler());
}
});
// Finally, we add our handler
RUN!
b.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch)
throws Exception {
ChannelPipeline p = ch.pipeline();
p.addLast(new LoggingHandler(LogLevel.INFO));
p.addLast(new SimpleDaytimeHandler());
}
});
ChannelFuture f = b.bind().sync();
f.channel().closeFuture().sync();
// It works!
.I.A.
Futures
ByteBuf API
Codecs
Transports
Zero-file-copy
We can also
create
client code
Real life
Insights
We’re using Netty for
Real-Time Bidding
Boo s ap
Tons o op ons
Don’t be afraid
of “low-level”
Ta HTTP
Explore what’s
inside Netty
Integrate things
you love. In my
case: GUICE
Gu e
@Inject
DaytimeService(Provider<DaytimeServer> daytimeProvider) {}
b.childHandler(() → {
ChannelPipeline p = ch.pipeline();
p.addLast(new LoggingHandler(LogLevel.INFO));
p.addLast(daytimeProvider.get());
});
// Inject a Provider<T> and get
// instances
But… is Netty
FAST?
2ms*
* Without network latency
2ms*
Yah but… what
volume are you
talking about?
+10k QPS
1 node*
+3k QPS
*Fou 2.79GHz In e Pen um Xeon P o esso s, 7.5GB RAM
But, is this
ALOT or not?
Parse example
http://blog.parse.com/learn/how-we-moved-our-api-from-ruby-to-go-and-saved-our-sanity/
(From Ruby to Go) A year and a
half in, at the end of 2012, we had
200 API servers running on m1.
xlarge instance types with 24
unicorn workers per instance. This
was to serve 3000 requests per
second for 60,000 mobile apps
We have 16 nodes!
4x Netty nodes
10x Kafka, DNS, the
usual suspects…
I KNOW IT’S
NOT FAIR,
but it’s good stuff
for your ego BRO
Lovely ecosystem
like Ratpack,
or users,
with vert.x or akka
It will change the
way you program
some of your apps
Hello, Async
problems
Forget about
max onn params
One more thing...
(It’s 5:00 in the
morning and I had
to say it)
(did you notice the
“Apple
background”?)
Netty from the trenches
Netty from the trenches
JUST KIDDING
It doesn’ really
matter!
Have fun!
THANKS
ProTip:
We’re hiring
Q & A
#HiddenTrovitTrac@jordi9

More Related Content

PDF
Reactive server with netty
ODP
Building Netty Servers
PDF
Asynchronous, Event-driven Network Application Development with Netty
PDF
Building scalable network applications with Netty (as presented on NLJUG JFal...
PDF
Netty: asynchronous data transfer
PPT
Netty 4-based RPC System Development
PDF
Netty @Apple: Large Scale Deployment/Connectivity
PPTX
Using RabbitMQ and Netty library to implement RPC protocol
Reactive server with netty
Building Netty Servers
Asynchronous, Event-driven Network Application Development with Netty
Building scalable network applications with Netty (as presented on NLJUG JFal...
Netty: asynchronous data transfer
Netty 4-based RPC System Development
Netty @Apple: Large Scale Deployment/Connectivity
Using RabbitMQ and Netty library to implement RPC protocol

What's hot (20)

PPTX
Notes on Netty baics
PDF
Monitoring with Prometheus
PDF
An Introduction to Twisted
PPTX
OWASP ZAP Workshop for QA Testers
PDF
GopherFest 2017 - Adding Context to NATS
PPTX
Commication Framework in OpenStack
PDF
Anatomy of neutron from the eagle eyes of troubelshoorters
PDF
From a cluster to the Cloud
PDF
Acus08 Advanced Load Balancing Apache2.2
ZIP
How we use Twisted in Launchpad
PDF
Monitoring infrastructure with prometheus
PDF
HTTP/2, HTTP/3 and SSL/TLS State of the Art in Our Servers
PDF
Apache ZooKeeper
PDF
iptables and Kubernetes
PPT
Easy Steps to implement UDP Server and Client Sockets
PDF
debugging openstack neutron /w openvswitch
PPTX
How to Troubleshoot OpenStack Without Losing Sleep
PDF
Debugging Network Issues
PPTX
Troubleshooting containerized triple o deployment
PDF
Docker and Fargate
Notes on Netty baics
Monitoring with Prometheus
An Introduction to Twisted
OWASP ZAP Workshop for QA Testers
GopherFest 2017 - Adding Context to NATS
Commication Framework in OpenStack
Anatomy of neutron from the eagle eyes of troubelshoorters
From a cluster to the Cloud
Acus08 Advanced Load Balancing Apache2.2
How we use Twisted in Launchpad
Monitoring infrastructure with prometheus
HTTP/2, HTTP/3 and SSL/TLS State of the Art in Our Servers
Apache ZooKeeper
iptables and Kubernetes
Easy Steps to implement UDP Server and Client Sockets
debugging openstack neutron /w openvswitch
How to Troubleshoot OpenStack Without Losing Sleep
Debugging Network Issues
Troubleshooting containerized triple o deployment
Docker and Fargate
Ad

Viewers also liked (20)

PPTX
Introduction of netty
KEY
Non blocking io with netty
PDF
Zero-Copy Event-Driven Servers with Netty
PDF
Netty - a pragmatic introduction
PDF
Real time analytics with Netty, Storm, Kafka
PPTX
Netty Notes Part 3 - Channel Pipeline and EventLoops
PDF
深入浅出Netty l.t
PDF
KEY
Nettyらへん
PPTX
Netty Notes Part 2 - Transports and Buffers
PDF
3 apache-avro
PDF
Create responsive websites with Django, REST and AngularJS
PPTX
55 New Features in JDK 9
PDF
Selección y reclutamiento 2.0 "Encuéntrate y te encontrarán"
PDF
OSARE in pratica
PPTX
Scale up - How to build adaptive data systems in the age of virality
PDF
Is 'Made in the USA' Back in Vogue?
PDF
Letter of Intent - Open Society Fellowship
PPT
Key metrics for Inside Sales Teams
PPTX
Gerontology & Geriatrics: Research
Introduction of netty
Non blocking io with netty
Zero-Copy Event-Driven Servers with Netty
Netty - a pragmatic introduction
Real time analytics with Netty, Storm, Kafka
Netty Notes Part 3 - Channel Pipeline and EventLoops
深入浅出Netty l.t
Nettyらへん
Netty Notes Part 2 - Transports and Buffers
3 apache-avro
Create responsive websites with Django, REST and AngularJS
55 New Features in JDK 9
Selección y reclutamiento 2.0 "Encuéntrate y te encontrarán"
OSARE in pratica
Scale up - How to build adaptive data systems in the age of virality
Is 'Made in the USA' Back in Vogue?
Letter of Intent - Open Society Fellowship
Key metrics for Inside Sales Teams
Gerontology & Geriatrics: Research
Ad

Similar to Netty from the trenches (20)

PDF
Building scalable network applications with Netty
PDF
PDF
Netty training
PDF
Netty In Action 1st Edition Norman Maurer Marvin Allen Wolfthal
PDF
Java Network Programming Third Edition 3rd Edition Elliotte Rusty Harold
PDF
Java Network Programming, 4th Edition.pdf
PDF
04 android
PDF
Java Network Programming Fourth Edition Elliotte Rusty Harold
PPT
java networking
PDF
MINA2 (Apache Netty)
PDF
EEEM048_Lecture5_Software platforms and services .pdf
PDF
Java Network Programming Fourth Edition Elliotte Rusty Harold
PPTX
FlowER Erlang Openflow Controller
PDF
Java Network Programming Fourth Edition Harold Elliotte
PPT
Socket Programming - nitish nagar
PDF
28 networking
PDF
NIO MULTIPLEXER.pdf
PDF
JJUG CCC 2018 Spring - I-7 (俺が)はじめての Netty
PDF
第2回クラウドネットワーク研究会 「OpenFlowコントローラとその実装」
PDF
10 fn s03
Building scalable network applications with Netty
Netty training
Netty In Action 1st Edition Norman Maurer Marvin Allen Wolfthal
Java Network Programming Third Edition 3rd Edition Elliotte Rusty Harold
Java Network Programming, 4th Edition.pdf
04 android
Java Network Programming Fourth Edition Elliotte Rusty Harold
java networking
MINA2 (Apache Netty)
EEEM048_Lecture5_Software platforms and services .pdf
Java Network Programming Fourth Edition Elliotte Rusty Harold
FlowER Erlang Openflow Controller
Java Network Programming Fourth Edition Harold Elliotte
Socket Programming - nitish nagar
28 networking
NIO MULTIPLEXER.pdf
JJUG CCC 2018 Spring - I-7 (俺が)はじめての Netty
第2回クラウドネットワーク研究会 「OpenFlowコントローラとその実装」
10 fn s03

More from Jordi Gerona (7)

PDF
Google Guava - Core libraries for Java & Android
PDF
Clean code via dependency injection + guice
PPT
Unit Testing - Trovit
PPTX
Mitos y otras criaturas startuperas (webbar)
PPT
Mercurial
PPT
Unit Testing - GTUG
PPT
Dependency Injection con Guice - GTUG
Google Guava - Core libraries for Java & Android
Clean code via dependency injection + guice
Unit Testing - Trovit
Mitos y otras criaturas startuperas (webbar)
Mercurial
Unit Testing - GTUG
Dependency Injection con Guice - GTUG

Recently uploaded (20)

PDF
Electronic commerce courselecture one. Pdf
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Machine learning based COVID-19 study performance prediction
DOCX
The AUB Centre for AI in Media Proposal.docx
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
Big Data Technologies - Introduction.pptx
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
KodekX | Application Modernization Development
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
sap open course for s4hana steps from ECC to s4
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PPTX
Spectroscopy.pptx food analysis technology
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Empathic Computing: Creating Shared Understanding
Electronic commerce courselecture one. Pdf
Chapter 3 Spatial Domain Image Processing.pdf
Machine learning based COVID-19 study performance prediction
The AUB Centre for AI in Media Proposal.docx
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Building Integrated photovoltaic BIPV_UPV.pdf
Big Data Technologies - Introduction.pptx
Per capita expenditure prediction using model stacking based on satellite ima...
KodekX | Application Modernization Development
“AI and Expert System Decision Support & Business Intelligence Systems”
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Agricultural_Statistics_at_a_Glance_2022_0.pdf
sap open course for s4hana steps from ECC to s4
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
NewMind AI Weekly Chronicles - August'25 Week I
Spectroscopy.pptx food analysis technology
Diabetes mellitus diagnosis method based random forest with bat algorithm
Advanced methodologies resolving dimensionality complications for autism neur...
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Empathic Computing: Creating Shared Understanding

Netty from the trenches

Editor's Notes

  • #5: NS: Ok, maybe with an image things are easier
  • #6: Ok, kinda… make sense. Keep reading
  • #10: I was looking for a fast webserver?! more hype words please I think I’m gonna pass, forget it never happened -- Almost happened to me 3 years ago
  • #15: They’re all the same...
  • #16: low-level, input and output (I/O) operations
  • #17: Just to name a few: reading data from a disk drive, a remote procedure call (RPC), send a file over a network, etc. In general terms, any communication between CPU + memory and any other device is considered I/O.
  • #21: The same goes with write() operations
  • #22: We can say that our program blocks while the communication is in progress. This type of I/O is known as blocking I/O or synchronous I/O. NS: What’s the problem?
  • #23: The big problem with blocking I/O is that while you’re waiting, you will leave most of your system resources idle. Meaning that your processor will mostly do nothing but to wait that the I/O operations are finished.
  • #24: The big problem with blocking I/O is that while you’re waiting, you will leave most of your system resources idle. Meaning that your processor will mostly do nothing but to wait that the I/O operations are finished.
  • #25: Imagine that for every request you have to handle, you need to read something from the database. Your code will block waiting for the database operations to finish every time. In that period, you’re dedicating memory and processing time to a thread that it’s only waiting
  • #27: Because of this, typical web servers spawns a new thread for every incoming request to handle more traffic
  • #31: But as you can see, this is not optimal. Under stress situations, most of your threads will be consuming more memory and CPU waiting for other operations to finish. We can do better...
  • #32: But as you can see, this is not optimal. Under stress situations, most of your threads will be consuming more memory and CPU waiting for other operations to finish. We can do better...
  • #33: Another approach is to issue an I/O call but not wait until it’s finished
  • #34: As you can imagine, these kind of operations don’t block your program. In fact, the call returns immediately to the caller NS: and...
  • #35: you’ll be notified once the operation has finished
  • #39: Yup, just like with Dependency Injection
  • #40: Even though, keep in mind that if your tasks depend on having completed an I/O operation, you’d still have to wait for its completion. But this time, you won’t be wasting resources just waiting, because other processing that doesn’t depend on I/O can be executed
  • #41: With asynchronous I/O APIs and multithreading we can build more robust, scalable application. Async I/O also called NIO, remember first slides
  • #42: Most Operating Systems (OS) nowadays implement many asynchronous calls with different strategies. For example, with Unix systems you have polling, signals or select loops, while Windows has support for callback functions.
  • #43: Java and the JVM started to offer integration with package java.nio NS: since...
  • #44: 1.4., 2002
  • #45: Java 1.7 introduced a new API for files and more NIO goodies, usually referred as NIO2.
  • #46: The drawback of this approach is that our software will be more complex, if you tried to use Selector API you know this
  • #50: You freak dependency-haters
  • #52: The main difference is that in Netty all API definitions are asynchronous in nature, no matter what. NS: What does it mean?
  • #53: It is important to be aware of this encapsulation. Netty can be used as a general library as a replacement for Java NIO regarding network operations. Just like you would use Guava or Apache Commons.
  • #56: These days most of the projects tend to use HTTP for everything, from sending large files to building web service
  • #57: But HTTP is not always the answer to everything. Just like email works over SMTP, or non-critical data can be sent via UDP. For example, StatsD is a daemon that sends over UDP aggregates of different types of metrics and statistics.
  • #58: More often than you think you can find yourself trying to implement some protocol of your own. Think about mobile messaging, real-time exchanges between ad-servers, or you wanting to invoke some remote method in another server, like an RPC
  • #72: From my personal experience, I can confirm that is true in every way. It’s really easy to use Netty once you get used to the API. Soon you will notice how rapidly you are developing your applications
  • #73: If “implementing a protocol” sounds like too much for you, it’s not. Don’t think of it like that. You’ll be implementing exactly what you need for your program NS: By the way...
  • #74: By the way, most common protocols (HTTP, UDP, SSL…) are supported out-of-the-box, with many more coming.
  • #85: 3 → 4 → 4.1 → 5.0 - Even more basic, day to day things you’ll use, change
  • #94: This protocol defines that a daytime service simply sends the current date and time as a character string without regard to the input One daytime service is defined as a connection based application on TCP. A server listens for TCP connections on TCP port 13. Once a connection is established the current date and time is sent out the connection as a ascii character string (and any data received is thrown away). The service closes the connection after sending the quote
  • #96: Handlers in Netty are where you specify your business logic and write the actual application code you’ll need
  • #97: Handlers in Netty are where you specify your business logic and write the actual application code you’ll need
  • #98: A ChannelHandler will handle the operations for that Channel. Channel is roughly, a connection
  • #99: Inbound handlers are responsible to handle incoming traffic and dispatch events to the next Handler,
  • #100: outbound handlers do the exact same thing but in the other direction.
  • #101: Before, in version 3 they were known as Upstream and Downstream (like jenkins jobs) But it doesn’t stop there
  • #102: Move on. We have our class in place, time to do real work.
  • #103: We need to hook up into some method to do the actual work.
  • #104: But RFC says: “Once a connection is established the current date and time is sent out the connection. “ Handler has a natural lifecycle, very simplified in Netty 4
  • #111: ByteBuf is a container to hold bytes, with most common operations implemented in ByteBufUtil helper class. You may know that the Java offers its own java.nio.ByteBuffer class with the same purpose, but it has too many caveats to stick to it. We will see much more about ByteBuf in chapter 4
  • #113: Keep in mind that all of this is done for the sake of performance. Netty keeps internal pools to reuse space and prevent too many context switching, memory leaks and other typical problems you would face writing a network application on your own.
  • #117: NS: You know how to run this?
  • #118: Forget about classloaders, logger problems… If you want to call this a microservice, be my guest I don’t know what to think after fowler’s article about them
  • #120: Similar to JDK’s ExecutorService but with many power-ups.
  • #121: An EventLoopGroup is a multithreaded event loop that will handle I/O operations
  • #122: One EventLoop instance will handle I/O operations for a Channel.
  • #124: Put it in another way When we receive a connection, a Channel is registered for that connection, and then it gets assigned to an EventLoop inside the EventLoopGroup. Once assigned, that EventLoop is responsible to handle all I/O operations for that connection.
  • #125: This way, we can say that with some EventLoops instances, running always in the same thread, we can handle many Channels
  • #126: If you noticed, this is a big difference with most regular synchronous servers, where a connection is assigned to a thread This is the secret behind Netty’s thread model, and what vert.x and others use. Vert.x is actually using Netty, with Netty defaults… I believe magic happens there It changed for the best since version 3, with a lot of lessons learned. Like context switching is hard This is version 4.0, but now with version 4.1 and even 5.0, you can customize it, but following this pattern NS: Going back to the example
  • #128: The “boss” group is the one that accepts incoming connections. The “worker” group is the one that will handle all the work once a connection is accepted. The “boss” group will register and pass the connection to the “worker” group.
  • #131: For the Daytime protocol we need to accept incoming TCP/IP connections, so we need to use a ServerSocketChannel implementation. In this case, we are using NioServerSocketChannel, just like the previous NioEventLoopGroup uses NIO Selector to accept new connections.
  • #133: This option will set the maximum queue length for incoming connections. If a connection request arrives when the queue is full, the connection is refused. What makes this option special is that this restriction is not handled by Netty. It’s not even under JVM’s control. It’s a platform-dependent option that the underlying operating system will decide how to handle.
  • #134: If you noticed, this is a big difference with most regular synchronous servers, where a connection is assigned to a thread This is the secret behind Netty’s thread model, and what vert.x and others use. Vert.x is actually using Netty, with Netty defaults… I believe magic happens there It changed for the best since version 3, with a lot of lessons learned. Like context switching is hard This is version 4.0, but now with version 4.1 and even 5.0, you can customize it, but following this pattern NS: Going back to the example
  • #136: Netty uses a ChannelPipeline to define your application workflow. You may add one or more handlers to the ChannelPipeline Every connection received, it will execute this workflow
  • #137: Invoking ChannelPipeline.addLast(), you’re appending handlers at the end and defining the order of execution. There are more methods available, but it’s easier to keep it this way We’re usin
  • #139: NS: I want to use ChannelFuture to introduce for all the K.I.A that happened here.
  • #140: Netty is HUGE, but when you get all of its concepts, it’s always the same
  • #145: Tons of options, we’re constantly exploring them, try to find what works best Here is where your devops team can help you understand them
  • #146: “Understand your domain”, you actually need to understand what’s happening
  • #149: There’s no need to live in the past. You still want all DI goodies
  • #150: It this easy! Instead of using plain news We did some paranoid microbenchmarks, and it’s worth it every nano-second
  • #151: We need to respond always below 100ms,
  • #153: You have to measure everything. We use both statsd and caliper YourKit or any other profiler is your friend
  • #160: It doesn’t make any sense! Please share your configs
  • #162: Even if you’re not using Netty directly
  • #163: Snowball effect You’re handling 500 connections per machine → 90 thousand You won’t get an OOM error, everything is getting slower (because you’re measuring it in real time)
  • #164: You have to handle this, on your own
  • #167: Something big is coming… and is not the winter I’ve seen 2 times the Techempower result tests… it happens to be that I’m a big fan of those results… I was surprised about Vert.x being first, and even more surprised being better than Netty NS: So, I had to do it...
  • #168: Round 10, April 2015 Round 9, Round 8… one per year… pretty similar results… Where’s vert.x?