Netty问题,我这里是nettynetty 获取客户端ip,我业务代码走到netty的时候启动netty去请求服务

  尊重原创,转载注明出处,原文地址:&
  本文将不会对netty中每个点分类讲解,而是一个服务端启动的代码走读,在这个过程中再去了解和学习,这也是博主自己的学习历程。下面开始正文~~~~
  众所周知,在写netty服务端应用的时候一般会有这样的启动代码:
(代码一) 1 EventLoopGroup bossGroup = new NioEventLoopGroup(1);
2 EventLoopGroup workerGroup = new NioEventLoopGroup();
ServerBootstrap bootStrap = new ServerBootstrap();
bootStrap.group(bossGroup, workerGroup)
  .channel(NioServerSocketChannel.class)
  .childHandler(new WebsocketChatServerInitializer())
  .option(ChannelOption.SO_BACKLOG, 128)
  .childOption(ChannelOption.SO_KEEPALIVE, true);
<span style="color: #
<span style="color: #
ChannelFuture f = bootStrap.bind(port).sync();
<span style="color: #
f.channel().closeFuture().sync();
<span style="color: # } finally {
<span style="color: #
<span style="color: # }
  本文将沿着这条主线来走读代码,但是在走读之前首先要先认识一下Netty中的reactor模式是怎么玩的。
  首先先借用Doug Lea在中的经典的图示:
  这张图是经典的运用了多路复用的Reactor模式,也大致说明了在netty中各线程的工作模式,mainReactor负责处理客户端的请求,subReacor负责处理I/O的读写操作,同时还会有一些用户的线程,用于异步处理I/O数据,在整个过程中通过角色细化,有效地将线程资源充分利用起来,构建了一条无阻塞通道,最后将耗时的业务逻辑交由业务线程去处理。本文不会对reactor做过多的解读,而是结合netty的线程池模式来学习。
  回到刚刚的主题,在服务端启动的时候首先会new两个NioEventLoopGroup,一个叫bossGroup(boss线程池),一个叫workerGroup(worker线程池),而这两个就分别对应了上述的mainReactor和subReacor。接下来我们来看在new的过程中发生了什么。
  代码走到MultithreadEventLoopGroup的构造方法中:
(代码二) 1 public abstract class MultithreadEventLoopGroup extends MultithreadEventExecutorGroup implements EventLoopGroup {
private static final int DEFAULT_EVENT_LOOP_THREADS;
DEFAULT_EVENT_LOOP_THREADS = Math.max(1, SystemPropertyUtil.getInt(
"io.netty.eventLoopThreads", Runtime.getRuntime().availableProcessors() * 2));
if (logger.isDebugEnabled()) {
<span style="color: #
logger.debug("-Dio.netty.eventLoopThreads: {}", DEFAULT_EVENT_LOOP_THREADS);
<span style="color: #
<span style="color: #
<span style="color: #
<span style="color: #
protected MultithreadEventLoopGroup(int nThreads, ThreadFactory threadFactory, Object... args) {
<span style="color: #
super(nThreads == 0? DEFAULT_EVENT_LOOP_THREADS : nThreads, threadFactory, args);
<span style="color: #
<span style="color: # ...
<span style="color: # }
  可以看到如果参数传入了thread个数就取这个数目,如果没有传入就取可用处理器(CPU)个数的2倍。因此【代码一】中boss只有1个线程,而worker有2*cpu个数个线程。
  继续往下走到了核心代码MultithreadEventExecutorGroup中:
(代码三) 1 public abstract class MultithreadEventExecutorGroup extends AbstractEventExecutorGroup {
private final EventExecutor[]
private final AtomicInteger childIndex = new AtomicInteger();
private final AtomicInteger terminatedChildren = new AtomicInteger();
private final Promise&?& terminationFuture = new DefaultPromise(GlobalEventExecutor.INSTANCE);
private final EventExecutorC
protected MultithreadEventExecutorGroup(int nThreads, ThreadFactory threadFactory, Object... args) {
<span style="color: #
if (nThreads &= 0) {
<span style="color: #
throw new IllegalArgumentException(String.format("nThreads: %d (expected: & 0)", nThreads));
<span style="color: #
<span style="color: #
<span style="color: #
if (threadFactory == null) {
<span style="color: #
threadFactory = newDefaultThreadFactory();
<span style="color: #
<span style="color: #
<span style="color: #
children = new SingleThreadEventExecutor[nThreads];
<span style="color: #
if (isPowerOfTwo(children.length)) {
<span style="color: #
chooser = new PowerOfTwoEventExecutorChooser();
<span style="color: #
<span style="color: #
chooser = new GenericEventExecutorChooser();
<span style="color: #
<span style="color: #
<span style="color: #
for (int i = 0; i & nT i ++) {
<span style="color: #
boolean success = false;
<span style="color: #
<span style="color: #
children[i] = newChild(threadFactory, args);
<span style="color: #
success = true;
<span style="color: #
} catch (Exception e) {
<span style="color: #
// TODO: Think about if this is a good exception type
<span style="color: #
throw new IllegalStateException("failed to create a child event loop", e);
<span style="color: #
} finally {
<span style="color: #
if (!success) {
<span style="color: #
...<span style="color: #
<span style="color: #
<span style="color: #
<span style="color: #
<span style="color: #
final FutureListener&Object& terminationListener = new FutureListener&Object&() {
<span style="color: #
<span style="color: #
public void operationComplete(Future&Object& future) throws Exception {
<span style="color: #
if (terminatedChildren.incrementAndGet() == children.length) {
<span style="color: #
terminationFuture.setSuccess(null);
<span style="color: #
<span style="color: #
<span style="color: #
<span style="color: #
<span style="color: #
for (EventExecutor e: children) {
<span style="color: #
e.terminationFuture().addListener(terminationListener);
<span style="color: #
<span style="color: #
  首先new一个线程工厂newDefaultThreadFactory,然后给变量children赋值【PS:children是线程执行器的集合,几个线程就会有几个EventExecutor。因此EventExecutor是Reactor模式中真正执行工作的对象,它继承自ScheduledExecutorService,所以应该明白它本质上是什么了吧】
  children是赋值new了给定线程数数量的SingleThreadEventExecutor,看其内部代码,SingleThreadEventExecutor构造方法:
(代码四) 1 public abstract class SingleThreadEventExecutor extends AbstractScheduledEventExecutor {
private final EventExecutorG
private final Queue&Runnable& taskQ
private final T
protected SingleThreadEventExecutor(
EventExecutorGroup parent, ThreadFactory
threadFactory, boolean addTaskWakesUp) {
<span style="color: #
if (threadFactory == null) {
<span style="color: #
throw new NullPointerException("threadFactory");
<span style="color: #
<span style="color: #
<span style="color: #
this.parent =
<span style="color: #
this.addTaskWakesUp = addTaskWakesUp;
<span style="color: #
<span style="color: #
thread = threadFactory.newThread(new Runnable() {
<span style="color: #
<span style="color: #
public void run() {
<span style="color: #
boolean success = false;
<span style="color: #
updateLastExecutionTime();
<span style="color: #
<span style="color: #
SingleThreadEventExecutor.this.run();
<span style="color: #
success = true;
<span style="color: #
} catch (Throwable t) {
<span style="color: #
logger.warn("Unexpected exception from an event executor: ", t);
<span style="color: #
} finally {
<span style="color: #
<span style="color: #
<span style="color: #
<span style="color: #
<span style="color: #
threadProperties = new DefaultThreadProperties(thread);
<span style="color: #
taskQueue = newTaskQueue();
<span style="color: #
<span style="color: #
<span style="color: # }
  回到刚刚的主题(代码三),发现在children[i] = newChild(threadFactory, args);而newChild是抽象方法,由于最开始我们初始化的是NioEventLoopGroup,因此是在NioEventLoopGroup中调用的:
(代码五)1 protected EventExecutor newChild(
<span style="color: #
ThreadFactory threadFactory, Object... args) throws Exception {
<span style="color: #
return new NioEventLoop(this, threadFactory, (SelectorProvider) args[0]);
<span style="color: # }
  因此相当于我们有多少个work或boss线程就有多少个NioEventLoop,而每一个NioEventLoop都绑定了一个selector。所以,相当于一个NioEventLoopGroup有自定义线程数量的NioEventLoop。
  【PS:EventLoopGroup顾名思义是EventLoop的group,即包含了一组EventGroup。在实际的业务处理中,EventLoopGroup会通过EventLoop next()方法选择一个 EventLoop,然后将实际的业务处理交给这个被选出的EventLoop去做。对于 NioEventLoopGroup来说,其真实功能都会交给EventLoopGroup去实现。】
  接下来我们重点去看一下EventLoop和EventLoopGroup,自己画了这一块的UML图来理一下类关系:
  可以看出,EventLoop也继承自EventLoopGroup,因此也是EventLoopGroup的一种。同时看到,这一堆类都实现自ScheduledExecutorService,那么大家应该理解EventLoop和EventLoopGroup本质上是什么东西了吧。这里先不铺展开,下文中在讲注册逻辑时会对EventLoopGroup做一个更详细的了解。
  我们先回到【代码五主线】,我们接下来继续看初始化逻辑:
(代码六)1 NioEventLoop(NioEventLoopGroup parent, ThreadFactory threadFactory, SelectorProvider selectorProvider) {
<span style="color: #
super(parent, threadFactory, false);
<span style="color: #
if (selectorProvider == null) {
<span style="color: #
throw new NullPointerException("selectorProvider");
<span style="color: #
<span style="color: #
provider = selectorP
<span style="color: #
selector = openSelector();
<span style="color: #
  初始化NioEventLoop时调用了openSelector来打开当前操作系统中一个默认的selector实现。
  回到【代码一主线】,服务端初始化了boss和worker线程之后调用ServerBootstrap.group()来绑定两个线程池调度器。接下来调用ServerBootstrap.channel(NioServerSocketChannel.class)。这块逻辑很简单就是在bootstrap内部初始化了一个class类型是NioServerSocketChannel的ChannelFactory,【PS:ChannelFactory不会指定生产对象的具体类型,只要继承自Channel就可以了】。
  接下来,ServerBootstrap.childHandler()作用就是设置ChannelHandler来响应Channel的请求。一般这里都会设置抽象类ChannelInitializer,并且实现模板方法initChannel,在ChannelHandler注册(初始化)的时候会调用initChannel来完成ChannelPipeline的初始化。
(代码七) 1 public abstract class ChannelInitializer&C extends Channel& extends ChannelInboundHandlerAdapter {
protected abstract void initChannel(C ch) throws E
@SuppressWarnings("unchecked")
public final void channelRegistered(ChannelHandlerContext ctx) throws Exception {
initChannel((C) ctx.channel());
ctx.pipeline().remove(this);
<span style="color: #
ctx.fireChannelRegistered();
<span style="color: #
<span style="color: #
<span style="color: # }
  关于ChannelHandler我们后面会做详细的介绍,这里只需要了解到此就可以了。
  回到【代码一主线】,接下来bootStrap.option()和childOption()分别是给boss线程和worder线程设置参数,这里先忽略。
  然后是绑定端口ChannelFuture f = bootStrap.bind(port);在这一步中不仅仅是绑定端口,实际上需要做大量的初始化工作。我们先看一下AbstractBootstrap中的核心代码:
(代码八) 1   private ChannelFuture doBind(final SocketAddress localAddress) {
final ChannelFuture regFuture = initAndRegister();
final Channel channel = regFuture.channel();
if (regFuture.cause() != null) {
return regF
if (regFuture.isDone()) {
ChannelPromise promise = channel.newPromise();
<span style="color: #
doBind0(regFuture, channel, localAddress, promise);
<span style="color: #
<span style="color: #
<span style="color: #
final PendingRegistrationPromise promise = new PendingRegistrationPromise(channel);
<span style="color: #
regFuture.addListener(new ChannelFutureListener() {
<span style="color: #
<span style="color: #
public void operationComplete(ChannelFuture future) throws Exception {
<span style="color: #
Throwable cause = future.cause();
<span style="color: #
if (cause != null) {
<span style="color: #
promise.setFailure(cause);
<span style="color: #
<span style="color: #
promise.executor = channel.eventLoop();
<span style="color: #
<span style="color: #
doBind0(regFuture, channel, localAddress, promise);
<span style="color: #
<span style="color: #
<span style="color: #
<span style="color: #
<span style="color: #
  【代码八主线】首先是initAndRegister(),看一下代码:
(代码九) 1 final ChannelFuture initAndRegister() {
final Channel channel = channelFactory().newChannel();
init(channel);
} catch (Throwable t) {
channel.unsafe().closeForcibly();
return new DefaultChannelPromise(channel, GlobalEventExecutor.INSTANCE).setFailure(t);
<span style="color: #
ChannelFuture regFuture = group().register(channel);
<span style="color: #
if (regFuture.cause() != null) {
<span style="color: #
if (channel.isRegistered()) {
<span style="color: #
channel.close();
<span style="color: #
<span style="color: #
channel.unsafe().closeForcibly();
<span style="color: #
<span style="color: #
<span style="color: #
<span style="color: #
return regF
<span style="color: #
  首先调用工厂方法生成一个新Channel,我们刚刚说过,ChannelFactory不限定Channel的具体类型,而我们注册的是NioServerSocketChannel,那么这里生产的就是该类型的Channel,然后调用init(),具体实现在ServerBootstrap中:
(代码十) 1
void init(Channel channel) throws Exception {
final Map&ChannelOption&?&, Object& options = options();
synchronized (options) {
channel.config().setOptions(options);
final Map&AttributeKey&?&, Object& attrs = attrs();
synchronized (attrs) {
<span style="color: #
for (Entry&AttributeKey&?&, Object& e: attrs.entrySet()) {
<span style="color: #
@SuppressWarnings("unchecked")
<span style="color: #
AttributeKey&Object& key = (AttributeKey&Object&) e.getKey();
<span style="color: #
channel.attr(key).set(e.getValue());
<span style="color: #
<span style="color: #
<span style="color: #
<span style="color: #
ChannelPipeline p = channel.pipeline();
<span style="color: #
<span style="color: #
final EventLoopGroup currentChildGroup = childG
<span style="color: #
final ChannelHandler currentChildHandler = childH
<span style="color: #
final Entry&ChannelOption&?&, Object&[] currentChildO
<span style="color: #
final Entry&AttributeKey&?&, Object&[] currentChildA
<span style="color: #
synchronized (childOptions) {
<span style="color: #
currentChildOptions = childOptions.entrySet().toArray(newOptionArray(childOptions.size()));
<span style="color: #
<span style="color: #
synchronized (childAttrs) {
<span style="color: #
currentChildAttrs = childAttrs.entrySet().toArray(newAttrArray(childAttrs.size()));
<span style="color: #
<span style="color: #
<span style="color: #
p.addLast(new ChannelInitializer&Channel&() {
<span style="color: #
<span style="color: #
public void initChannel(Channel ch) throws Exception {
<span style="color: #
ChannelPipeline pipeline = ch.pipeline();
<span style="color: #
ChannelHandler handler = handler();
<span style="color: #
if (handler != null) {
<span style="color: #
pipeline.addLast(handler);
<span style="color: #
<span style="color: #
pipeline.addLast(new ServerBootstrapAcceptor(
<span style="color: #
currentChildGroup, currentChildHandler, currentChildOptions, currentChildAttrs));
<span style="color: #
<span style="color: #
<span style="color: #
  在init()中做了大致这么几件事:1,配置channel的option;2,配置channel的attr;3,ChannelPipeline增加两个Handler,一个是bootstrap中的私有handler,一个是ServerBootstrapAcceptor(这个Handler用于接收客户连接后设置其初始化参数)。
  【代码九主线】完成了init之后调用EventLoopGroup.register(channel)完成了channel的注册,实际上就是将channel注册到EventLoop中的selector上。这块我们可以了解一下其中的实现:
  先看一下EventLoopGroup接口:
(代码十一)1 public interface EventLoopGroup extends EventExecutorGroup {
<span style="color: #
<span style="color: #
<span style="color: #
EventLoop next();
<span style="color: #
<span style="color: #
ChannelFuture register(Channel channel);
<span style="color: #
<span style="color: #
ChannelFuture register(Channel channel, ChannelPromise promise);
<span style="color: #
  其中next方法返回EventLoopGroup里的一个EventLoop,register用于注册Channel到EventLoop里。【PS:EventLoopGroup顾名思义是EventLoop的group,即包含了一组EventGroup。在实际的业务处理中,EventLoopGroup会通过EventLoop next()方法选择一个 EventLoop,然后将实际的业务处理交给这个被选出的EventLoop去做。对于 NioEventLoopGroup来说,其真实功能都会交给EventLoopGroup去实现】
  我们详细看一下register到底如何实现的,往下看是在SingleThreadEventLoop里实现了该方法:  
(代码十二) 1 public abstract class SingleThreadEventLoop extends SingleThreadEventExecutor implements EventLoop {
public ChannelFuture register(Channel channel) {
return register(channel, new DefaultChannelPromise(channel, this));
public ChannelFuture register(final Channel channel, final ChannelPromise promise) {
<span style="color: #
if (channel == null) {
<span style="color: #
throw new NullPointerException("channel");
<span style="color: #
<span style="color: #
if (promise == null) {
<span style="color: #
throw new NullPointerException("promise");
<span style="color: #
<span style="color: #
<span style="color: #
channel.unsafe().register(this, promise);
<span style="color: #
<span style="color: #
<span style="color: #
<span style="color: #
  注意,在这里调用了Channel的Unsafe内部类完成了注册,因此接下来的东西都是NIO中的 【PS:Unsafe是定义在Channel中的内部接口,是不会被用户代码调用到的,但是在channel的I/O操作中实际上都是由unsafe来完成的。Unsafe不论是接口还是类,都会定义到channel的内部(例如Channel接口中定义了Unsafe接口,AbstractChannel抽象类中定义了AbstractUnsafe抽象类),因此如果将nio类比为一个linux系统的话,那么unsafe就是其中的内核空间】
  具体的register操作是在AbstractUnsafe中完成,在register()方法中调用了模板方法,我们看一下在AbstractNioChannel中的核心实现:
(代码十三) 1 @Override
2 protected void doRegister() throws Exception {
boolean selected = false;
for (;;) {
selectionKey = javaChannel().register(eventLoop().selector, 0, this);
} catch (CancelledKeyException e) {
if (!selected) {
<span style="color: #
eventLoop().selectNow();
<span style="color: #
selected = true;
<span style="color: #
<span style="color: #
<span style="color: #
<span style="color: #
<span style="color: #
<span style="color: #
<span style="color: # }
  这里实际上调用的是SelectableChannel中的register方法,作用就是将本channel注册到本channel的eventLoop的Selector中,那么问题又来了,什么是SelectableChannel?【PS:它实现Channel接口,代码注释说明其是一种可以被Selector使用用于多路复用的Channel,SelectableChannel可以通过 register方法将自己注册在Selector上,并提供其所关注的事件类型。因此,继承自SelectableChannel的Channel才可以真正和Selector打交道,例如ServerSocketChannel和SocketChannel】
  继续看其中的SelectableChannel中的实现:
(代码十四) 1 public final SelectionKey register(Selector sel, int ops,
Object att)throws ClosedChannelException{
synchronized (regLock) {
SelectionKey k = findKey(sel);
if (k != null) {
k.interestOps(ops);
k.attach(att);
<span style="color: #
if (k == null) {
<span style="color: #
// New registration
<span style="color: #
synchronized (keyLock) {
<span style="color: #
if (!isOpen())
<span style="color: #
throw new ClosedChannelException();
<span style="color: #
k = ((AbstractSelector)sel).register(this, ops, att);
<span style="color: #
addKey(k);
<span style="color: #
<span style="color: #
<span style="color: #
<span style="color: #
<span style="color: #
  这里的逻辑很清晰,如果该channel有在Selector中注册过(有对应的SelectionKey),那么将这个key强制绑定到入参的Channel中(可能会导致之前绑定失效),如果该channel没有在Selector中注册过,那么调用AbstractSelector(底层JDK实现)该register逻辑。至此我们完成了register逻辑代码的走读。
  继续回归【代码八主线】,我们已经完成了initAndRegister逻辑,如果不出意外那么regFuture.isDone()将是true,接下来调用了doBind0():
(代码十五) 1   private static void doBind0(
final ChannelFuture regFuture, final Channel channel,
final SocketAddress localAddress, final ChannelPromise promise) {
channel.eventLoop().execute(new Runnable() {
public void run() {
if (regFuture.isSuccess()) {
channel.bind(localAddress, promise).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
<span style="color: #
<span style="color: #
promise.setFailure(regFuture.cause());
<span style="color: #
<span style="color: #
<span style="color: #
<span style="color: #
  这里有必要了解一下ChannelPromise,它扩展了Promise和ChannelFuture,是一个可写入的ChannelFuture。我再在网上搜了很多资料里说它具备监听器的功能。但是我自己不这么认为,我们看Promise接口在future的基础上增加了setSuccess(), setFailure()这些方法,而ChannelFuture里success和failuer都是不可写的。为什么呢?从定义上来看,ChannelFuture本来就是异步执行的结果,既然已经异步了那么在返回的时候本来就无法确定其成功或者失败,而有的时候我们做校验或者写一些业务逻辑的时候可以确定其结果,因此我觉得ChannelPromise作为一个可写的ChannelFuture是对其的一个补充,可以标记异步任务成功或者失败,因此它是netty异步框架中实际使用的异步执行结果。在这里调用channel.bind(localAddress, promise);作用很明确就是给该channel绑定端口,然后该方法会立即返回一个ChannelPromise(不论这个实际的异步操作有没有做完)。一般用法也是这样的,方法定义时返回值都是ChannelFuture,而实现时实际返回的都是ChannelPromise。
  最后给立即返回的这个ChannelFuture添加一个listener。netty中有两种方式获取异步执行的真正结果,一种是调用老祖宗Future的get方法来获取(阻塞等待),一种是添加listener(异步回调),netty中推荐使用第二种方式,在整个的netty异步框架中也大量使用了这种方式。刚刚添加的那个listener的作用是:如果注册失败了,那么就关闭该Channel。最后bind返回异步的ChannelPromise,完成整个bind流程。
  至此【代码一主线】走读完毕,我们大致浏览了一遍server端bootstrap启动流程。
  最后大致总结一下服务端启动的主流程:
初始化boss和worker线程调度器NioEventLoopGroup,打开其中的Selector对象并配置相关参数。
ServerBootstrap绑定这两个NioEventLoopGroup。
为server端确定绑定Channel的class类型(即将要使用什么类型),在本文的例子中绑定的是NioServerSocketChannel,实质上只是初始化ChannelFactory。(此时还没有初始化该Channel,也没有为Selector注册该Channel)。
初始化用户定义的ChannelInitializer,也就是在ChannelPipeline中添加用户自己的ChannelHandler(此时还没有注册,只是初始化变量而已)。
调用bind(port)启动监听,整个bind的过程非常复杂,做了最核心的初始化工作:
    1) ChannelFactory生成核心的NioServerSocketChannel实例,为该Channel初始化参数,然后为NioServerSocketChannel的pipeline中再添加两个netty框架的Handler。
    2) 将NioServerSocketChannel实例绑定到boss线程调度器的Selector中,此时boss线程被激活并开始接受I/O请求,同时所有的Pipeline中的Handler也会完成注册。
    3) 异步为NioServerSocketChannel绑定注册的端口。
  至此,ServerBootstrap启动完毕,开始接收I/O请求。本文大致走读了一遍服务端启动的代码,在走读的过程中对一些概念进行解读,相信大家在大脑中对netty的基本成员已经有了一个轮廓。那么服务端启动之后,netty是如何接收并分发socket请求,pipeline中又是如何组织并调用handler,以及boss和worker如何协同工作将在下一篇博客中进行解读。
阅读(...) 评论()

我要回帖

更多关于 netty 客户端发送数据 的文章

 

随机推荐