美文网首页
《Nio系列五》- Netty实现时间查询服务

《Nio系列五》- Netty实现时间查询服务

作者: 逍遥无极 | 来源:发表于2017-12-01 16:12 被阅读0次

前几节中,讲解了Bio、Nio、Aio实现时间查询服务的细节,比对其优缺点进行了对比。从本节开始,Nio系列将讲解Netty的相关知识,为了比较使用Netty实现服务与直接使用JDK提供的IO操作实现服务的区别,本节仍然以实现时间查询服务为例,讲解Netty的使用细节。

Netty实现服务端

Netty屏蔽了IO底层的操作,即便对IO操作不熟悉,没有专业的知识基础,也可以写出稳定可用的服务。使用Netty编程,基本就是按照特定的步骤进行自定义的设值,启动服务即可。Netty服务端实现逻辑如下:

  1. 创建两个线程池 EventLoopGroup,一个用于处理客户端的链接操作,如果服务只监听了一个端口的话,建议改线程池的大小设置为1,另一个线程池用于处理IO的读写操作。
  2. 配置ServerBootstrap, 该类是服务端配置辅助类,主要配置服务端的一些设置参数。例如设置使用的线程池、使用的channel类型、连接上限、初始化逻辑操作等等。
  3. 使用serverBootstrap绑定端口,使用同步方法绑定端口,绑定成功返回ChannelFuture对象,到此服务端就启动了
  4. 等待future执行完,主要就是为了不让逻辑执行完成后退出

实现代码如下:

public class NettyServer {

    private int port;

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

    public void start(){
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 1024)
                .childHandler(new ChannelInitializer<SocketChannel>(){
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {

                        ch.pipeline().addLast(new TimerServerHandler());
                    }
                });

        try {
            //同步绑定
            ChannelFuture future = serverBootstrap.bind(new InetSocketAddress(port)).sync();
            //等待关闭
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {

        NettyServer server = new NettyServer(8080);
        server.start();
    }
}

重点讲解一下childHandler()方法,该方法中接收一个ChannelInitializer对象,ChannelInitializer是一个抽象类,我们需要继承该类实现抽象方法initchannel(),在该方法中往pipeline中添加自己的处理逻辑。数据的编解码、数据的接收读取都可以在这里进行扩展。处理逻辑类的实现如下:

public class TimerServerHandler extends ChannelHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        ByteBuf byteBuf = (ByteBuf) msg;
        byte[] bytes = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(bytes);
        String message = new String(bytes, "utf-8");
        System.out.println("获取到请求:" + message);
        String response = null;
        if("时间".equals(message)){
            response = (new Date()).toString();
        }else{
            response = "不支持该请求";
        }
        byte[] responseBytes = response.getBytes();
        ByteBuf responseBuf = Unpooled.buffer(responseBytes.length);
        responseBuf.writeBytes(responseBytes);
        System.out.println("返回响应:" + response);
        ctx.write(responseBuf);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

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

逻辑处理类,需要继承ChannelHandlerAdapter,其中重要介绍一下channelRead()方法,该方法在接收到数据时自动调用(会存在半包问题,此处不考虑),ctx是上下文参数,可以通过ctx读写数据,msg是读取到的数据,这个数据可以是Buffer,可以是String,可以是任意对象,关键是看有没有在initChannel方法中进行编解码配置。读取到数据中,解析数据,然后进行响应。到此服务端代码就写完了。

Netty实现客户端

客户端的实现与服务端实现类似,不同之处在于:

  1. 辅助配置类为Bootstrap
  2. 只需要配置一个线程池即可,因为可以断不需要处理请求连接操作

实现代码如下:

public class NettyClient {

    private int port;
    private String hostname;

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

    public void start(){

        EventLoopGroup group = new NioEventLoopGroup();

        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new TimeClientHandler());
                    }
                });
        try {
            ChannelFuture future = bootstrap.connect(new InetSocketAddress(hostname, port)).sync();
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            group.shutdownGracefully();
        }

    }

    public static void main(String[] args) {

        NettyClient client = new NettyClient(8080, "127.0.0.1");
        client.start();
    }
}

重点看一下客户端的处理逻辑类TimeClientHandler的实现,代码如下:

public class TimeClientHandler extends ChannelHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        ByteBuf byteBuf = (ByteBuf) msg;
        byte[] bytes = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(bytes);
        String message = new String(bytes, "utf-8");
        System.out.println("收到响应:" + message);

    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        String message = "时间";
        byte[] bytes = message.getBytes();
        ByteBuf byteBuf = Unpooled.buffer(bytes.length);
        byteBuf.writeBytes(bytes);
        System.out.println("发送请求:" + message);
        ctx.writeAndFlush(byteBuf);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

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

channelActive()在连接服务器成功时调用,连接成功后发送请求即可。channelRead()方法在当有响应数据时调用(接收数据队列中有数据了就会调用,当然也会受到initChannel()方法中配置的影响),到此客户端也实现完成。

总结

经过对Netty的学习,我们发现在实现逻辑中,我们不在和Channel、socket打交道了,而是而需要和Buffer打交道即可(如果配置了编解码Buffer也不用打交道,直接处理对象即可)。Netty屏蔽了IO处理的细节,简化了编程的复杂性。

下一节,将讲解Netty对半包/粘包问题的处理。

欢迎扫描下方二维码,关注公众号,我们可以进行技术交流,共同成长

qrcode_for_gh_5580beb3cba1_430.jpg

相关文章

网友评论

      本文标题:《Nio系列五》- Netty实现时间查询服务

      本文链接:https://www.haomeiwen.com/subject/hhmibxtx.html