使用common pool2实现资源的池化

2018-04-22  本文已影响0人  luhuancheng
空间换时间
使用common pool2实现资源的池化
实例,实现rabbitmq channel的池化
// 实现接口PooledObjectFactory
package com.luhc.pool;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConnectionFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.DefaultPooledObject;

/**
 * @author luhuancheng
 * @since 2018/4/22 21:37
 */
public class MyRabbitMQChannelPoolFactory implements PooledObjectFactory<Channel> {

    private ConnectionFactory factory;

    public MyRabbitMQChannelPoolFactory(ConnectionFactory factory) {
        this.factory = factory;
    }

    @Override
    public PooledObject<Channel> makeObject() throws Exception {
        // 池对象创建实例化资源
        return new DefaultPooledObject<>(factory.newConnection().createChannel());
    }

    @Override
    public void destroyObject(PooledObject<Channel> p) throws Exception {
        // 池对象销毁资源
        if (p != null) {
            p.getObject().close();
        }
    }

    @Override
    public boolean validateObject(PooledObject<Channel> p) {
        // 验证资源是否可用
        return p.getObject().isOpen();
    }

    @Override
    public void activateObject(PooledObject<Channel> p) throws Exception {

    }

    @Override
    public void passivateObject(PooledObject<Channel> p) throws Exception {

    }
}

// 自定义池
package com.luhc.pool;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConnectionFactory;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

/**
 * @author luhuancheng
 * @since 2018/4/22 21:41
 */
public class MyRabbitMQChannelPool {

    private GenericObjectPool<Channel> pool;

    public MyRabbitMQChannelPool(ConnectionFactory factory, GenericObjectPoolConfig poolConfig) {
        this.pool = new GenericObjectPool<>(new MyRabbitMQChannelPoolFactory(factory), poolConfig);
    }

    public Channel getChannel() {

        try {
            return pool.borrowObject();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public void returnChannel(Channel channel) {
        if (channel != null) {
            pool.returnObject(channel);
        }
    }
}

上一篇 下一篇

猜你喜欢

热点阅读