五、Netty高性能结构设计

5.1、线程模型基本介绍

  1. 不同的线程模型,对程序的性能有很大影响。

  2. 目前存在的线程模型有:

    传统阻塞IO服务模型

    Reactor模式

  3. 根据Reactor的数量和处理资源池线程的数量不同,有3种典型的实现

    1. 单Reactor单线程
    2. 单Reactor多线程
  4. Netty线程模式(Netty注意基于主从Rectory多线程模型做了一定的改进,其中主从Reactor多线程模型有多个Reactor);

5.2、传统阻塞I/O服务模型

5.2.1、工作原理图

在这里插入图片描述

PS:

  1. 黄色的框表示对象,蓝色的框表示线程
  2. 白色的框表示方法(API)

5.2.2、模型特点

  1. 采用阻塞IO模式获取输入的数据
  2. 每个连接都需要独立的线程完成数据的输入,业务处理,数据返回

5.2.3、问题分析

  1. 当并发数很大,就会创建大量的线程,占用很大系统资源
  2. 连接创建后,如果当线程暂时没有数据可读,该线程会阻塞在read操作,造成线程资源浪费。

5.3、Reactor模式

5.3.1、针对传统阻塞IO服务模型的2个缺点,解决方案

  1. 基于I/O复用模型:多个连接共用一个阻塞对象,应用程序只需要在一个阻塞对象等待,无需阻塞等待所有连接。当某个连接有新的数据可以处理时,操作系统通知应用程序,线程从阻塞状态返回,开始进行业务处理,

    Reactor对应的叫法:1.反应器模式。2.分发者模式(Dispatcher)3.通知者模式(notifier)

  2. 基于线程池复用线程资源:不必再为每个连接创建线程,将连接完成后的业务处理任务分配给线程进行处理,一个线程可以处理多个连接的业务。

在这里插入图片描述

5.3.2、I/O复用结合线程池,就是Reactor模式基本设计思想

在这里插入图片描述

PS:

  1. Reactor模式,通过一个或多个输入同时传递给服务处理器的模式(基于事件驱动)
  2. 服务器端程序处理传入的多个请求,并将它们同步分派到相应的处理线程,因此Reactor模式也叫Dispatcher模式
  3. Reactor模式使用I复用监听事件,收到事件后,分发给某个线程(进程),这点就是网络服务器高并发处理关键

5.3.3、Reactor模式中核心组成

  1. Reactor:Reactor在单独的线程中运行,负责监听和分发事件,分发给合适的处理程序来对IO事件做出反应,它就像公司的电话接线员,它接听来自客户的电话并将线路转移到适当的联系人;
  2. Handlers:处理程序执行I/O事件要完成的实际事件,类似于客户想要与之交谈的公司中的实际官员。Reactor通过适当的处理程序来响应I/O事件,处理程序执行非阻塞操作。

5.3.4、Reactor模式分类

根据Reactor的数量和处理资源池线程的数量不同,有3种典型的实现

  1. 单Reactor单线程
  2. 当Reactor多线程
  3. 主从Reactor多线程

5.4、单Reactor单线程

在这里插入图片描述

5.4.1、方案说明

  1. Select 是前面I/O复用模型介绍的标准网络编程API,可以实现应用程序通过一个阻塞对象监听多路连接请求
  2. Reactor对象通过Select监控客户端请求事件,收到事件后通过Dispatch进行分发
  3. 如果是建立连接请求事件,则由Acceptor通过Accept处理连接请求,然后创建一个Handler对象处理连接完成后的后续业余处理
  4. 如果不是建立连接事件,则Reactor会分发调用连接对应的Handler来响应。
  5. Handler会完成Read->业务处理->Send的完整业务流程

结合实例:服务器端用一个线程通过多路复用搞定所有的IO操作(包括连接,读,写等),编码简单,清晰明了。但是如果客户端连接数量较多,将无法支撑,前面的NIO案例就属于这个模型。

5.4.2、方案优缺点分析

  1. 优点:模型简单,没有多线程、进程通信、竞争的问题,全部都在一个线程中完成。
  2. 缺点:性能问题,只有一个线程,无法完成发挥多核CPU的性能。Handler在处理某个连接上的业务时,整个进程无法处理其他连接事件,很容易导致性能瓶颈。
  3. 缺点:可靠性问题,线程意外终止,或者进人死循环,会导致整个系统通信模块不可用,不能接收和处理外部消息,造成节点故障
  4. 使用场景:客户端的数量有限,业务处理非常快速,比如Redis在业务处理的时间复杂度O(1)的情况。

5.5、单Reactor多线程

5.5.1、原理图

在这里插入图片描述

5.5.2、原理图小结

  1. Reactor对象通过selec监控客户端请求事件,收到事件后,通过dispatch进行分发
  2. 如果建立连接请求,则右Acceptor通过accept处理连接请求,然后创建一个Handler对象处理完成连接后的各种事件
  3. 如果不是连接请求,则由reactor分发调用连接对应的handler来处理
  4. handler只负责响应事件,不做具体的业务处理,通过read读取数据后,会分发给后面的worker线程池的某个线程处理业务
  5. worker线程池会分配独立线程完成真正的业务,并将结果返回给handler
  6. handler收到响应后,通过send将结果返回给client

5.5.3、方案优缺点分析

  1. 优点:可以充分的利用多核cpu的处理能力
  2. 缺点:多线程数据共享和访问比较复杂,Reactor处理所有的事件的监听和响应,在单线程运行,在高并发场景容易出现性能瓶颈。

5.6、主从Reactor多线程

5.6.1、工作原理图

针对单Reactor多线程模型中,Reactor在单线程中运行,高并发场景下容易成为性能瓶颈,可以让Reactor在多线程中运行。

在这里插入图片描述

5.6.2、原理图小结

  1. Reactor主线程MainReactor对象通过select监听连接事件,收到事件后,通过Acceptor处理连接事件
  2. Acceptor处理连接事件后,MainReactor将连接分配给SubReactor
  3. subreactor将连接加入到连接队列进行监听,并创建handler进行各种事件处理。
  4. 当有新事件发生时,subreator就会调用对应的handler处理。
  5. handler通过read读取数据,分发给后面的worker线程处理。
  6. worker线程池分配独立的worker线程进行业务处理,并返回结果
  7. handler收到响应的结果后,再通过send将结果返回给client
  8. Reactor主线程可以对应多个Reactor子线程,即MainReactor可以关联多个SubReactor

5.6.3、Scalable IO in Java对Multiple Reactors的原理图解

在这里插入图片描述

5.6.4、方案优缺点

  1. 优点:父线程与子线程的数据交互简单职责明确,父线程只需要接收新连接,子线程完成后续的业务处理。
  2. 优点:父线程与子线程的数据交互简单,Reactor主线程只需要把新连接传给子线程,子线程无需返回数据。
  3. 缺点:编程复杂度较高。
  4. 结合实例:这个模型在许多项目中广泛使用,包括Nginx主从Reactor多进程模型,Memcache主从多线程,Netty主从多线程模型的支持

5.7、Reactor模式小结

5.7.1、3种模式用生活案例来理解

  1. 单Reactor单线程,前台接待员和服务员是同一个人,全程为顾客服务
  2. 单Reactor多线程,1个前台接待员,多个服务员,接待员只负责接待
  3. 主从Reactor多线程,多个前台接待员,多个服务生

5.7.2、Reactor模式具有如下的优点

  1. 响应快,不必为单个同步时间所阻塞,虽然Reactor本身依然是同步的
  2. 可以最大程度的避免复杂的多线程及同步问题,并且避免了多线程/进程的切换开销
  3. 扩展性好,可以方便的通过增加Reactor实例个数来充分利用CPU资源
  4. 复用性好,Reactor模型本身与具体事件处理逻辑无关,具有很高的复用性。

5.8、Netty模型

5.8.1、工作原理示意图-简单版

Netty主要基于主从Reactor多线程模型做了一定的改进,其中主从Reactor多线程模型有多个Reactor

在这里插入图片描述

5.8.2、对上图说明

  1. BossGroup线程维护Selector,只关注Accepcpt
  2. 当接收到Accept事件,获取到对应的SocketChannel,封装成NIOSocketChannel并注册到Worker线程(事件循环),并进行维护
  3. 当worker线程监听到selector中通道发生自己感兴趣的事件后,就进行处理(就由handler),注意handler已经进入通道。

5.8.3、工作原理示意图-进阶版

在这里插入图片描述

5.8.4、工作原理示意图-详细版

在这里插入图片描述

5.8.5、对上图的说明小结

  1. Netty抽象出两组线程池BossGroup专门负责接收客户端的连接,WorkerGroup专门负责网路的读写
  2. BossGroup和WorkerGroup类型都是NioEventLoopGroup
  3. NioEventLoopGroup相当于一个事件循环组,这个组这含有多个事件循环,每一个事件循环是NioEventLoop
  4. NioEventLoop表示一个不断循环的执行处理任务的线程,每个NioEventLoop都有一个selector,用于监听绑定在其上的socket的网络通讯
  5. NioEventLoopGroup可以有多个线程,即可以含有多个NioEventLoop
  6. 每个BossNioEventLoop循环执行的步骤有3步
    • 轮询accept事件
    • 处理accept事件,与client建立连接,生成NioSocketChannel,并将其注册到worker NIOEventLoop上的selector
    • 处理任务队列的任务,即runAllTasks
  7. 每个Worker NIOEventLoop循环执行的步骤
    • 轮询read,write事件
    • 处理io事件,即read,write事件,在对应NioSocketChannel处理
    • 处理任务队列的任务,即runAllTasks
  8. 每个Worker NIOEventLoop 处理业务时,会使用pipeline(管道),pipeline中包含了channel,即通过pipeline可以获取到对应通道,管道中维护了很多的处理器

5.8.6、Netty快速入门实例-tcp服务

  1. Netty服务器在6668端口监听,客户端能发送消息给服务器 “hello,服务器”

  2. 服务器可以回复消息给客户端 “hello,客户端”

  3. 目的:对Netty线程模型有一个初步认识,便于理解Netty模型理论

    package com.feng.netty.simple;
    import io.netty.bootstrap.ServerBootstrap;
    import io.netty.channel.ChannelFuture;
    import io.netty.channel.ChannelInitializer;
    import io.netty.channel.ChannelOption;
    import io.netty.channel.EventLoopGroup;
    import io.netty.channel.nio.NioEventLoopGroup;
    import io.netty.channel.socket.SocketChannel;
    import io.netty.channel.socket.nio.NioServerSocketChannel;
    public class NettyServer {    
        public static void main(String[] args) throws InterruptedException {        
            //创建BossGroup和WorkerGroup        
            //说明        
            //1.创建两个线程组bossGroup 和 workerGroup        
            //2.bossGroup 只是处理连接请求,真正的客户端业务处理,会交给workerGroup完成        
            //3.两个都是无限循环        
            EventLoopGroup bossGroup = new NioEventLoopGroup();        
            EventLoopGroup workerGroup =new NioEventLoopGroup();        
            try {            
                //创建服务器端的启动对象,配置参数            
                ServerBootstrap bootstrap = new ServerBootstrap();            
                //使用链式编程来进行设置            
                bootstrap.group(bossGroup,workerGroup)//设置两个线程组                    
                    .channel(NioServerSocketChannel.class)//使用NioSocketChannel作为服务器的通道实现           
                    .option(ChannelOption.SO_BACKLOG,128)//设置线程队列得到连接个数                    
                    .childOption(ChannelOption.SO_KEEPALIVE,true)//设置保持活动连接状态                    
                    .childHandler(new ChannelInitializer<SocketChannel>() {                        
                        @Override                        
                        protected void initChannel(SocketChannel ch) throws Exception {                   
                            ch.pipeline().addLast(new NettyServerHandler());                        
                        }                    
                    });
                //            
                System.out.println("...服务器 is ready...");            
                //绑定一个端口并且同步,生成了一个chanelFuture            
                ChannelFuture cf = bootstrap.bind(6668).sync();            
                //对关闭通道进行监听            
                cf.channel().closeFuture().sync();        
            } finally {            
                bossGroup.shutdownGracefully();            
                workerGroup.shutdownGracefully();        
            }    
        }
    }
    
    package com.feng.netty.simple;
    import io.netty.buffer.ByteBuf;
    import io.netty.buffer.Unpooled;
    import io.netty.channel.Channel;
    import io.netty.channel.ChannelHandlerContext;
    import io.netty.channel.ChannelInboundHandlerAdapter;
    import io.netty.channel.ChannelPipeline;
    import io.netty.util.CharsetUtil;
    public class NettyServerHandler extends ChannelInboundHandlerAdapter {    
        /**     
        * 读取数据(这里我们可以读取客户端发送的消息)     
        * @param ctx 上下文对象,含有管道pipeline,管道channel,地址    
        * @param msg 就是客户端发送的数据,默认Object     
        */    
        @Override    
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {        
            System.out.println("服务器读取线程:"+Thread.currentThread().getName());        
            System.out.println("server ctx="+ctx);        
            ChannelPipeline pipeline =ctx.pipeline();
            //本质是一个双向链表,出站入站        
            Channel channel = ctx.channel();        
            //ByteBuf是Netty提供的,不是NIO的ByteBuffer        
            ByteBuf byteBuf =(ByteBuf) msg;        
            System.out.println("客户端发送的消息:"+byteBuf.toString(CharsetUtil.UTF_8));        
            System.out.println("客户端地址:"+channel.remoteAddress());    
        }    
        /**     
        * 数据读取完毕     
        * @param ctx 上下文对象,含有管道pipeline,管道channel,地址     
        */    
        @Override    
        public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {        
            //将数据写人到缓存,并刷新        
            //一般讲,我们对这个发送的数据进行编码        
            ctx.writeAndFlush(Unpooled.copiedBuffer("hello,客户端(>^ω^<)喵",CharsetUtil.UTF_8));    
        }    
        /**     
        * 处理异常,一般是需要关闭通道     
        */    
        @Override    
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {       
            ctx.close();    
        }
    }
    
    package com.feng.netty.simple;
    import io.netty.bootstrap.Bootstrap;
    import io.netty.channel.Channel;
    import io.netty.channel.ChannelFuture;
    import io.netty.channel.ChannelInitializer;
    import io.netty.channel.EventLoopGroup;
    import io.netty.channel.nio.NioEventLoopGroup;
    import io.netty.channel.socket.SocketChannel;
    import io.netty.channel.socket.nio.NioSocketChannel;
    public class NettyClient {    
        public static void main(String[] args) throws InterruptedException {        
            //客户需要一个事件循环组        
            EventLoopGroup group = new NioEventLoopGroup();        
            try {            
                //创建客户端启动对象            
                Bootstrap bootstrap =new Bootstrap();            
                //设置相关参数           
                bootstrap.group(group)//设置线程组                    
                    .channel(NioSocketChannel.class)//设置客户端通道的实现类(反射)                    
                    .handler(new ChannelInitializer<SocketChannel>() {                       
                        @Override                        
                        protected void initChannel(SocketChannel socketChannel) throws Exception {       
                            socketChannel.pipeline().addLast(new NettyClientHandler());                   
                        }                    
                    });            
                System.out.println("客户端 ok..");            
                //启动客户端去连接服务器端            
                //关于channelFuture要分析,涉及到netty都得异步模型           
                ChannelFuture channelFuture = bootstrap.connect("127.0.0.1",6668).sync();            
                //给关闭通道进行监听            
                channelFuture.channel().closeFuture().sync();        
            } finally {            
                group.shutdownGracefully();        
            }    
        }
    }
    
    package com.feng.netty.simple;
    import io.netty.buffer.ByteBuf;
    import io.netty.buffer.Unpooled;
    import io.netty.channel.ChannelHandlerContext;
    import io.netty.channel.ChannelInboundHandlerAdapter;
    import io.netty.util.CharsetUtil;
    /** 
    * 客户端 
    * @author cpms 
    */
    public class NettyClientHandler extends ChannelInboundHandlerAdapter {    
        /**     
        * 当通道就绪就会触发该方法     
        * @param ctx 上下文,     
        */    
        @Override    
        public void channelActive(ChannelHandlerContext ctx) throws Exception {        
            System.out.println("client "+ctx);        
            ctx.writeAndFlush(Unpooled.copiedBuffer("hello.server:(>^ω^<)喵", CharsetUtil.UTF_8));    
        }    
        /**     
        * 当通道有读取事件时,会触发     
        * @param ctx 上下文     
        * @throws Exception     
        */    
        @Override    
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {        
            ByteBuf byteBuf = (ByteBuf) msg;        
            System.out.println("服务器回复的消息:"+byteBuf.toString(CharsetUtil.UTF_8));        
            System.out.println("服务器的地址"+ctx.channel().remoteAddress());    }   
        @Override    
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {       
            cause.printStackTrace();        
            ctx.close();    
        }
    }
    

5.8.7、任务队列中的Task有3种典型使用场景

  1. 用户程序自定义的普通任务

  2. 用户自定义定时任务

  3. 非当前Reactor线程调用Channel的各种方法。例如在推送系统的业务线程里面,根据用户的标识,找到对应的Channel引用,然后调用Write类方法向该用户推送消息,就会进入到这种场景。最终的Write会提交到任务队列中后被异步消费

  4. 代码演示

    package com.feng.netty.simple;
    import io.netty.buffer.ByteBuf;
    import io.netty.buffer.Unpooled;
    import io.netty.channel.Channel;
    import io.netty.channel.ChannelHandlerContext;
    import io.netty.channel.ChannelInboundHandlerAdapter;
    import io.netty.channel.ChannelPipeline;
    import io.netty.util.CharsetUtil;
    import java.util.concurrent.TimeUnit;
    public class NettyServerHandler extends ChannelInboundHandlerAdapter {    
        /**     
        * 读取数据(这里我们可以读取客户端发送的消息)     
        * @param ctx 上下文对象,含有管道pipeline,管道channel,地址    
        * @param msg 就是客户端发送的数据,默认Object     
        */    
        @Override    
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {        
            //比如这里我们有一个非常耗时长的业务->异步执行->提交该channel对应的        
            //NIOEventLoop 的taskQueue中,        
            //解决方法1 用户程序自定义的普通任务        
            ctx.channel().eventLoop().execute(new Runnable() {            
                @Override            
                public void run() {                
                    try{                    
                        Thread.sleep(10*1000);                    
                        ctx.writeAndFlush(Unpooled.copiedBuffer("hello,客户端,汪1",CharsetUtil.UTF_8));          			  System.out.println("channel code=" +ctx.channel().hashCode());                
                    }catch (Exception e){                    
                        e.printStackTrace();                
                    }            
                }        
            });        
            //用户自定义定义任务-> 该任务是提交到scheduleTaskQueue中        
            ctx.channel().eventLoop().schedule(new Runnable() {            
                @Override            
                public void run() {                
                    try{                    
                        Thread.sleep(10*1000);                    
                        ctx.writeAndFlush(Unpooled.copiedBuffer("hello,客户端,汪2",CharsetUtil.UTF_8));                    
                        System.out.println("channel code=" +ctx.channel().hashCode());                
                    }catch (Exception e){                    
                        e.printStackTrace();                
                    }            
                }        
            },5, TimeUnit.SECONDS);        
            System.out.println("go on ...");       
            /*        
            System.out.println("服务器读取线程:"+Thread.currentThread().getName());        
            System.out.println("server ctx="+ctx);       
            ChannelPipeline pipeline =ctx.pipeline();//本质是一个双向链表,出站入站        
            Channel channel = ctx.channel();        
            //ByteBuf是Netty提供的,不是NIO的ByteBuffer        
            ByteBuf byteBuf =(ByteBuf) msg;       
            System.out.println("客户端发送的消息:"+byteBuf.toString(CharsetUtil.UTF_8));        
            System.out.println("客户端地址:"+channel.remoteAddress());       
            */    
        }    
        /**     
        * 数据读取完毕     
        * @param ctx 上下文对象,含有管道pipeline,管道channel,地址     
        */    
        @Override    
        public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {        
            //将数据写人到缓存,并刷新        
            //一般讲,我们对这个发送的数据进行编码        
            ctx.writeAndFlush(Unpooled.copiedBuffer("hello,客户端(>^ω^<)喵",CharsetUtil.UTF_8));    }    
        /**     
        * 处理异常,一般是需要关闭通道     
        */    
        @Override    
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {       
            ctx.close();    
        }
    }
    

5.8.8、方案再说明

  1. Netty抽象出两组线程池,BossGroup专门负责接收客户端连接,WorkerGroup 专门负责网络读写操作。
  2. NioEventLoop表示一个不断循环执行处理任务的线程,每个NioEventLoop都有一个selector,用于绑定在其上的socket网络通道。
  3. NioEventLoop内部采用串行化设计,从消息的读取->解码->处理->编码->发送,始终由IO线程NioEventLoop负责
  4. NioEventLoopGroup下包含多个NioEventLoop
    • 每个NioEventLoop中包含有一个Selector,一个taskQueue
    • 每个NioEventLoop的Selector上可以注册监听多个NioChannel
    • 每个NioChannel只会绑定在唯一的NioEventLoop上
    • 每个NioChannel都绑定有一个自己的ChannelPipeline

5.9、异步模型

5.9.1、基本介绍

  1. 异步的概念和同步相对。当一个异步过程调用发出后,调用者不能立刻得到结果。实际处理这个调用的组件在完成后,通过状态,通知和回调来通知调用者。
  2. Netty中的I\O操作是异步的,包括Bing,Write,Connect等操作会简单的返回一个ChannelFuture
  3. 调用者并不能立刻获得结果,而是通过Future-Listener机制,用户可以方便的主动获取或者通过通知机制获得IO操作结果
  4. Netty的异步模型是建立在Future和callback的之上的。callback就是回调。重点说Future,它的核心思想是:假设一个方法fun,计算过程可能非常耗时,等待fun返回显然不合适,那么可以在调用fun的时候,立马返回一个Future,后续可以通过Future去监控方法fun的处理过程(即:Future-Listenr机制)

5.9.2、Future说明

  1. 表示异步的执行结果,可以通过它提供的方法来检测执行是否完成,比如检索计算等等。
  2. ChannelFuture是一个接口,public interface Channel extends Future,我们可以添加监听器,当监听的事件发生时,就会通知到监听器,

5.9.3、工作原理示意图

在这里插入图片描述

PS

  1. 在使用Netty进行编程时,拦截操作和转换出入站数据只需要您提供callback或利用future即可。这使得链式操作简单、高效、并有利于编写可重用的、通用的代码。
  2. Netty框架的目标就是让你的业务逻辑从网络基础应用编码中分离出来,解脱出来

5.9.4、Future-Listener机制

  1. 当Future对象刚刚创建时,处于非完成状态,调用者可以通过返回的ChannelFuture来获取操作执行的状态,注册监听函数来执行完成后的操作

  2. 常见操作如下

    • 通过isDone方法来判断当前操作是否完成;
    • 通过isSuccess方法来判断已完成的当前操作是否成功;
    • 通过getCause方法来获取已完成的当前操作失败的原因;
    • 通过isCancelled 方法来判断已完成的当前操作是否被取消
    • 通过addListener方法来注册监听器,当操作已完成(isDone方法返回完成),将会通知指定的监听器;如果future对象已完成,则通过指定的监听器。
  3. 举例说明:

    ChannelFuture cf = bootstrap.bind(6668).sync();
              cf.addListener(new ChannelFutureListener() {
                  @Override
                  public void operationComplete(ChannelFuture channelFuture) throws Exception {
                      if (cf.isSuccess()){
                          System.out.println("监听端口6668成功");
                      }else {
                          System.out.println("监听端口6668失败");
                      }
                  }
              });
    

5.10、快速入门实例-HTTP服务

  1. Netty服务器在6668端口监听,浏览器发出请求
  2. 服务器可以回复消息给客户端,并对特定请求资源进行过滤
package com.feng.netty.http;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
public class TestServer {    
    public static void main(String[] args) throws Exception {        
        EventLoopGroup bossGroup = new NioEventLoopGroup();        
        EventLoopGroup workerGroup =new NioEventLoopGroup();        
        try {            
            ServerBootstrap serverBootstrap= new ServerBootstrap();            
            serverBootstrap.group(bossGroup,workerGroup)
                .channel(NioServerSocketChannel.class)                 
                .childHandler(new TestServerInitializer());            
            ChannelFuture channelFuture = serverBootstrap.bind(6688).sync();            
            channelFuture.channel().closeFuture().sync();        
        }finally {            
            bossGroup.shutdownGracefully();            
            workerGroup.shutdownGracefully();        
        }    
	}
}

package com.feng.netty.http;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpServerCodec;

public class TestServerInitializer extends ChannelInitializer<SocketChannel> {    
    @Override    
    protected void initChannel(SocketChannel ch) throws Exception {        

        //向管道加入处理器        
        //得到管道        
        ChannelPipeline pipeline = ch.pipeline();       
        //加入一个netty提供的httpServerCodec codec =>[coder - decoder]       
        //HttpServerCodec说明       
        //1.HttpServerCodec是netty提供的http的编解码器        
        pipeline.addLast("MyHttpServerCodec",new HttpServerCodec());        
        //2.增加一个自定义的handler        
        pipeline.addLast("MyTestHttpServerHandler",new TestHttpServerHandler());    

    }

}
package com.feng.netty.http;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import java.net.URI;
/** 
* ps: 
* 1. SimpleChannelInboundHandler是ChannelInboundHandlerAdapter的子类 
* 2. HttpObject:客户端和服务器端互相通讯的数据被封装成HttpObject 
*/
public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {    
    /**     
	* 读取客户端数据     
	* @param ctx 上下文     
	* @param msg 消息    
	*/    
    @Override    
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {        
        //判断msg是不是HttpRequest请求        
        if (msg instanceof HttpRequest){            
            System.out.println("pipeline hashcode="+ctx.pipeline().hashCode());           
            System.out.println("msg 类型="+msg.getClass()
          );            
        System.out.println("客户端地址"+ctx.channel().remoteAddress());           
            //获取到            HttpRequest httpRequest = (HttpRequest) msg;            
            //获取uri,过滤指定资源            
            URI uri = new URI(httpRequest.uri());            
            if ("/favicon.ico".equals(uri.getPath())){               
                System.out.println("请求了 favicon.ico,不做相应响应");                
                return;            
            }            
            //回复信息给浏览器【http协议】            
            ByteBuf content = Unpooled.copiedBuffer("hello,我是服务器", CharsetUtil.UTF_8);           
            //构造一个http的响应。即HttpResponse            
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,                    HttpResponseStatus.OK, content);            
            //设置内容类型            
            response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain;charset=utf-8");            
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH,content.readableBytes());            
            //将构建好 response 返回            
            ctx.writeAndFlush(response);        
        }    
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值