使用netty编写syslog日志接收服务端
1.添加netty依赖
<dependency><groupId>io.netty</groupId><artifactId>netty-all</artifactId><version>4.1.72.Final</version> <!-- 版本号可能需要根据实际情况更新 --></dependency>
2.代码案例
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.CharsetUtil;public class UdpSyslogServer {private static final int PORT = 5140; // Syslog 常用端口是 514,这里使用 5140 避免需要管理员权限public static void main(String[] args) throws Exception {EventLoopGroup group = new NioEventLoopGroup();try {Bootstrap b = new Bootstrap();b.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true).handler(new ChannelInitializer<NioDatagramChannel>() {@Overridepublic void initChannel(NioDatagramChannel ch) throws Exception {ch.pipeline().addLast(new SyslogPacketHandler());}});// 绑定端口,开始接收进来的连接Channel channel = b.bind(PORT).sync().channel();System.out.println("UDP Syslog Server listening on " + PORT);// 等待直到服务器 socket 关闭channel.closeFuture().await();} finally {// 关闭 EventLoopGroup,释放所有资源group.shutdownGracefully();}}private static class SyslogPacketHandler extends SimpleChannelInboundHandler<DatagramPacket> {@Overrideprotected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {// 获取 DatagramPacket 中的数据ByteBuf buf = packet.content();String syslogMessage = buf.toString(CharsetUtil.UTF_8);// 打印接收到的 Syslog 消息System.out.println(packet.sender() + ": " + syslogMessage);}}
}