//package com.yida.data.server.config;
//
//import cc.mrbird.febs.common.redis.service.RedisService;
//import com.yida.data.server.handler.MyHandler;
//import com.yida.data.server.service.DataService;
//import io.netty.bootstrap.ServerBootstrap;
//import io.netty.buffer.PooledByteBufAllocator;
//import io.netty.buffer.Unpooled;
//import io.netty.channel.ChannelFuture;
//import io.netty.channel.ChannelInitializer;
//import io.netty.channel.ChannelOption;
//import io.netty.channel.ChannelPipeline;
//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.DelimiterBasedFrameDecoder;
//import io.netty.handler.codec.string.StringDecoder;
//import io.netty.handler.codec.string.StringEncoder;
//import io.netty.util.concurrent.Future;
//import io.netty.util.concurrent.GenericFutureListener;
//import java.net.InetAddress;
//import java.net.InetSocketAddress;
//import java.net.UnknownHostException;
//import javax.annotation.Resource;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.context.annotation.Configuration;
//
//@Slf4j
//@Configuration
//public class StartConfig {
//
//    @Resource
//    private DataService dataService;
//    @Resource
//    private RedisService redisService;
//
//    private final static EventLoopGroup bossGroup = new NioEventLoopGroup();
//    //开启两个线程池
//    private final static EventLoopGroup workGroup = new NioEventLoopGroup();
//    //启动装饰类
//    private final static ServerBootstrap serverBootstrap = new ServerBootstrap();
//    //本机的ip地址
//    private String ip;
//
//    //启动端口
//    private int port = 1993;
//
//    /**
//     * 启动服务
//     */
//    public void start() {
//
//        try {
//            //获取本机的ip地址
//            ip = InetAddress.getLocalHost().getHostAddress();
//        } catch (UnknownHostException e1) {
//            e1.printStackTrace();
//        }
//
//        serverBootstrap.group(bossGroup, workGroup)
//            //非阻塞
//            .channel(NioServerSocketChannel.class)
//            //连接缓冲池的大小
//            .option(ChannelOption.SO_BACKLOG, 1024)
//            //设置通道Channel的分配器
//            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
//            .childHandler(new ChannelInitializer<SocketChannel>() {
//
//                @Override
//                protected void initChannel(SocketChannel socketChannel) throws Exception {
//                    ChannelPipeline pipeline = socketChannel.pipeline();
//                    // 按#分割 最大长度1024字节
//                    pipeline.addLast(new DelimiterBasedFrameDecoder(1024, Unpooled.copiedBuffer("#".getBytes())));
//                    // 解码器 转换为字符串
//                    pipeline.addLast(new StringDecoder());
//                    // 编码器
//                    pipeline.addLast(new StringEncoder());
//                    //数据处理
//                    pipeline.addLast(new MyHandler(dataService, redisService));
//
//
//                }
//            });
//        ChannelFuture channelFuture = null;
//        //启动成功标识
//        boolean startFlag = false;
//        //启动失败时，多次启动，直到启动成功为止
//        while (!startFlag) {
//            try {
//                channelFuture = serverBootstrap.bind(port).sync();
//                startFlag = true;
//            } catch (Exception e) {
//                log.info("端口号：" + port + "已被占用！");
//                port++;
//                log.info("尝试一个新的端口：" + port);
//                //重新便规定端口号
//                serverBootstrap.localAddress(new InetSocketAddress(port));
//            }
//        }
//
//        //服务端启动监听事件
//        channelFuture.addListener(new GenericFutureListener<Future<? super Void>>() {
//            @Override
//            public void operationComplete(Future<? super Void> future) throws Exception {
//                //启动成功后的处理
//                if (future.isSuccess()) {
//                    log.info("netty 服务器启动成功，Started Successed:" + ip + ":" + port);
//                } else {
//                    log.info("netty 服务器启动失败，Started Failed:" + ip + ":" + port);
//                }
//            }
//        });
//
//        try {
//            // 监听通道关闭事件
//            // 应用程序会一直等待，直到channel关闭
//            ChannelFuture closeFuture = channelFuture.channel().closeFuture();
//            closeFuture.sync();
//        } catch (Exception e) {
//            e.printStackTrace();
//            log.error("发生其他异常", e);
//        } finally {
//            // 优雅关闭EventLoopGroup，
//            // 释放掉所有资源包括创建的线程
//            bossGroup.shutdownGracefully();
//            workGroup.shutdownGracefully();
//        }
//    }
//}
