1.pom.xml
<!--定時任務和@Slf4j註解日誌的依賴-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
2.代碼應用
package com.cloudtech.server;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.cloudtech.util.Consts;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
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.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
/**
*
* @ClassName: Server
* @Description:netty服務端
* @author wude
* @date 2018年9月7日
*
*/
@Slf4j
public class Server {
/**
* 啓動
*/
public void start(int port) {
// 服務類
ServerBootstrap b = new ServerBootstrap();
// 創建boss和worker
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
//業務線程池,實現消息串行化
EventLoopGroup busyGroup = new NioEventLoopGroup();
try {
// 設置循環線程組事例
b.group(bossGroup, workerGroup);
// 設置channel工廠
b.channel(NioServerSocketChannel.class);
// 設置管道
b.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
//第一個參數 讀超時
//第二個參數 寫超時
//第三個參數讀寫超時
ch.pipeline().addLast(new IdleStateHandler(5, 5, 60));
ByteBuf delimiter = Unpooled.copiedBuffer(")".getBytes());
ch.pipeline().addLast(new DelimiterBasedFrameDecoder(Consts.MAX_BUFF_LEN,delimiter));
ch.pipeline().addLast(new StringDecoder());
ch.pipeline().addLast(busyGroup,new ServerHandler());
}
});
b.option(ChannelOption.SO_BACKLOG, 2048);//serverSocketchannel的設置,鏈接緩衝池的大小
b.childOption(ChannelOption.SO_KEEPALIVE, true);//socketchannel的設置,維持鏈接的活躍,清除死鏈接
b.childOption(ChannelOption.TCP_NODELAY, true);//socketchannel的設置,關閉延遲發送
log.info("啓動梯度塔秒級站採集成功!port={}",port);
//綁定端口
ChannelFuture future = b.bind(port);
//等待服務端關閉
future.channel().closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
} finally{
//釋放資源
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
busyGroup.shutdownGracefully();
}
}
}
在類上增加@Slf4j註解,就可以在代碼中通過log調用日誌的一些方法