JDBC -- Connection Pool

Connection Pool: create many connection objects in advance, and put the connection into the cache(list). The client will get the connection from the cache, return the connectio to the cache after using it. This way could improve the access effeciency of data base.

Simulate the connection pool:

package com.pp.pool;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

import com.pp.util.JdbcUtil;

/*
 * Simulate the completion of connetion pool
 */
public class SimpleConnectionPool {
    private static List<Connection> pool = new ArrayList<Connection>();

    static {
        for (int i = 0; i < 10; i++) {
            Connection conn = JdbcUtil.getConnection();
            pool.add(conn);
        }

    }

    // get the connection object from cache pool
    public synchronized static Connection getConnection() {
        if (pool.size() > 0) {
            Connection conn = pool.remove(0);
            return conn;
        } else {
            throw new RuntimeException("Server is busy!");
        }
    }

    // return the connection
    public static void releas(Connection conn) {
        pool.add(conn);
    }
}

 DBCP: DataBaseConnectionPool

package com.pp.util;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSourceFactory;

public class DBCPUtil {
    private static DataSource dataSource;
    static {
        try {
            InputStream in = DBCPUtil.class.getClassLoader()
                    .getResourceAsStream("dbcpconfig.properties");
            Properties prop = new Properties();
            prop.load(in);
            dataSource = BasicDataSourceFactory.createDataSource(prop);
        } catch (Exception e) {
            throw new RuntimeException("Fail to initialize the data source!");
        }
    }

    public static Connection getConneciton() {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException("Fail to get the connection!");
        }
    }

    public static DataSource getDataSource() {
        return dataSource;
    }
}

 dbcpconfig.properties:

#连接设置
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/day17
username=root
password=root

#<!-- 初始化连接 -->
initialSize=10

#最大连接数量
maxActive=50

#<!-- 最大空闲连接 -->
maxIdle=20

#<!-- 最小空闲连接 -->
minIdle=5

#<!-- 超时等待时间以毫秒为单位 6000毫秒/1000等于60秒 -->
maxWait=60000


#JDBC驱动建立连接时附带的连接属性属性的格式必须为这样:[属性名=property;] 
#注意:"user" 与 "password" 两个属性会被明确地传递,因此这里不需要包含他们。
connectionProperties=useUnicode=true;characterEncoding=utf8

#指定由连接池所创建的连接的自动提交(auto-commit)状态。
defaultAutoCommit=true

#driver default 指定由连接池所创建的连接的只读(read-only)状态。
#如果没有设置该值,则“setReadOnly”方法将不被调用。(某些驱动并不支持只读模式,如:Informix)
defaultReadOnly=

#driver default 指定由连接池所创建的连接的事务级别(TransactionIsolation)。
#可用值为下列之一:(详情可见javadoc。)NONE,READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE
defaultTransactionIsolation=REPEATABLE_READ

C3P0:

package com.pp.util;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class C3P0Util {
    private static ComboPooledDataSource dataSource = new ComboPooledDataSource();
//    static {
//        try {
//            dataSource.setDriverClass("com.mysql.jdbc.Driver");
//            dataSource.setJdbcUrl("jdbc:mysql:///day17");
//            dataSource.setUser("root");
//            dataSource.setPassword("root");
//            dataSource.setMaxPoolSize(50);
//            dataSource.setMinPoolSize(5);
//            dataSource.setInitialPoolSize(10);
//        } catch (Exception e) {
//            throw new ExceptionInInitializerError("初始化失败!");
//        }
//    }

    public static Connection getConnection() {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public static DataSource getDataSourece() {
        return dataSource;
    }
}

Use config file to configure the connection pool:

c3p0-config.xml:

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
    <default-config>
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql:///day17</property>
        <property name="user">root</property>
        <property name="password">root</property>

        <property name="initialPoolSize">10</property>
        <property name="maxIdleTime">30</property>
        <property name="maxPoolSize">100</property>
        <property name="minPoolSize">10</property>
        <property name="maxStatements">200</property>
    </default-config>
    <!-- This app is massive! -->
    <named-config name="intergalactoApp">
        <property name="initialPoolSize">100</property>
        <property name="minPoolSize">50</property>
        <property name="maxPoolSize">1000</property>
        <property name="maxStatements">200</property>
    </named-config>
</c3p0-config>

How to manage the data source in Tomcat?

  Once the Tomcat configure the data source, the data source will be put in the JNDI container via JNDI

  JNDI: Java Naming and Directory Interface, like a Map<String,Object> container.

  How to configure?

    1. copy the data base driver jar file to the Tomcatlib directory

    2. create a context.xml configuring file in the META-INF directory:

    context.xml:

<?xml version="1.0" encoding="UTF-8"?>
<Context>
    <Resource name="jdbc/day17" auth="Container" type="javax.sql.DataSource"
        maxActive="20" maxIdle="50" maxWait="10000" username="root"
        password="root" driverClassName="com.mysql.jdbc.Driver"
        url="jdbc:mysql://localhost:3306/day17" />
</Context>

    3. get the created data source from JNDI container: write the fowlling code in the JSP.

  <%
        Context initContext = new InitialContext();
        Context envContext = (Context) initContext.lookup("java:/comp/env");
        DataSource ds = (DataSource) envContext.lookup("jdbc/day17");
        Connection conn = ds.getConnection();
        response.getWriter().write(conn.toString());
    %>

    

原文地址:https://www.cnblogs.com/ppcoder/p/7484301.html