netty IO模式的支持

netty IO模式的支持

选择开发模式:

// 设置对应 EventLoopGroup
// Nio模型
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
// 直接修改即可对应方法名即可,
// Oio模式
EventLoopGroup bossGroup = new OioEventLoopGroup();
EventLoopGroup workerGroup = new OioEventLoopGroup();

选择IO模式:

// 设置Nio模式
......
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 100)
.handler(new LoggingHandler(LogLevel.INFO))
......
}
// 设置Oio模式
......
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(OioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 100)
.handler(new LoggingHandler(LogLevel.INFO))
......
}

创建方法:进入 channel(OioServerSocketChannel.class) 方法,发现是一个反射+工厂来实现 Channel 的创建

public B channel(Class<? extends C> channelClass) {
return channelFactory(new ReflectiveChannelFactory<C>(
ObjectUtil.checkNotNull(channelClass, "channelClass")
));
}

进入 ReflectiveChannelFactory() 类 :

//泛型+反射+工厂实现IO模式切换
public class ReflectiveChannelFactory<T extends Channel> implements ChannelFactory<T> {
private final Constructor<? extends T> constructor;
public ReflectiveChannelFactory(Class<? extends T> clazz) {
ObjectUtil.checkNotNull(clazz, "clazz");
try {
//获取无参构造器
this.constructor = clazz.getConstructor();
} catch (NoSuchMethodException e) {
throw new IllegalArgumentException("Class " + StringUtil.simpleClassName(clazz) +
" does not have a public non-arg constructor", e);
}
}
@Override
//泛型T代表不同的Channel
public T newChannel() {
try {
//反射创建channel
return constructor.newInstance();
} catch (Throwable t) {
throw new ChannelException("Unable to create Channel from class " + constructor.getDeclaringClass(), t);
}
}
......
}

netty IO模式的支持

原文:https://www.cnblogs.com/sleepday/p/15309787.html

以上是netty IO模式的支持的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>