springboot整合NIO框架netty

 

小编在网上找到的一个大神编写的NIO框架demo,githua地址:

https://codeload.github.com/marquisXuan/netty

下面是其中一个最简单的小测试:

1.添加依赖pom.xml

        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>5.0.0.Alpha2</version>
        </dependency>

下面是小编的包文件创建

2.编写服务端Server

TimeServer 类:

package com.example.demo.nettyServer;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <p>
 * create by 叶云轩 at 2018/4/11-下午6:33
 * contact by tdg_yyx@foxmail.com
 */
public class TimeServer {
    /*
     NioEventLoopGroup本质是一个线程组,包含一组NIO线程专门用于网络事件的处理
     一个用于服务端接受客户端的连接
     一个用于进行SocketChannel的网络读写
     */

    /**
     * TimeServer 日志控制器
     * Create by 叶云轩 at 2018/4/12 上午11:26
     * Concat at tdg_yyx@foxmail.com
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(TimeServer.class);

    /**
     * 绑定端口
     *
     * @param port 端口号
     * @throws Exception 异常
     */
    public void bind(int port) throws Exception {
        LOGGER.info("--- [绑定端口] {}", port);
        // 声明Boss线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        // 声明Worker线程组
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            LOGGER.info("--- [启动NIO] ");
            // Netty用于启动NIO服务端的辅助启动类,目的是降低服务端的开发复杂度
            ServerBootstrap bootstrap = new ServerBootstrap();
            // 将两个NIO线程组传递到ServerBootStrap中
            bootstrap.group(bossGroup, workerGroup)
                    // NioServerSocketChannel 相当于NIO中的ServerSocketChannel类
                    .channel(NioServerSocketChannel.class)
                    // 配置NioServerSocketChannel的TCP参数 backlog设置为1024
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    // 绑定I/O事件处理类
                    .childHandler(new ChildChannelHandler());
            // 绑定端口,同步等待成功
            // channelFuture 相当于JDK的java.util.concurrent.Future用于异步操作通知回调
            ChannelFuture channelFuture = bootstrap.bind(port).sync();
            // 等待服务端监听端口关闭
            channelFuture.channel().closeFuture().sync();
        } finally {
            // 优雅退出,释放线程池资源
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

 ChildChannelHandler 类:

package com.example.demo.nettyServer;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * I/O事件处理类
 * <p>
 * create by 叶云轩 at 2018/4/11-下午6:34
 * contact by tdg_yyx@foxmail.com
 */
public class ChildChannelHandler extends ChannelInitializer<SocketChannel> {

    /**
     * ChildChannelHandler 日志控制器
     * Create by 叶云轩 at 2018/4/12 上午11:29
     * Concat at tdg_yyx@foxmail.com
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(ChildChannelHandler.class);


    /**
     * LineBasedFrameDecoder: 以换行符为结束标志的解码器
     *  依次遍历ByteBuf中的可读字节,
     *  如果有"\n" 或者 "\r\n" -> 就以此位置为结束位置 之后将可读索引到结束位置区间的字节组成一行
     */

    /**
     * 创建NioSocketChannel成功之后,进行初始化时,
     * 将ChannelHandler设置到ChannelPipeline中,
     * 同样,用于处理网络I/O事件
     *
     * @param ch
     * @throws Exception
     */
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        LOGGER.info("--- [通道初始化]");
        // region 解决粘包/拆包问题相关代码
        ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
        // 将接收到的对象转成字符串
        ch.pipeline().addLast(new StringDecoder());
        // endregion

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

TimeServerHandler 类: 

package com.example.demo.nettyServer;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

/**
 * 针对网络事件进行读写操作的类
 * <p>
 * create by 叶云轩 at 2018/4/11-下午6:35
 * contact by tdg_yyx@foxmail.com
 */
public class TimeServerHandler extends ChannelHandlerAdapter {
    /**
     * TimeServerHandler 日志控制器
     * Create by 叶云轩 at 2018/4/12 上午11:30
     * Concat at tdg_yyx@foxmail.com
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(TimeServerHandler.class);
    /**
     * 模拟粘包/拆包问题计数器
     */
    private int counter;

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

    /**
     * 读事件
     *
     * @param ctx ChannelHandlerContext
     * @param msg 消息
     *
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        // region 解决模拟粘包/拆包问题相关代码
        String body = (String) msg;
        LOGGER.info("--- [接收到的数据] {} | [counter] {}", body, ++counter);
        String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new Date(System.currentTimeMillis()).toString() : "BAD ORDER";
        currentTime = currentTime + System.getProperty("line.separator");
        ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
        // endregion

        // 异步发送应答消息给Client
        ctx.writeAndFlush(resp); // --> 将消息放到发送缓冲数组中
    }
}

3.编写访问端:

TimeClient类:
package com.example.demo.nettyClient;

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

/**
 * Netty时间服务器客户端
 * <p>
 * create by 叶云轩 at 2018/4/12-上午9:53
 * contact by tdg_yyx@foxmail.com
 */
public class TimeClient {

    public void connect(int port, String host) throws Exception {
        // 配置客户端的NIO线程组
        EventLoopGroup clientGroup = new NioEventLoopGroup();
        try {
            // Client辅助启动类
            Bootstrap bootstrap = new Bootstrap();
            // 配置bootstrap
            bootstrap.group(clientGroup)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        /**
                         * 创建NioSocketChannel成功之后,进行初始化时,
                         * 将ChannelHandler设置到ChannelPipeline中,
                         * 同样,用于处理网络I/O事件
                         * @param ch
                         * @throws Exception
                         */
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            // region 解决粘包/拆包问题相关代码
                            ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
                            ch.pipeline().addLast(new StringDecoder());
                            // endregion
                            ch.pipeline().addLast(new TimeClientHandler());
                        }
                    });
            // 发起异步连接操作  同步方法待成功
            ChannelFuture future = bootstrap.connect(host, port).sync();
            // 等待客户端链路关闭
            future.channel().closeFuture().sync();
        } finally {
            // 优雅退出,释放NIO线程组
            clientGroup.shutdownGracefully();
        }


    }
}

 

TimeClientHandler类:
package com.example.demo.nettyClient;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <p>
 * create by 叶云轩 at 2018/4/12-上午10:16
 * contact by tdg_yyx@foxmail.com
 */
public class TimeClientHandler extends ChannelHandlerAdapter {

    /**
     * TimeClientHandler 日志控制器
     * Create by 叶云轩 at 2018/4/12 上午10:16
     * Concat at tdg_yyx@foxmail.com
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(TimeClientHandler.class);
    /**
     * 模拟粘包/拆包问题计数器
     */
    private int counter;

    /**
     *
     */
    private byte[] req;

    public TimeClientHandler() {
        // region 模拟粘包/拆包问题相关代码
        req = ("QUERY TIME ORDER" + System.getProperty("line.separator")).getBytes();
        // endregion
    }

    /**
     * 捕捉异常
     *
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        LOGGER.warn("--- [异常,释放资源] {}", cause.getMessage());
        ctx.close();
    }

    /**
     * 当客户端和服务端TCP链路建立成功之后调用此方法
     * 发送指令给服务端,调用ChannelHandlerContext.writeAndFlush方法将请求消息发送给服务端
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // region 模拟粘包/拆包问题相关代码
        ByteBuf message;
        for (int i = 0; i < 100; i++) {
            message = Unpooled.buffer(req.length);
            message.writeBytes(req);
            ctx.writeAndFlush(message);
        }
        // endregion
    }

    /**
     * 服务端返回应答消息时,调用此方法
     *
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // region 解决粘包/拆包问题相关代码
        String body = (String) msg;
        // endregion
        LOGGER.info("--- [Now is] {} | [counter] {}", body, ++counter);
    }
}

4.编写测试类

 //netty服务测试端
    @Test
    public void startNettyServer1() throws Exception{
        new TimeServer().bind(8808);
    }



   //访问测试端
    @Test
    public void startNettyClient() throws Exception{
        new TimeClient().connect(8808,"127.0.0.1");

    }

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值