apache Common Pool学习

原文地址:

https://blog.csdn.net/u013332124/article/details/81042375

测试代码

模拟数据库连接代码

package com.lv.db;
/**
 * 自定义一个数据库连接对象,假定该对象创建和销毁都会消耗资源,造成jvm内存不稳定
 */
public class DbConnection {
    private Boolean isActive;

    public Boolean getIsActive() {
        return isActive;
    }

    public void setIsActive(Boolean isActive) {
        this.isActive = isActive;
    }
    
}

池对象工厂

package com.lv.pool;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import com.lv.db.DbConnection;
/**
* DbConnection的工厂类
*/
public class DbConnectionFactory implements PooledObjectFactory{

   public PooledObject makeObject() throws Exception {
       DbConnection dbConnection = new DbConnection();
       //构建一个池对象
       return new DefaultPooledObject(dbConnection);
   }

   public void destroyObject(PooledObject p) throws Exception {
       //断开连接
       p.getObject().setIsActive(false);
   }

   public boolean validateObject(PooledObject p) {
       //判断这个对象是否保持连接状态
       return p.getObject().getIsActive();
   }

   public void activateObject(PooledObject p) throws Exception {
       //激活这个对象让他连接上数据库
       p.getObject().setIsActive(true);
   }

   public void passivateObject(PooledObject p) throws Exception {
       //让对象断开连接
       p.getObject().setIsActive(false);
   }

}

package com.lv.pool;

import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

import com.lv.db.DbConnection;

public class MyPool {
    
    private static GenericObjectPool myPool;
    static{
        DbConnectionFactory factory = new DbConnectionFactory();
        GenericObjectPoolConfig config = new GenericObjectPoolConfig();
        config.setMaxIdle(20);
        config.setMaxTotal(100);
        config.setMinIdle(5);
        myPool = new GenericObjectPool(factory, config);
    }
    
    /**
     * 获取池对象
     */
    public static GenericObjectPool getPool(){
        return myPool;
    }
    
    //测试使用池连接
    public static void main(String[] args) throws Exception {
        GenericObjectPool pool = MyPool.getPool();
        DbConnection connection = pool.borrowObject();
        Boolean isActive = connection.getIsActive();
        System.out.println("isActive---"+isActive);
        pool.returnObject(connection);
    }
    
}

你可能感兴趣的:(apache Common Pool学习)