一、环境
- 系统:macOS Monterey(MacBook Pro 13-inch,M1,2020)
- JDK:11
- Maven:3.8.1
- IDEA:2022.2.1(Ultimate Edition)
- Netty:netty-all 4.1.65.Final
二、工程
1、引入依赖
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.18.0</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.18.0</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.18.0</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>2.0.3</version>
</dependency>
2、配置log4j2.xml
${sys:user.home} 是根据当前环境配置,其它系统需要根据情况设置。
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="info">
<Properties>
<Property name="logDir">${sys:user.home}/Downloads/files/data/logs/demo-netty-base</Property>
<Property name="rollingSuffix">log.gz</Property>
<Property name="CONSOLE_LOG_PATTERN">%d %p %F:%L - %m%n</Property>
<Property name="FILE_LOG_PATTERN">%d %p %F:%L - %m%n</Property>
</Properties>
<appenders>
<console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="${CONSOLE_LOG_PATTERN}"/>
</console>
<RollingRandomAccessFile name="RollingFileInfo" fileName="${logDir}/info.log"
filePattern="${logDir}/logs/%d{yyyy-MM-dd}-%i-info.${rollingSuffix}"
immediateFlush="true">
<Filters>
<ThresholdFilter level="INFO"/>
</Filters>
<PatternLayout pattern="${FILE_LOG_PATTERN}"/>
<Policies>
<TimeBasedTriggeringPolicy/>
<SizeBasedTriggeringPolicy size="1024 MB"/>
</Policies>
<DefaultRolloverStrategy max="40">
<Delete basePath="${logDir}/logs/" maxDepth="1">
<IfFileName glob="*.${rollingSuffix}">
<IfAny>
<IfAccumulatedFileSize exceeds="50 GB"/>
<IfLastModified age="15d"/>
</IfAny>
</IfFileName>
</Delete>
</DefaultRolloverStrategy>
</RollingRandomAccessFile>
<RollingRandomAccessFile name="RollingFileError" fileName="${logDir}/error.log"
filePattern="${logDir}/logs/%d{yyyy-MM-dd}-%i-error.${rollingSuffix}"
immediateFlush="true">
<ThresholdFilter level="ERROR"/>
<PatternLayout pattern="${FILE_LOG_PATTERN}"/>
<Policies>
<TimeBasedTriggeringPolicy/>
<SizeBasedTriggeringPolicy size="1024 MB"/>
</Policies>
<DefaultRolloverStrategy max="40"/>
</RollingRandomAccessFile>
</appenders>
<loggers>
<root level="info">
<appender-ref ref="Console"/>
<appender-ref ref="RollingFileInfo"/>
<appender-ref ref="RollingFileError"/>
</root>
</loggers>
</Configuration>
三、使用
package com.example;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @Author Yincn
* @Date 2022/10/27 08:22
*/
public class NettyServer {
static Logger log = LoggerFactory.getLogger(NettyServer.class);
public static void main(String[] args) throws Exception {
NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
NioEventLoopGroup workGroup = new NioEventLoopGroup(1);
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup, workGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<>() {
@Override
protected void initChannel(Channel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new StringDecoder());
pipeline.addLast(new StringEncoder());
pipeline.addLast(new NettyServerHandler());
}
});
ChannelFuture channelFuture = serverBootstrap.bind(8088).addListener(v -> {
if (v.isSuccess()) {
log.info("Server start success.");
}
});
channelFuture.channel().closeFuture().sync();
log.warn("main thread end.");
} catch (Exception e) {
log.error("exception!", e);
} finally {
bossGroup.shutdownGracefully();
workGroup.shutdownGracefully();
}
}
}