DBCP数据源的使用

DBCP(DataBase Connection Pool)是一个开源的数据源工具,实际开发直接使用就行了

导入需要的jar包,数据库使用mysql测试

配置文件就是一个properties文件,key-value值按规范写就行了

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/blogs_stu
username=root
password=
#初始化连接数
initialSize=10
#最大连接数
maxActive=50
#最大空闲连接
maxIdle=20
#最小空闲连接 minIdle=5 //超时等待时间,单位为毫秒 maxWait=60000 #附带的连接属性 connectionProperties=useUnicode=true;characterEncoding=utf8 #事物默认自动提交 defaultAutoCommit=true
#设置数据库是否为只读,不设置表示否
defaultReadOnly=
#设置事物的隔离级别。可选值NONE,READ_UNCOMMITTED,READ_COMMITTED,REPEATABLE_READ,SERIALIZABLE
#一般都是选REPEATABLE_READ,能避免脏读,不可重复读,但可能会虚读(为了性能这点牺牲还是值得的)
defaultTransactionIsolation=REPEATABLE_READ

工具类DBCPUtil

public class DBCPUtil {
    private static DataSource ds;
    static{
        try {
            InputStream is=DBCPUtil.class.getClassLoader().getResourceAsStream("dbcpconfig.properties");
            Properties p=new Properties();
            p.load(is);
            ds=BasicDataSourceFactory.createDataSource(p);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static Connection getConnection(){
        try {
            return ds.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static void release(Connection conn,Statement stmt,ResultSet rs){
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            conn=null;
        }
        if(stmt!=null){
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            stmt=null;
        }
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            rs=null;
        }
    }
}

测试下打印一下该Connection对象,会发现其实该工具就是使用了一个包装类包装了原有的Connection接口实现类,

扩展了close方法,以实现将用完的Connection对象放回连接池中

public class Test6{
    public static void main(String[] args) throws SQLException  {
        Connection conn=DBCPUtil.getConnection();
        System.out.println(conn.getClass().getName());
    }
}

所以如果调用DBCPUtil中的close方法其实是调用包装类中扩展的close方法,该方法将Connection对象放回连接池。

 

posted on 2016-08-29 15:33  pokid  阅读(455)  评论(0编辑  收藏  举报

导航