关于netty的ChannelPoolMap

时间:2015-06-17 09:24:54

标签: netty

我试图将netty用作Key-value数据库的客户端,很高兴找到netty 4.0.28.Final提供本机连接池。

我有一个简单的连接池,如下所示(根据Netty 4.0.28.Final's note):

QdbConnectionPool:

public class QdbConnectionPool {

private ChannelPoolMap<InetSocketAddress,FixedChannelPool> poolMap;

public void init(){
    EventLoopGroup group = new NioEventLoopGroup();
    final Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(group).channel(NioSocketChannel.class)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS,10000);

    poolMap = new AbstractChannelPoolMap<InetSocketAddress, FixedChannelPool>() {
        @Override
        protected FixedChannelPool newPool(InetSocketAddress key) {
            bootstrap.remoteAddress(key);
            return new FixedChannelPool(bootstrap,new QdbPoolHandler(),100);
        }
    };

}

public QdbResult query(InetSocketAddress address,String bkey){
    final QdbResult result = new QdbResult(bkey);
    final CountDownLatch countDownLatch = new CountDownLatch(1);
    final FixedChannelPool pool = poolMap.get(address);
    Future<Channel> future = pool.acquire();
    future.addListener(new FutureListener<Channel>() {
        @Override
        public void operationComplete(Future<Channel> future) {
            if (future.isSuccess()) {
                Channel ch = future.getNow();
                System.out.println(ch.toString());
                ch.pipeline().addLast(new QdbClientHandler(result, countDownLatch));
                ch.pipeline().fireChannelActive();
            } else {
                System.out.println("future not succ");
            }
        }
    });
    try{
        countDownLatch.await();
    }catch (InterruptedException ex){

    }
    pool.release(future.getNow());
    return result;
}

public static void main(String[] args) throws Exception{
    InetSocketAddress address = new InetSocketAddress("127.0.0.1", 8888);
    QdbConnectionPool pool = new QdbConnectionPool();
    pool.init();
    QdbResult result  = pool.query(address, "xxxxxx");        
}

}

QdbPoolHandler带有返回内容的解码器:

public class QdbPoolHandler extends AbstractChannelPoolHandler {


@Override
public void channelCreated(Channel ch) throws Exception{
    ch.pipeline().addLast(new QdbDecoder());
}

}

这是我的理解和我的问题

1)当调用pool.acquire()时,池将进行连接

2)在得到Future之后,我添加QdbClientHanlder()来处理消息发送和接收(QdbClientHandler()将在其自己的channelRead()方法中删除),我是否正确使用它?

3)我通过channel.pipeline()。fireChannelActive()发出请求,我正确使用它吗?有没有其他方法来解雇请求? channel.pipeline()。fireChannelActive()重新定义了ChannelPipeline,我可以从中获得未来吗?

4)我使用CowntDownLatch确保请求完成(countDownLatch&#39;倒计时()方法将在QdbClientHanlder的channelRead()或exceptionCaught()方法中调用),我是否正确使用它?还有其他方法可以确保请求完成吗?

0 个答案:

没有答案