首页 > Web开发 > 详细

netty IO模式的支持

时间:2021-09-23 00:16:22      阅读:5      评论:0      收藏:0      [点我收藏+]

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

(0)
(0)
   
举报
评论 一句话评论(0
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!