Netty 连接池的使用姿势

netty版本 4.1.9.Final

一、类介绍

1.ChannelPool ,连接池接口

2.SimpleChannelPool,实现ChannelPool接口,简单的连接池实现

3.FixedChannelPool,继承SimpleChannelPool,有大小限制的连接池实现

4.ChannelPoolMap,管理host与连接池映射的接口

5.AbstractChannelPoolMap,抽象类,实现ChannelPoolMap接口

二、具体使用

我们以http协议的实现来使用连接池,直接上代码

1.ClientPool

public class ClientPool{

    //key为目标host,value为目标host的连接池
    public ChannelPoolMap<InetSocketAddress, FixedChannelPool> poolMap = null;


    public ClientPool(){
        init();
    }

    public void init(){
        EventLoopGroup group = new NioEventLoopGroup();
        final Bootstrap cb = new Bootstrap();

        cb.group(group).channel(NioSocketChannel.class);

        poolMap = new AbstractChannelPoolMap<InetSocketAddress, FixedChannelPool>() {
            @Override
            protected FixedChannelPool newPool(InetSocketAddress key) {
                return new FixedChannelPool(cb.remoteAddress(key), new ChannelPoolHandler() {
                    public void channelReleased(Channel ch) throws Exception {
                        System.out.println("22");
                    }

                    public void channelAcquired(Channel ch) throws Exception {
                        System.out.println("33");
                    }

                    public void channelCreated(Channel ch) throws Exception {
                        //可以在此绑定channel的handler
                        ch.pipeline().addLast(new HttpClientCodec())
                                .addLast(new HttpObjectAggregator(1024 * 1024))
                                .addLast(new HttpBackendHandler());
                    }
                },20);//单个host连接池大小
            }
        };

    }

    public void getHttpClient(InetSocketAddress address,final FullHttpRequest msg) {
        if(address == null){
            throw new RuntimeException("InetSocketAddress can not be null");
        }

        final FixedChannelPool pool = this.poolMap.get(address);

        Future<Channel> f = pool.acquire();

        future.addListener(new FutureListener<Channel>() {

            public void operationComplete(Future<Channel> f) {
                if (f.isSuccess()) {
                    Channel ch = f.getNow();
                    ChannelFuture lastWriteFuture = null;

                    lastWriteFuture = ch.writeAndFlush(msg);

                    // Wait until all messages are flushed before closing the channel.
                    if (lastWriteFuture != null) {

                        try {
                            lastWriteFuture.sync();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                    pool.release(ch);
                }
            }
        });
    }

}

2.HttpBackendHandler

public class HttpBackendHandler extends SimpleChannelInboundHandler<FullHttpResponse> {


    public HttpBackendHandler() {
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("Backend Handler is Active!");
        super.channelActive(ctx);
    }

    @Override
    public void channelRead0(final ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception {
         //todo something
    }
    
    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        System.out.println("Backend Handler destroyed!");
    }
    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        if (ctx.channel().isActive()) {
            ctx.channel().writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
        }
    }
}

3.使用

public class NettyHttpClientPoolTest {

    public static void main(String[] args){
        ClientPool pool = new ClientPool();
        InetSocketAddress address = new InetSocketAddress("127.0.0.1",8080;
        FullHttpRequest request = new DefaultFullHttpRequest(..);
        pool.sendMsg(address,request);
    }

}

代码有些未完善,需要自己完善一哈,本文主要是做下学习记录

转载于:https://my.oschina.net/jayhu/blog/863572

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值