我为何放弃TOMCAT转而使用Netty
放弃Tomcat而选择Netty的原因通常与Tomcat基于线程的模型相关,这意味着每个连接都会占用一个线程,这在处理大量连接时会有性能瓶颈。Netty采用了非阻塞I/O和事件驱动模型,它能够更有效地处理网络I/O,特别适合于高并发和需要高性能的网络应用。
以下是Netty服务器的简单示例代码,它创建了一个基本的Echo服务器,用于回显客户端发送的消息:
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
public class EchoServer {
private final int port;
public EchoServer(int port) {
this.port = port;
}
public void start() throws Exception {
final EchoServerHandler serverHandler = new EchoServerHandler();
EventLoopGroup group = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(group)
.channel(NioServerSocketChannel.class)
.localAddress(port)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(serverHandler);
}
});
ChannelFuture f = b.bind().sync();
System.out.println(EchoServer.class.getName() + " started and listen on " + port);
f.channel().closeFuture().sync();
} finally {
group.shutdownGracefully().sync();
}
}
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.err.println("Usage: " + EchoServer.class.getSimpleName() + " <port>");
return;
}
int port = Integer.parseInt(args[0]);
new EchoServer(port).start();
}
}
class EchoServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
ctx.write(msg);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
在这个例子中,EchoServer
类设置了服务器的基础设施,并启动了Netty服务器。EchoServerHandler
类实现了具体的逻辑来处理进来的连接和数据。这个简单的例子展示了如何使用Netty创建一个非阻塞I/O的服务器。
评论已关闭