05 Netty高性能架构设计(重点)

1、线程模型基本介绍

在这里插入图片描述

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

示意图

在这里插入图片描述

模型特点

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

问题分析

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

1.2Reactor模式

改进

针对传统阻塞I/O服务模型的2个缺点,解决方案:

  • 基于I/o复用模型:多个连接共用一个阻塞对象,应用程序只需要在一个阻塞对象等待,无须阻塞等地所有连接。当某个连接由新的数据可以处理时,操作系统通知应用程序,线程从阻塞状态返回,开始进行业务处理
  • 基于线程池复用线程资源:不必再为每个链接创建线程,将连接完成后的业务处理任务分配给线程进行处理,一个线程可以处理多个连接的任务

在这里插入图片描述

复用+结合此线程池 ,就是Reactor模式基本设计思想,如图

在这里插入图片描述

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

Reactor模式中的核心组成

在这里插入图片描述

Reactor模式分类:

在这里插入图片描述

单Reactor单线程

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

单Reactor多线程

在这里插入图片描述

  • Reactor对象通过对select监控客户端请求事件,收到事件后,通过Dispatcher分发
  • 如果建立连接请求,则由Acceptor通过accrpty处理联结请求,然后创建一个Handler对象处理完成连接后的各种操作
  • 如果不是连接请求则由reactor分发调用连接对应的handler来处理
  • handler只负责响应事件,不做具体的业务处理,通过read读取数据后,会分发给后面的worjker线程池中的某个线程处理业务
  • worker线程池会分配给独立线程完成真正的业务,并将结果返回给handler
  • handler收到响应后,通过send将结果返回给client

在这里插入图片描述

主从Reactor多线程

在这里插入图片描述
在这里插入图片描述

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

在这里插入图片描述

Reactor模式小结

在这里插入图片描述
在这里插入图片描述

Netty模型

简单版

Netty主要基于主从Reacot多线程模型做了一定的选择,其中主从Reacot多线程模型有多个Reacot
在这里插入图片描述

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

进阶版

在这里插入图片描述

详细版

在这里插入图片描述

  • Netty抽象出两组线程池BossGoup专门负责接收客户端的连接,Worker专门负责网络的读写

  • BossGroupWorkerGroup类型都是NioEnventLoopGroup

  • NioEnventLoopGroup相当于一个事件循环组,这个组含有多个事件循环,每一个事件循环是NioEventLoopp

  • NioEnventLoop表示一个不断循环的执行处理任务的线程,每个NioEnventLoop都有一个Selector,用于监听绑定在其上的sockety的网络通讯

  • NioEnventLoopGroup可以有多个线程,既可以含有多个NioEventLoop

  • 每个Boss NioEnvenetLoop循环执行的步骤有3步:
    - 轮询accept事件
    - 处理accept事件,与client监理连接,生成NioSocketChannel,并将其注册到某个Worker NIOEventLoop上的Selector
    - 出路任务队列的任务,即runAllTasks

  • 每个Workert NioEventLoop循环执行的步骤
    - 轮询readwrite事件
    - 处理I/O事件,即read、write事件,在对应NioSocjetChannel处理
    - 处理任务队列的任务,即runAllTasks

  • 每个WorkerNIOEventLoop处理业务时,会使用PipeLine(管道)PipeLine中包含了Channel,即通过pipeLine可以获取对应通道,管道中维护了很多处理器

Netty快速入门实例TCP服务

在这里插入图片描述
参考 参考链接

代码

服务daunt


package Netty.base;

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;


/**
 * @Author Zhou  jian
 * @Date 2020 ${month}  2020/6/6 0006  11:56
 * 参考 https://netty.io/wiki/user-guide-for-4.x.html
 */
public class NettyServer {

    public static void main(String[] args) throws InterruptedException {

        //创建bossgroup和workerGROUP
        //创建两个线程组
        //2、bossGroup只是处理联结请求,he first one, often called 'boss', accepts an incoming connection
        // 真正的和客户端业务处理会交给workerGroup
        //3、两个都是循环
        //bossGroup和workergroup含有的子线程(NioEnventLoop)的个默认是
        //CPU的核数*2
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {


            //创建服务器端启动的配置参数
            ServerBootstrap bootstrap = new ServerBootstrap();

            //使用链式编程来进行设置、
            bootstrap.group(bossGroup,workerGroup)//设置两个线程组
                     .channel(NioServerSocketChannel.class)//使用NioSocektyChannel作为服务器的通道实现
                    .option(ChannelOption.SO_BACKLOG,128)//设置线程队列的连接个数
                    .childOption(ChannelOption.SO_KEEPALIVE,true)//设置保持活动联结状态
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                       //给pipeline设置处理器
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new NettyServerHandler());
                        }//创建一个通道测试对象
                    });//给workergroup的EnventLoop对应的管道设置处理器


            System.out.println("服务器is readey");

            //绑定一个端口并且同步,生成一个ChannelFuture对象
            //启动服务器(并绑定端口)
            ChannelFuture cf = bootstrap.bind(6668).sync();

            //对关闭通道进行监听
            // Wait until the server socket is closed.
            // In this example, this does not happen, but you can do that to gracefully
            // shut down your server.

            cf.channel().closeFuture().sync();

        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }
}
=======================
//
package Netty.base;

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;



/**
 * @Author Zhou  jian
 * @Date 2020 ${month}  2020/6/6 0006  12:11

    1、说明自定义一个Handler需要继承Netty规定好的HandlerAdapter
    2、这时我们自定义一个Handler,才能成为一个handler
 */
public class NettyServerHandler extends ChannelInboundHandlerAdapter {


    //读取数据实际(这里我们可以读取客户端发送的消息)

    /**
     *
     * @param ctx   上下文对象;含有管道 pipelINE 通道channel
     * @param msg   客户端发送的数据 默认object
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("server ctx="+ctx);
        System.out.println("看看Channel和pipeLine的关系");
        Channel channel = ctx.channel();
        ChannelPipeline pipeline = ctx.pipeline();//本质是一个双向链表,设计到出栈

        //将我们的msg转成一个bytebuffer
        //这个ByteBuf提供的,不是NIO提供的ByteBuffer
        ByteBuf buf = (ByteBuf)msg;
        System.out.println("客户端发送消息是"+buf.toString(CharsetUtil.UTF_8));
        System.out.println("客户端地址:"+ctx.channel().remoteAddress());
    }

    //读取数据完毕会送消息
    @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.channel().close();
    }
}

客户端

package Netty.base;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;

import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;


/**
 * @Author Zhou  jian
 * @Date 2020 ${month}  2020/6/6 0006  12:21
 */
public class NettyClient {

    public static void main(String[] args) throws InterruptedException {
        //客户端需要一个事件循环组
        NioEventLoopGroup group= new NioEventLoopGroup();


        try {

            //创建客户端启动对象
            //注意客户端使用的不是ServerBootstrap而是bootstrap
            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("客户dauntis OK");
            //启动客户端
            System.out.println("客户端 ok.....");

            //启动客户单取连接服务器端
            //关于ChannelFuture要分析,涉及到netty的异步
            ChannelFuture sync = bootstrap.connect("127.0.0.1", 6668).sync();

            //给关闭通道进行监听
            sync.channel().closeFuture().sync();
        }finally {
            group.shutdownGracefully();

        }




    }
}
//
/

package Netty.base;

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 Zhou  jian
 * @Date 2020 ${month}  2020/6/6 0006  12:30
 */
public class NettyClientHandler extends ChannelInboundHandlerAdapter {

    //当通道就绪就会触发该方法
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        System.out.println("client"+ctx);
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello,server:描", CharsetUtil.UTF_8));

    }

    //当通道有读取事件时,会触发
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf)msg;
        System.out.println("服务器回复的消息:"+buf.toString(CharsetUtil.UTF_8));
        System.out.println("服务器的地址: "+ctx.channel().remoteAddress());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}

任务队列中的Task有三种典型使用场景

  • 用户程序自定义的普通任务
  • 用户自定义定时任务
  • 非当前Reactor线程调用Channel的各种方法

  //解决方案1:用户自定义普通任务
        //拿到enventLoop使用内置的taskQueue
        ctx.channel().eventLoop().execute(new Runnable() {
            @Override
            public void run() {
                //比如这里有一个非常耗时的业务---》异步执行---》提交该channel
                try {
                    Thread.sleep(10*1000);
                    ctx.writeAndFlush(Unpooled.copiedBuffer("hello ,客户端,222222",CharsetUtil.UTF_8));

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });




        //用户自定义定时任务---》该任务提交到scheduleTaskQueue中
        ctx.channel().eventLoop().schedule(new Runnable() {
            @Override
            public void run() {
                //比如这里有一个非常耗时的业务---》异步执行---》提交该channel
                try {
                    Thread.sleep(10*1000);
                    ctx.writeAndFlush(Unpooled.copiedBuffer("hello ,客户端,定时任务",CharsetUtil.UTF_8));

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },5, TimeUnit.SECONDS);


异步模型

基本介绍

在这里插入图片描述

Future说明

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

Future-Listen机制

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

  • 常见的操作右如下:

    -

   //绑定一个端口并且同步,生成一个ChannelFuture对象
           //启动服务器(并绑定端口)
           final ChannelFuture cf = bootstrap.bind(6668).sync();


           //给cf注册人监听器,监控我们关心的时间
           cf.addListener(new ChannelFutureListener() {
               @Override
               public void operationComplete(ChannelFuture channelFuture) throws Exception {
                   if(cf.isSuccess()){
                       System.out.println("监听端口66668成功");
                   }else{
                       System.out.println("监听端口66668失败");

                   }
               }
           });

快速入门实例-Http服务

在这里插入图片描述


package Netty.http;

import Netty.base.NettyServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @Author Zhou  jian
 * @Date 2020 ${month}  2020/6/7 0007  13:46
 */
public class TestServer {
    public static void main(String[] args) {
        //创建bossgroup和workerGROUP
        //创建两个线程组
        //2、bossGroup只是处理联结请求,he first one, often called 'boss', accepts an incoming connection
        // 真正的和客户端业务处理会交给workerGroup
        //3、两个都是循环
        //bossGroup和workergroup含有的子线程(NioEnventLoop)的个默认是
        //CPU的核数*2
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();


        try {

            //创建服务器端启动的配置参数
            ServerBootstrap bootstrap = new ServerBootstrap();

            //使用链式编程来进行设置、
            bootstrap.group(bossGroup,workerGroup)//设置两个线程组
                    .channel(NioServerSocketChannel.class)//使用NioSocektyChannel作为服务器的通道实现
                    .childHandler(new TestServerInitializer());//给workergroup的EnventLoop对应的管道设置处理器




            //绑定一个端口并且同步,生成一个ChannelFuture对象
            //启动服务器(并绑定端口)
            final ChannelFuture cf = bootstrap.bind(8818).sync();



            //对关闭通道进行监听
            // Wait until the server socket is closed.
            // In this example, this does not happen, but you can do that to gracefully
            // shut down your server.

            cf.channel().closeFuture().sync();


        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }


    }
}



package 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;


/**
 * @Author Zhou  jian
 * @Date 2020 ${month}  2020/6/7 0007  13:46
 */
public class TestServerInitializer extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        //向管道加入处理器
        //得到管道
        ChannelPipeline pipeline = socketChannel.pipeline();
        //加入netty提供的httpServerCodec
        //netty提供的一个处理http编解码器
        pipeline.addLast("MyHttpServerCodec",new HttpServerCodec());
        //自定义一个handler
        pipeline.addLast("MyTestHttpServerHandler",new TestHttphandler());
    }
}



package 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;

/**
 * @Author Zhou  jian
 * @Date 2020 ${month}  2020/6/7 0007  13:54
 */
public class TestHttphandler  extends SimpleChannelInboundHandler<HttpObject> {

    //channelRead0读取客户端数据
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {

        //判断msg是不是httprequest请求
        if(msg instanceof HttpRequest){
            System.out.println("msg类型="+msg.getClass());
            System.out.println("客户端地址"+ctx.channel().remoteAddress());



            //对特定的资源进行过滤
            //获取到msg发送的请求协议
            HttpRequest httpRequest = (HttpRequest)msg;
            //获取uri
            URI uri = new URI(httpRequest.uri());
            if(uri.getPath().equals("/favicon.ico")){
                System.out.println("请求了图标");
                return;
            }



            //恢复信息给浏览器[http协议】
            ByteBuf content = Unpooled.copiedBuffer("hello,我是服务器", CharsetUtil.UTF_8);
            //构造一个http的响应,即httpresonse
          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());

            //将构建号的resppnse返回
            ctx.writeAndFlush(response);

        }



    }
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值