Netty框架简单使用

1.概述:

    Netty 是由 JBOSS 提供的一个 Java 开源框架。Netty 提供异步的、基于事件驱动的网络应用程序框架,用以快速开发高性能、高可靠性的网络 IO 程序。
           Netty 是一个基于 NIO 的网络编程框架,使用 Netty 可以帮助你快速、简单的开发出一 个网络应用,相当于简化和流程化了 NIO 的开发过程。
            作为当前最流行的 NIO 框架,Netty 在互联网领域、大数据分布式计算领域、游戏行业、 通信行业等获得了广泛的应用,知名的 Elasticsearch 、Dubbo 框架内部都采用了 Netty。

2.Netty的整体设计

2.1 线程模型

 1.单线程模型

 

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

2.线程池模型

服务器端采用一个线程专门处理客户端连接请求,采用一个线程池负责 IO 操作。在绝 大多数场景下,该模型都能满足使用。

3.Netty模型

 

比较类似于上面的线程池模型,Netty 抽象出两组线程池,BossGroup 专门负责接收客 户端连接,WorkerGroup 专门负责网络读写操作。NioEventLoop 表示一个不断循环执行处理 任务的线程,每个 NioEventLoop 都有一个 selector,用于监听绑定在其上的 socket 网络通道。 NioEventLoop 内部采用串行化设计,从消息的读取->解码->处理->编码->发送,始终由 IO 线 程 NioEventLoop 负责。

  • 一个 NioEventLoopGroup下包含多个 NioEventLoop
  • 每个 NioEventLoop 中包含有一个 Selector,一个 taskQueue
  • 每个 NioEventLoop 的 Selector 上可以注册监听多个 NioChannel
  • 每个 NioChannel 只会绑定在唯一的 NioEventLoop 上
  • 每个 NioChannel 都绑定有一个自己的 ChannelPipeline

2.2 异步模型

FUTURE, CALLBACK 和 HANDLER
Netty 的异步模型是建立在 future和callback的之上的。callback 大家都比较熟悉了,这 里重点说说 Future,它的核心思想是:假设一个方法 fun,计算过程可能非常耗时,等待 fun 返回显然不合适。那么可以在调用 fun 的时候,立马返回一个 Future,后续可以通过 Future 去监控方法 fun 的处理过程。 在使用 Netty 进行编程时,拦截操作和转换出入站数据只需要您提供 callback 或利用 future 即可。这使得链式操作简单、高效, 并有利于编写可重用的、通用的代码。Netty 框 架的目标就是让你的业务逻辑从网络基础应用编码中分离出来、解脱出来。

Netty的核心api:

  • ChannelHandler及其实现类

ChannelHandler接口定义了许多事件处理的方法,我们可以通过重写这些方法去实现具 体的业务逻辑。API关系如下图所示:

我们经常需要自定义一个Handler类去继承ChannelInboundHandlerAdapter,然后通过 重写相应方法实现业务逻辑我们接下来看看一般都需要重写哪些方法:

  1. public void channelActive(ChannelHandlerContext ctx),通道就绪事件
  2. public void channelRead(ChannelHandlerContext ctx, Object msg),通道读取数据事件
  3. public void channelReadComplete(ChannelHandlerContext ctx) ,数据读取完毕事件
  4. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause),通道发生异常事件
  • Pipeline和ChannelPipeline

ChannelPipeline是一个Handler的集合,它负责处理和拦截 inbound或者outbound 的事 件和操作,相当于一个贯穿Netty的链。

  1. ChannelPipeline addFirst(ChannelHandler... handlers),把一个业务处理类(handler)添加 到链中的第一个位置
  2. ChannelPipeline addLast(ChannelHandler... handlers),把一个业务处理类(handler)添加 到链中的最后一个位置
  • ChannelHandlerContext 

这是事件处理器上下文对象,Pipeline链中的实际处理节点。每个处理节点ChannelHandlerContext中包含一个具体的事件处理器ChannelHandler,同时ChannelHandlerContext中也绑定了对应的pipeline和Channel的信息,方便对ChannelHandler进行调用。常用方法如下所示:

  1. ChannelFuture close(),关闭通道
  2. ChannelOutboundInvoker flush(),刷新
  3. ChannelFuture writeAndFlush(Object msg),将数据写到ChannelPipeline中当前ChannelHandler的下一个ChannelHandler开始处理(出站)
  • ChannelOption

 Netty 在创建 Channel 实例后,一般都需要设置 ChannelOption 参数。ChannelOption 是 Socket 的标准参数,而非 Netty 独创的。常用的参数配置有:

  1. ChannelOption.SO_BACKLOG
    对应TCP/IP协议listen函数中的backlog参数,用来初始化服务器可连接队列大小。服务端处理客户端连接请求是顺序处理的,所以同一时间只能处理一个客户端连接。多个客户 端来的时候,服务端将不能处理的客户端连接请求放在队列中等待处理,backlog参数指定了队列的大小。
  2. ChannelOption.SO_KEEPALIVE,一直保持连接活动状态。
  • ChannelFuture

表示Channel中异步I/O操作的结果,在Netty中所有的I/O操作都是异步的,I/O的调用会直接返回,调用者并不能立刻获得结果,但是可以通过ChannelFuture来获取I/O操作的处理状态。常用方法如下所示:

  1. Channel channel(),返回当前正在进行IO操作的通道
  2. ChannelFuture sync(),等待异步操作执行完毕
  • EventLoopGroup和其实现类NioEventLoopGroup

EventLoopGroup是一组EventLoop的抽象,Netty为了更好的利用多核CPU 资源,一般会有多个EventLoop同时工作,每个EventLoop维护着一个Selector实例。

EventLoopGroup提供next接口,可以从组里面按照一定规则获取其中一个EventLoop来处理任务。在Netty服务器端编程中,我们一般都需要提供两个EventLoopGroup,例如:BossEventLoopGroup 和 WorkerEventLoopGroup。

通常一个服务端口即一个ServerSocketChannel对应一个Selector和一个EventLoop线程。BossEventLoop负责接收客户端的连接并将SocketChannel交给WorkerEventLoopGroup来进行IO 处理,如下图所示:

 

BossEventLoopGroup通常是一个单线程的EventLoop,EventLoop维护着一个注册了ServerSocketChannel的Selector实例,BossEventLoop不断轮询Selector将连接事件分离出来,通常是OP_ACCEPT事件,然后将接收到的SocketChannel交给WorkerEventLoopGroup,WorkerEventLoopGroup会由next选择其中一个EventLoopGroup来将这个SocketChannel注册到其维护的Selector并对其后续的IO事件进行处理。
      常用方法如下所示:

  1. public  NioEventLoopGroup(),构造方法

  2. public  Future<?>shutdownGracefully(),断开连接,关闭线程
  • ServerBootstrap和Bootstrap

ServerBootstrap是Netty中的服务器端启动助手,通过它可以完成服务器端的各种配置;Bootstrap是Netty中的客户端启动助手,通过它可以完成客户端的各种配置。常用方法如下所示:

  1. public ServerBootstrap group(EventLoopGroupparentGroup,EventLoopGroupchildGroup),该方法用于服务器端,用来设置两个EventLoop
  2. public B group(EventLoopGroupgroup),该方法用于客户端,用来设置一个EventLoop
  3. public B channel(Class<?extendsC>channelClass),该方法用来设置一个服务器端的通道实现
  4. public <T>B option(ChannelOption<T>option,Tvalue),用来给ServerChannel添加配置
  5. public <T>  ServerBootstrap  childOption(ChannelOption<T>childOption,Tvalue),用来给接收到的通道添加配置
  6. public  ServerBootstrap  childHandler(ChannelHandlerchildHandler),该方法用来设置业务处理类(自定义的handler)
  7. public ChannelFuture bind(intinetPort),该方法用于服务器端,用来设置占用的端口号
  8. public  ChannelFuture  connect(StringinetHost,intinetPort),该方法用于客户端,用来连接服务器端
  • Unpooled类

这是Netty提供的一个专门用来操作缓冲区的工具类,常用方法如下所示:

  1. public static ByteBuf copiedBuffer(CharSequencestring,Charsetcharset),通过给定的数据和字符编码返回一个ByteBuf对象(类似于NIO中的ByteBuffer对象)

测试案例:

导入pom坐标

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.lkw</groupId>
    <artifactId>netty_test2</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>4.1.25.Final</version>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.5</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.6</version>
        </dependency>
    </dependencies>

    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.2</version>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                        <encoding>UTF-8</encoding>
                        <showWarnings>true</showWarnings>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>

</project>

采用 4.1.8 版本

自定义服务器端业务处理类,继承 ChannelInboundHandlerAdapter

package com.lkw;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import java.util.ArrayList;
import java.util.List;

public class NettyServerHandler extends SimpleChannelInboundHandler<String> {
    private static List<Channel> channels = new ArrayList<>();

    //通道就绪事件
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channels.add(channel);
        System.out.println(channel.remoteAddress().toString() + "上线了");
    }

    //通道未就绪事件
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channels.remove(channel);
        System.out.println(channel.remoteAddress().toString() + "下线了");
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.copiedBuffer("收到了", CharsetUtil.UTF_8));
    }

    //数据读取事件
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
        Gson gson = new Gson();
        List<Person> personList = gson.fromJson(s, new TypeToken<List<Person>>() {
        }.getType());
        for (Person person : personList) {
            System.out.println(person.getName() + " " + person.getAge() + " " + person.getAddr());
        }


    }

    //异常读取事件
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        Channel channel = ctx.channel();
        System.out.println(channel.remoteAddress().toString() + "发生异常");
        ctx.close();
    }

}

创建Netty服务端程序

package com.lkw;

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;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class NettyServer {
    private int port; //端口号

    public NettyServer(int port) {
        this.port = port;
    }

    public void run() throws Exception {
        //首先创建两个线程组,创建主线程组,专门处理连接请求
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        //创建workerGroup,专门处理读写操作
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        //创建启动助手来配置相关东西
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workerGroup)  //将两个主从线程组
                .channel(NioServerSocketChannel.class)   //设置用什么通道
                .option(ChannelOption.SO_BACKLOG, 128) //设置线程队列中等待的个数
                .childOption(ChannelOption.SO_KEEPALIVE, true) //设置一直保持活动连接状态
                .childHandler(new ChannelInitializer<SocketChannel>() {//创建一个通道初始化容器
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast("decoder", new StringDecoder());   //添加解码器
                        socketChannel.pipeline().addLast("encoder", new StringEncoder());   //添加编码器
                        socketChannel.pipeline().addLast(new NettyServerHandler());            //添加自定义的Handler
                        System.out.println("正在启动");
                    }
                });
        //启动服务器并绑定端口号,等待客户端连接!非阻塞
        ChannelFuture cf = serverBootstrap.bind(port).sync();
        System.out.println("服务器已经启动");
        //关闭线程,关闭通道
        cf.channel().closeFuture().sync();
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }


    public static void main(String[] args) throws Exception {
        NettyServer nettyServer = new NettyServer(9999);
        nettyServer.run();
    }
}

编写一个客户端,继承 ChannelInboundHandlerAdapter ,同样这里也可以继承SimpleChannelInboundHandler,这个是她的子类,并分别重写了四个方法。

package com.lkw;

import com.google.gson.Gson;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class NettyClientHandler extends SimpleChannelInboundHandler<String> {
    private List<Person> people = Arrays.asList(
            new Person("张三", "19", "湖北"),
            new Person("李四", "19", "湖北"),
            new Person("王五", "19", "湖北")
    );

    //通道就绪事件
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Gson gson = new Gson();
        String s = gson.toJson(people);
        ctx.writeAndFlush(Unpooled.copiedBuffer(s, CharsetUtil.UTF_8));
    }

    //通道读取完毕事件
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
        System.out.println(s.trim());
    }
}

编写客户端程序:

package com.lkw;

import io.netty.bootstrap.Bootstrap;
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;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class NettyClient {
    private final int port;
    private final String host;

    public NettyClient(int port, String host) {
        this.host = host;
        this.port = port;
    }


    public void run() {
        EventLoopGroup group = null;
        try {
            //创建一个线程组来
            group = new NioEventLoopGroup();

            //创建客户端启动助手
            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("decoder", new StringDecoder());
                            socketChannel.pipeline().addLast("encoder", new StringEncoder());
                            socketChannel.pipeline().addLast(new NettyClientHandler());
                        }
                    });
            ChannelFuture sync = bootstrap.connect(host, port).sync();
            sync.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        NettyClient nettyClient = new NettyClient(9999, "127.0.0.1");
        nettyClient.run();
    }

}

上述代码编写了一个客户端程序,配置了线程组,配置了自定义的业务处理类,并启动连接 了服务器端。最终运行效果如下图所示:

服务端:

客户端:

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值