In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
In this article, the editor introduces in detail the "netty server auxiliary class ServerBootstrap how to create", the content is detailed, the steps are clear, and the details are handled properly. I hope this "netty server auxiliary class ServerBootstrap how to create" article can help you solve your doubts.
ServerBootstrap creation
ServerBootstrap creates server-side auxiliary classes for netty. Take NIO as an example, the creation code is as follows:
Public static void main (String [] args) throws Exception {ServerBootstrap bs = new ServerBootstrap () Bs.group (new NioEventLoopGroup (1) New NioEventLoopGroup () .channel (NioServerSocketChannel.class) .childHandler (new ChannelInitializer () {@ Override protected void initChannel (Channel ch) throws Exception {ch.pipeline () .addLa st (new HttpServerCodec ()) .addLast ( New HttpObjectAggregator (65535) .addLast (new Controller ()) }}) .bind (8080) .sync () .channel () .closeFuture () .sync ();} core parameters / / configuration properties, such as SO_KEEPALIVE, private final ServerBootstrapConfig config = new ServerBootstrapConfig (this); / / the event loop group "private volatile EventLoopGroup childGroup; private volatile ChannelHandler childHandler; initialization process bound by the child channel of acceot"
Mainly for binding local port-> registering itself to EventLoop, and registering accept and read events-> EventLoop's main loop will constantly select register channel events and handle them.
First perform the binding
The core logic is located in
In io.netty.bootstrap.AbstractBootstrap.doBind (SocketAddress) and io.netty.bootstrap.AbstractBootstrap.initAndRegister ()
Private ChannelFuture doBind (final SocketAddress localAddress) {final ChannelFuture regFuture = initAndRegister (); .if (regFuture.isDone ()) {/ / At this point we know that the registration was complete and successful. ChannelPromise promise = channel.newPromise (); / / binding logic doBind0 (regFuture, channel, localAddress, promise); return promise;} else {/ / Registration future is almost always fulfilled already, but just in case it's not. Final PendingRegistrationPromise promise = new PendingRegistrationPromise (channel); regFuture.addListener (new ChannelFutureListener () {@ Override public void operationComplete (ChannelFuture future) throws Exception {Throwable cause = future.cause () If (cause! = null) {/ / Registration on the EventLoop failed so fail the ChannelPromise directly to not cause an / / IllegalStateException once we try to access the EventLoop of the Channel. Promise.setFailure (cause);} else {/ / Registration was successful, so set the correct executor to use. / / See https://github.com/netty/netty/issues/2586 promise.registered (); doBind0 (regFuture, channel, localAddress, promise);}); return promise;}} register yourself with EventLoop
First, let's take a look at initAndRegister. The core logic is to initialize a NioServerSocketChannel instance using channelFactory, set the parameters in config for it, and then register it into EventLoop. In fact, it is registered by the delegated Unsafe of channel. The core logic is located in AbstractUnsafe.register0 to complete registration.
Final ChannelFuture initAndRegister () {Channel channel = null; try {/ / what is actually called in this example is the construction parameter of NioServerSocketChannel and sets the event type of interest to OP_ACCEPT channel = channelFactory.newChannel (); init (channel) } catch (Throwable t) {if (channel! = null) {/ / channel can be null if newChannel crashed (eg SocketException ("too many open files")) channel.unsafe (). CloseForcibly ();} / / as the Channel is not registered yet we need to force the usage of the GlobalEventExecutor return new DefaultChannelPromise (channel, GlobalEventExecutor.INSTANCE) .setFailure (t) } ChannelFuture regFuture = config (). Group (). Register (channel); if (regFuture.cause ()! = null) {if (channel.isRegistered ()) {channel.close ();} else {channel.unsafe (). CloseForcibly ();}} return regFuture } void init (Channel channel) throws Exception {/ / set properties. P.addLast (new ChannelInitializer () {@ Override public void initChannel (final Channel ch) throws Exception {final ChannelPipeline pipeline = ch.pipeline (); ChannelHandler handler = config.handler (); if (handler! = null) {pipeline.addLast (handler)) } ch.eventLoop () .execute (new Runnable () {@ Override public void run () {/ / set a default channelhandler: ServerBootstrapAcceptor for NioServerSocketChannel when the accept event occurs Register accept's channel with childEventLoop pipeline.addLast (new ServerBootstrapAcceptor (ch, currentChildGroup, currentChildHandler, currentChildOptions, currentChildAttrs)) })) } private void register0 (ChannelPromise promise) {try {/ / check if the channel is still open as it could be closed in the mean time when the register / / call was outside of the eventLoop if (! promise.setUncancellable () | |! ensureOpen (promise)) {return;} boolean firstRegistration = neverRegistered / / execute selector doRegister () from channel to eventloop; neverRegistered = false; registered = true; / / Ensure we call handlerAdded (...) Before we actually notify the promise. This is needed as the / / user may already fire events through the pipeline in the ChannelFutureListener. Pipeline.invokeHandlerAddedIfNeeded (); safeSetSuccess (promise); / / trigger InboundChannelHnader.channelRegistered event pipeline.fireChannelRegistered (); / / Only fire a channelActive if the channel has never been registered. This prevents firing / / multiple channel actives if the channel is deregistered and re-registered. If (isActive ()) {if (firstRegistration) {/ / triggers the channelActive event and binds the read event pipeline.fireChannelActive ();} else if (config (). IsAutoRead ()) {/ / This channel was registered before and autoRead () is set for channel. This means we need to begin read / / again so that we process inbound data. / See https://github.com/netty/netty/issues/4805 beginRead ();} catch (Throwable t) {/ / Close the channel directly to avoid FD leak. CloseForcibly (); closeFuture.setClosed (); safeSetFailure (promise, t);}} bind port logic
After the initAndRegister registration is successful, the real binding port logic is executed, and the core logic is located in NioSocketChannel.doBind0 (SocketAddress).
Private void doBind0 (SocketAddress localAddress) throws Exception {if (PlatformDependent.javaVersion () > = 7) {SocketUtils.bind (javaChannel (), localAddress);} else {SocketUtils.bind (javaChannel (). Socket (), localAddress);}}
So far, the binding is successful. When the ACCEPT event is triggered, NioServerSocketChannel.doReadMessages-> ServerBootstrapAcceptor.channelRead will be triggered and the child channel will be registered with the childEventLoop.
Public void channelRead (ChannelHandlerContext ctx, Object msg) {final Channel child = (Channel) msg; child.pipeline () .addLast (childHandler); setChannelOptions (child, childOptions, logger); for (Entry)
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.