Netty常考面试问题集锦
最近找实习面试了一家问netty的 下面说说几个常见的netty面试题吧
1.什么是netty 谈谈对netty的理解
答:netty是java的一个封装jdk的nio库,并且优化了许多原生nio缺点的网络框架
2.netty的初始化流程
答:首先netty真正的初始化在bind()方法之后执行
该方法是Netty服务端与端口进行绑定,也是Netty的核心方法
Netty把原生的bind和accept等操作全部封装到了一个unsafe类当中,并且每个channel都有一个unsafe类对象
netty的channel采用了包装(代理)模式把原生的channel封装了一遍,在bind之后会根据我们提供的serverChannel类型通过反射提供一个serverChannel对象,之后调用initAndRegister进行注册,
final ChannelFuture initAndRegister() {
Channel channel = null;
try {
//创建网络通道channel
channel = channelFactory.newChannel();
//为channel配置options就是该方法完成的
init(channel);
} catch (Throwable t) {
if (channel != null) {
// channel can be null if newChannel crashed (eg SocketException("too many open files"))
channel.unsafe().closeForcibly();
// as the Channel is not registered yet we need to force the usage of the GlobalEventExecutor
return new DefaultChannelPromise(channel, GlobalEventExecutor.INSTANCE).setFailure(t);
}
// as the Channel is not registered yet we need to force the usage of the GlobalEventExecutor
return new DefaultChannelPromise(new FailedChannel(), GlobalEventExecutor.INSTANCE).setFailure(t);
}
//在register阶段会选择bossGroup的一个EventLoop注册一个IO多路复用模型用于处理请求
ChannelFuture regFuture = config().group().register(channel);
if (regFuture.cause() != null) {
if (channel.isRegistered()) {
channel.close();
} else {
channel.unsafe().closeForcibly();
}
}
return regFuture;
}
当选择好boss中的一个eventLoop作为多路复用模型用于接收请求后,serverChannel的register事件在Bind结束后会设置InterestOP在Server端体现就是accept最后在Server的pipline加上一个ServerBootstrapAccepter的handler用于处理后面的初始化
3.说一说客户端是如何接入的
答:server端的EventLoop接收到accept事件后,因为在Server端设置监听类型的时候设置attachment是对应的ServerChannel,所以这里可以取到ServerChannel,在这里封装了accept得到的原生channel为netty的channel,在ServerChannel的pipeline上触发了read事件,把这些channel发送到serverbooststrapAccepter的handler进行初始化,注册等操作
4.Netty epoll空轮询bug
答: 产生原因 selector的轮询结果为空,也没有weakUp或者新消息处理会一直空查询,直到cpu占100%
Netty的解决方法:
1.对selector的select操作周记进行统计,每完成一次空的select操作进行计数
2.某个周期达到了n次空轮询会触发epoll死循环bug
3.将问题的selector上的channel注册到新建的selector上4.老的问题selecor关闭,使用新建的selector替换
上一篇: 史上最全面的Netty面试问题集锦
下一篇: 2022年度热门Netty面试问题集锦