In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article will give you a detailed introduction to how to carry out Java--Netty, the content of the article is of high quality, so the editor will share it for you as a reference. I hope you will have a certain understanding of the relevant knowledge after reading this article.
Introduction to Netty
Netty is a high-performance, highly scalable asynchronous event-driven network application framework, which greatly simplifies TCP and UDP client-side and server-side network development. It is a NIO framework that encapsulates Java NIO well. As an asynchronous NIO framework, all IO operations of Netty are asynchronous and non-blocking. Through the Future-Listener mechanism, users can easily obtain the results of IO operations actively or through the notification mechanism.
Characteristics of Netty
Unified API for different protocols
Based on flexible and extensible event-driven model
Highly customizable threading model
Better throughput, low latency
Save resources and minimize unnecessary memory copies
Full SSL/TLS and STARTTLS support
Can work well in the restricted environment of Applet and Android
No longer cause OutOfMemoryError due to too fast, too slow, or overloaded connections
There is no longer the problem of inconsistent NIO read and write frequency in high-speed network environment.
Core content of Netty
The core content of Netty mainly includes the following four aspects:
Reactor threading model: a high-performance multithreaded programming idea
Self-defined Channel concept in Netty: enhanced Channel concept
ChannelPipeline responsibility chain Design pattern: event handling Mechanism
Memory management: enhanced ByteBuf buffer
Netty overall structure diagram
Netty core components
EventLoop:EventLoop maintains a thread and task queue that allows tasks to be submitted for execution asynchronously. EventLoop itself implements the Executor interface. When you call the executor method to submit a task, you will determine whether to start it or not. If it is not started, you will call the built-in executor to create a new thread to trigger the execution of the run method. The general process is as follows: see Netty source code SingleThreadEventExecutor:
EventLoopGroup:EventLoopGroup mainly manages the life cycle of eventLoop, which can be thought of as a thread pool, in which a set of EventLoop is maintained. Each eventLoop handles multiple Channel, while a Channel can only correspond to one EventLoop.
Bootstrap:BootStrap is the boot class of the client, which is mainly used for the client to connect to the remote host, with 1 EventLoopGroup. When Bootstrap calls the bind () (connect UDP) and connect () (connect TCP) methods, a new Channel without a parent Channel is created to implement all network exchanges.
ServerBootstrap:ServerBootstrap is the server-side boot class, the main user server binds the local port, there are 2 EventLoopGroup. When ServerBootstarp calls the bind () method, it creates a ServerChannel to accept connections from the client, and the ServerChannel manages multiple sub-Channel for communication with the client.
Channel in Channel:Netty is an abstract concept, which can be understood as an enhancement and extension of Java NIO Channel, adding many new properties and methods, such as bing methods.
ChannelFuture:ChannelFuture can register one or more ChannelFutureListener instances and will be notified when the operation is completed, regardless of success or failure. The ChannelFuture stores the results of subsequent operations and cannot predict when the operations will be performed, and the operations submitted to the Channel are performed in the order in which they are awakened.
ChannelHandler:ChannelHandler is used to deal with business logic, with inbound and outbound implementations respectively.
ChannelPipeline:ChannelPipeline provides a container for the ChannelHandler chain and defines the API used to propagate inbound and outbound event streams on the chain.
Netty thread model
The threading model of Netty is based on the threading implementation of Reactor pattern. The Reactor pattern can be referred to the Reactor pattern. According to the user's configuration, Netty can support single-thread Reactor model, multi-thread Reactor model and master-slave multi-Reactor model. The general process in Netty is as follows:
Sample getting started Code for Netty
Server code example:
Import io.netty.bootstrap.ServerBootstrap
Import io.netty.buffer.ByteBuf
Import io.netty.buffer.Unpooled
Import io.netty.channel.*
Import io.netty.channel.nio.NioEventLoopGroup
Import io.netty.channel.socket.SocketChannel
Import io.netty.channel.socket.nio.NioServerSocketChannel
Import io.netty.handler.logging.LogLevel
Import io.netty.handler.logging.LoggingHandler
Import java.nio.charset.Charset
Public class EchoServer {
Public static void main (String [] args) {
/ / accept thread group, used to accept connections
EventLoopGroup bossGroup = new NioEventLoopGroup (1)
/ / Icano thread group, which is used to process business logic
EventLoopGroup workerGroup = new NioEventLoopGroup (1)
Try {
/ / the server starts the boot
ServerBootstrap b = new ServerBootstrap ()
B.group (bossGroup, workerGroup) / / bind two thread groups
.channel (NioServerSocketChannel.class) / / specify the channel type
.option (ChannelOption.SO_BACKLOG, 100) / / sets the buffer for TCP connections
.handler (new LoggingHandler (LogLevel.INFO)) / / sets the log level
.childHandler (
New ChannelInitializer () {
@ Override
Protected void initChannel (SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline (); / / get processor chain
Pipeline.addLast (new EchoServerHandler ()); / / add a new component processor
}
});
/ / start the service through bind
ChannelFuture f = b.bind (8080) .sync ()
/ / blocks the main thread until the network service is turned off
F.channel (). CloseFuture (). Sync ()
} catch (Exception e) {
E.printStackTrace ()
} finally {
WorkerGroup.shutdownGracefully ()
BossGroup.shutdownGracefully ()
}
}
}
Class EchoServerHandler extends ChannelInboundHandlerAdapter {
/ / whenever new data is received from the client, this method is called when a message is received.
@ Override
Public void channelRead (ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println ("data received:" + ((ByteBuf) msg) .toString (Charset.defaultCharset ()
Ctx.write (Unpooled.wrappedBuffer ("Server message" .getBytes ()
Ctx.fireChannelRead (msg)
}
/ / after reading the data, @ Override is called.
Public void channelReadComplete (ChannelHandlerContext ctx) throws Exception {
Ctx.flush ()
}
/ / @ Override is called when Netty is called due to an IO error or an exception thrown by the processor while handling the event
Public void exceptionCaught (ChannelHandlerContext ctx, Throwable cause) throws Exception {
Cause.printStackTrace ()
Ctx.close ()
}
}
Client code example:
Import io.netty.bootstrap.Bootstrap
Import io.netty.buffer.ByteBuf
Import io.netty.buffer.Unpooled
Import io.netty.channel.*
Import io.netty.channel.nio.NioEventLoopGroup
Import io.netty.channel.socket.SocketChannel
Import io.netty.channel.socket.nio.NioSocketChannel
Import java.nio.charset.Charset
Public class EchoClient {
Public static void main (String [] args) {
EventLoopGroup group = new NioEventLoopGroup ()
Try {
Bootstrap b = new Bootstrap ()
B.group (group)
.channel (NioSocketChannel.class)
.option (ChannelOption.TCP_NODELAY, true)
.handler (
New ChannelInitializer () {
@ Override
Public void initChannel (SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline ()
P.addLast (new EchoClientHandler ())
}
});
ChannelFuture f = b.connect ("127.0.0.1", 8080). Sync ()
F.channel (). CloseFuture (). Sync ()
} catch (Exception e) {
E.printStackTrace ()
} finally {
Group.shutdownGracefully ()
}
}
}
Class EchoClientHandler extends ChannelInboundHandlerAdapter {
Private final ByteBuf firstMessage
Public EchoClientHandler () {
FirstMessage = Unpooled.buffer (256)
For (int I = 0; I < firstMessage.capacity (); iTunes +) {
FirstMessage.writeByte ((byte) I)
}
}
@ Override
Public void channelActive (ChannelHandlerContext ctx) {
Ctx.writeAndFlush (firstMessage)
}
@ Override
Public void channelRead (ChannelHandlerContext ctx, Object msg) {
System.out.println ("data received:" + ((ByteBuf) msg) .toString (Charset.defaultCharset ()
Ctx.write (Unpooled.wrappedBuffer ("Client message" .getBytes ()
}
@ Override
Public void channelReadComplete (ChannelHandlerContext ctx) {
Ctx.flush ()
}
@ Override
Public void exceptionCaught (ChannelHandlerContext ctx, Throwable cause) {
Cause.printStackTrace ()
Ctx.close ()
}
} this is the end of the introduction to Java--Netty. I hope the above content can help you to some extent and learn more knowledge. If you think the article is good, you can share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.