Netty服务端的业务流程分析
Netty的服务端怎么和java NIO联系起来的,一直很好奇这块内容,这里跟下代码,下篇文章看下Channel相关的知识。
finalChannelFuture initAndRegister(){finalChannel channel = channelFactory().newChannel();//try{init(channel);}catch(Throwable t){channel.unsafe().closeForcibly();//立即关闭通道且不会触发事件//因为这个通道还没有注册到EventLoop,所以我们需要强制GlobalEventExecutor的使用。returnnewDefaultChannelPromise(channel,GlobalEventExecutor.INSTANCE).setFailure(t);}//注册一个EventLoopChannelFuture regFuture = group().register(channel);//注册失败if(regFuture.cause()!=null){if(channel.isRegistered()){channel.close();}else{channel.unsafe().closeForcibly();}}// If we are here and the promise is not failed, it's one of the following cases:// 程序运行到这里且promise没有失败,可能有如下几种情况// 1) If we attempted registration from the event loop, the registration has been completed at this point.// 如果试图注册到一个EventLoop,该注册完成,// i.e. It's safe to attempt bind() or connect() now because the channel has been registered.// 2) If we attempted registration from the other thread, the registration request has been successfully// added to the event loop's task queue for later execution.// 如果试图注册到其他线程,该注册已经成功,但是没有完成,添加一个事件到任务队列中,等会执行// i.e. It's safe to attempt bind() or connect() now:// because bind() or connect() will be executed *after* the scheduled registration task is executed// because register(), bind(), and connect() are all bound to the same thread.return regFuture;}
@OverridepublicChannelFutureregister(Channel channel){return next().register(channel);}
@OverridepublicChannelFutureregister(finalChannel channel,finalChannelPromise promise){if(channel ==null){thrownewNullPointerException("channel");}if(promise ==null){thrownewNullPointerException("promise");}channel.unsafe().register(this, promise);return promise;}
@Overridepublicfinalvoidregister(EventLoop eventLoop,finalChannelPromise promise){if(eventLoop ==null){thrownewNullPointerException("eventLoop");}if(isRegistered()){promise.setFailure(newIllegalStateException("registered to an event loop already"));return;}if(!isCompatible(eventLoop)){promise.setFailure(newIllegalStateException("incompatible event loop type: "+ eventLoop.getClass().getName()));return;}AbstractChannel.this.eventLoop = eventLoop;if(eventLoop.inEventLoop()){register0(promise);}else{try{eventLoop.execute(newOneTimeTask(){@Overridepublicvoid run(){register0(promise);}});}catch(Throwable t){logger.warn("Force-closing a channel whose registration task was not accepted by an event loop: {}",AbstractChannel.this, t);closeForcibly();closeFuture.setClosed();safeSetFailure(promise, t);}}}
@Overrideprotectedvoid doRegister()throwsException{boolean selected =false;for(;;){try{selectionKey = javaChannel().register(eventLoop().selector,0,this);return;}catch(CancelledKeyException e){if(!selected){// Force the Selector to select now as the "canceled" SelectionKey may still be// cached and not removed because no Select.select(..) operation was called yet.eventLoop().selectNow();selected =true;}else{// We forced a select operation on the selector before but the SelectionKey is still cached// for whatever reason. JDK bug ?throw e;}}}}
wakeup 方法所得的结果privatestaticvoid doBind0(finalChannelFuture regFuture,finalChannel channel,finalSocketAddress localAddress,finalChannelPromise promise){// This method is invoked before channelRegistered() is triggered. Give user handlers a chance to set up// the pipeline in its channelRegistered() implementation.channel.eventLoop().execute(newRunnable(){@Overridepublicvoid run(){if(regFuture.isSuccess()){channel.bind(localAddress, promise).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);}else{promise.setFailure(regFuture.cause());}}});}
@Overrideprotectedvoid run(){for(;;){boolean oldWakenUp = wakenUp.getAndSet(false);try{if(hasTasks()){selectNow();}else{select(oldWakenUp);// 'wakenUp.compareAndSet(false, true)' is always evaluated// before calling 'selector.wakeup()' to reduce the wake-up// overhead. (Selector.wakeup() is an expensive operation.)//// However, there is a race condition in this approach.// The race condition is triggered when 'wakenUp' is set to// true too early.//// 'wakenUp' is set to true too early if:// 1) Selector is waken up between 'wakenUp.set(false)' and// 'selector.select(...)'. (BAD)// 2) Selector is waken up between 'selector.select(...)' and// 'if (wakenUp.get()) { ... }'. (OK)//// In the first case, 'wakenUp' is set to true and the// following 'selector.select(...)' will wake up immediately.// Until 'wakenUp' is set to false again in the next round,// 'wakenUp.compareAndSet(false, true)' will fail, and therefore// any attempt to wake up the Selector will fail, too, causing// the following 'selector.select(...)' call to block// unnecessarily.//// To fix this problem, we wake up the selector again if wakenUp// is true immediately after selector.select(...).// It is inefficient in that it wakes up the selector for both// the first case (BAD - wake-up required) and the second case// (OK - no wake-up required).if(wakenUp.get()){selector.wakeup();}}cancelledKeys =0;needsToSelectAgain =false;finalint ioRatio =this.ioRatio;if(ioRatio ==100){processSelectedKeys();runAllTasks();}else{finallong ioStartTime =System.nanoTime();processSelectedKeys();finallong ioTime =System.nanoTime()- ioStartTime;runAllTasks(ioTime *(100- ioRatio)/ ioRatio);}if(isShuttingDown()){closeAll();if(confirmShutdown()){break;}}}catch(Throwable t){logger.warn("Unexpected exception in the selector loop.", t);// Prevent possible consecutive immediate failures that lead to// excessive CPU consumption.try{Thread.sleep(1000);}catch(InterruptedException e){// Ignore.}}}}
Netty服务端的业务流程分析的更多相关文章
- Netty服务端的启动源码分析
ServerBootstrap的构造: public class ServerBootstrap extends AbstractBootstrap<ServerBootstrap, Serve ...
- Netty之旅三:Netty服务端启动源码分析,一梭子带走!
Netty服务端启动流程源码分析 前记 哈喽,自从上篇<Netty之旅二:口口相传的高性能Netty到底是什么?>后,迟迟两周才开启今天的Netty源码系列.源码分析的第一篇文章,下一篇我 ...
- 【Netty源码分析】Netty服务端bind端口过程
这一篇博客我们介绍一下Netty服务端绑定端口的过程,我们通过跟踪代码一直到NIO原生绑定端口的操作. 绑定端口操作 ChannelFuture future = serverBootstrap.bi ...
- Netty 服务端启动过程
在 Netty 中创建 1 个 NioServerSocketChannel 在指定的端口监听客户端连接,这个过程主要有以下 个步骤: 创建 NioServerSocketChannel 初始化并注 ...
- Netty 服务端创建
参考:http://blog.csdn.net/suifeng3051/article/details/28861883?utm_source=tuicool&utm_medium=refer ...
- netty服务端启动--ServerBootstrap源码解析
netty服务端启动--ServerBootstrap源码解析 前面的第一篇文章中,我以spark中的netty客户端的创建为切入点,分析了netty的客户端引导类Bootstrap的参数设置以及启动 ...
- Netty服务端NioEventLoop启动及新连接接入处理
一 Netty服务端NioEventLoop的启动 Netty服务端创建.初始化完成后,再向Selector上注册时,会将服务端Channel与NioEventLoop绑定,绑定之后,一方面会将服务端 ...
- Netty服务端Channel的创建与初始化
Netty创建服务端Channel时,从服务端 ServerBootstrap 类的 bind 方法进入,下图是创建服务端Channel的函数调用链.在后续代码中通过反射的方式创建服务端Channel ...
- netty服务端客户端启动流程分析
服务端启动流程 我们回顾前面讲解的netty启动流程,服务端这边有两个EventLoopGroup,一个专门用来处理连接,一个用来处理后续的io事件 服务端启动还是跟nio一样,绑定端口进行监听,我们 ...
随机推荐
- docker 存储
[root@docker01 ~]# docker run --name b1 -v /data -it busybox / # ls bin data dev etc home proc root ...
- [Luogu4177][CEOI2008]order
luogu sol 这题有点像网络流24题里面的太空飞行计划啊. 最大收益=总收益-最小损失. 先令\(ans=\sum\)任务收益. 源点向每个任务连容量为收益的边. 每个机器向汇点连容量为购买费用 ...
- C#:使用UPnP来穿透NAT使内网接口对外网可见
在写完Object 672后,软件的一个致命问题暴露出来,如果服务器和客户端都在内网环境下,即双方都通过NAT来接触外网,那么此时客户端是无法直接和服务器交流的. 解决方案可以是: 1:把服务器部署在 ...
- C# Message 消息处理
一.消息概述 Windows下应用程序的执行是通过消息驱动的.消息是整个应用程序的工作引擎,我们需要理解掌握我们使用的编程语言是如何封装消息的原理.C#自定义消息通信往往采用事件驱动的方式实现,但有时 ...
- [推荐]InfoQ上的深入浅出Node.js的系列文章
InfoQ上的深入浅出Node.js的系列文章 详情如下链接:http://www.heiboard.com/?p=2081
- java编程思想第五章初始化与清理
5.1使用构造器确保初始化: 构造器与一般方法一样,但是没有返回值,且其方法名与类名完全相同. 不接受任何参数的构造器成为默认构造器,也叫无参构造器. 5.2 方法重载: 为什么会有方法重载? 构造器 ...
- java中static的学习
1.static引入: 通常来说,当创建一个类是,就是在描述那个类的对象的外观与行为.除非用new创建那个类的对象,否则实际并未获取任何对象.当执行new来创建对象时,数据存储空间才被分配,七方法才供 ...
- asp.net过滤HTML标签,只保留换行与空格
自己从网上找了一个过滤HTML标签的方法,我也不知道谁的才是原创的,反正很多都一样.我把那方法复制下来,代码如下: /// <summary> /// 去除HTML标记 /// </ ...
- linux下的时间
1.linux下时间管理机制: 在系统启动时,Linux操作系统将时间从CMOS中读到系统时间变量中,以后修改时间通过修改系统时间实现.为了保持系统时间与CMOS时间的一致性,Linux每隔11分钟会 ...
- Day2-Python基础2---浅copy、深copy的差别
浅copy 首先我们来看下面一段代码: 1 >>> names = ["maqing"," peilin"," xiaoming&q ...