netty4.x FixedChannelPool使用

FixedChannelPool是netty的连接池,除了这个以外netty还有另外一个连接池SimpleChannelPool,它们俩的关系其实就是儿子与爸爸,FixedChannelPool继承了SimpleChannelPool,这篇文章里主要是讲FixedChannelPool的故事。
注意上面讲的是连接池不是线程池喔。

  • 使用场景
    作为客户端想要连接服务器,但是并不想像传统的那样一个连接一个线程的来,线程资源有限就不说了,当连接很多的时候可要 怎 么 办!这时候想到一个办法,那就是连接池了。使用连接池咱们可以把所有的连接都放入连接池,当需要的时候拿出来,使用完再放回去。

1.初始化连接池

public void connect(int port, String host, int maxChannel) {

        EventLoopGroup group = new NioEventLoopGroup(1);

        Bootstrap bootstrap = new Bootstrap();

// 连接池每次初始化一个连接的时候都会根据这个值去连接服务器
        InetSocketAddress remoteaddress = InetSocketAddress.createUnresolved(host, port);// 连接地址
        bootstrap.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
                .remoteAddress(remoteaddress);

// 初始化连接池
// 这个值可要好好保管好了,后面拿连接放连接都要通过它啦
        FixedChannelPool channelPool = new FixedChannelPool(bootstrap, new SHChannelPoolHandler(), maxChannel);

    }

细心的朋友可能看到SHChannelPoolHandler这个类并不是netty自身的,没错,这是咱们第二步要做的:
2.连接池操作类:

public class SHChannelPoolHandler implements ChannelPoolHandler {

    /**
     * 使用完channel需要释放才能放入连接池
     */
    @Override
    public void channelReleased(Channel ch) throws Exception {
        // TODO Auto-generated method stub

        // 刷新管道里的数据
        ch.writeAndFlush(Unpooled.EMPTY_BUFFER); //flush掉所有写回的数据  

        // LoggerFactory.getLogger(SHChannelPoolHandler.class).info("释放channel,channel
        // released " + ch.toString());
    }

    /**
     * 获取连接池中的channel
     */
    @Override
    public void channelAcquired(Channel ch) throws Exception {
        // TODO Auto-generated method stub

        // LoggerFactory.getLogger(SHChannelPoolHandler.class).info("获取channel,channel
        // acquired " + ch.toString());
    }

    /**
     * 当channel不足时会创建,但不会超过限制的最大channel数
     */
    @Override
    public void channelCreated(Channel ch) throws Exception {
        // TODO Auto-generated method stub

        // LoggerFactory.getLogger(SHChannelPoolHandler.class).info("创建新channel,channel
        // created " + ch.toString());

        NioSocketChannel channel = (NioSocketChannel) ch;

        // 客户端逻辑处理   ClientHandler这个也是咱们自己编写的,继承ChannelInboundHandlerAdapter,实现你自己的逻辑
        channel.pipeline().addLast(new ClientHandler());

    }

}

至此就完成啦
3.使用

// 从连接池拿到连接
    Channel channel = this.channelPool.acquire().get();

        // 写出数据
        channel.write("xxxx");

        // 连接放回连接池,这里一定记得放回去
        this.channelPool.release(channel);

其中FixedChannelPool还有很多构造方法,包括获取连接的时候也有很多重载,详细的使用还是多看看官方文档

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值