您的位置:首页 > 其它

Netty线程模型

2017-06-09 15:52 351 查看


Netty线程模型


传统的BIO实现的TCP服务器,特别对于TCP长连接,通常都要为每个连接开启一个线程,线程也是操作系统的一种资源,所以很难实现高性能高并发。而异步IO实现的TCP服务器,由于IO操作都是异步的,可以用一个线程或者少量线程来处理大量连接的IO操作,所以只需要少量的IO线程就可以实现高并发的服务器。


在网络编程过程中,通常有一些业务逻辑是比较耗时、阻塞的,例如数据库操作,如果网络不好,加上数据库性能差,SQL不够优化,数据量大,一条SQL可能会执行很久。由于IO线程本身数量就不多,通常只有一个或几个,而如果这种耗时阻塞的代码在IO线程中运行的话,IO线程的其他事情,例如网络read和write,就无法进行了,会影响IO性能以及整个服务器的性能。


所以,如果有耗时的任务,就绝对不能在IO线程中运行,而是要另外开启线程来处理。

public class Server {

public void start() throws InterruptedException {
EventLoopGroup boss = new NioEventLoopGroup(1);
EventLoopGroup worker = new NioEventLoopGroup(4);
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(boss, worker)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<Channel>() {
EventExecutorGroup group = new DefaultEventExecutorGroup(16);
@Override
protected void initChannel(Channel arg0) throws Exception {
ChannelPipeline channelPipeline = arg0.pipeline();
channelPipeline.addLast(new LineBasedFrameDecoder(80));
channelPipeline.addLast(group,new ServerHandler());
}
});
ChannelFuture channelFuture = serverBootstrap.bind(7744).sync();
System.out.println("Server.enclosing_method()");
channelFuture.channel().closeFuture().sync();
}
public static void main(String[] args) throws InterruptedException {
Server server = new Server();
server.start();
}

}

public class ServerHandler extends SimpleChannelInboundHandler<Object>{

@Override
protected void channelRead0(ChannelHandlerContext arg0, Object arg1) throws Exception {

}

@Override
public void channelRead(ChannelHandlerContext arg0, Object arg1) throws Exception {
Thread.sleep(3000);//处理耗时操作

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: