Open source database connection pool

Part blog just finished how to customize a database connection pool, of course, since this database connection pool definition is very simple, by virtue of their ability can not write good connection pool. But do not worry, we can use the open-source database connection pool, open-source advantage is reflected here.

There are three open source in Java database connection pool provides an independent source of data to achieve:

  • DBCP database connection pool
  • C3P0 database connection pool
  • Apache Tomcat built-in connection pool (apache dbcp)
1, DBCP database connection pool

DBCP connection pool is open source under the Apache Software Foundation implemented using DBCP data source, the application should add the following two jar files in the system:

  • commons-dbcp.jar
  • commons-pool.jar

Today's jar package resources I also put on the network drive. Link: https: //pan.baidu.com/s/1-Rj4TQLI_5DGLdfb45N62g
extraction code: ba3a
copy the contents of this open Baidu network disk phone App, the operation more convenient oh
jar package ready, so let's use it.
Create a new Java project.
Then create a test class DBCPTest, write test code

@Test
public void demo1(){
    //首先使用BasicDataSource创建连接池
    BasicDataSource basicDataSource = new BasicDataSource();
    try {
        //从连接池中获取连接
        Connection connection = basicDataSource.getConnection();
        String sql = "select * from account";
        PreparedStatement stmt = connection.prepareStatement(sql);
        ResultSet set = stmt.executeQuery();
        while(set.next()){
            System.out.println(set.getString("name"));
        }
        //释放资源
        JDBCUtils.release(stmt, connection);
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

Now run the test code, can check out the table data?
Apparently, even the database did not give the parameters, this test code will certainly be an error.
That now to set about the parameters, modify the test code

@Test
public void demo1(){
    //首先使用BasicDataSource创建连接池
    BasicDataSource basicDataSource = new BasicDataSource();
    //创建连接需要四个参数
    basicDataSource.setDriverClassName("com.mysql.jdbc.Driver");
    basicDataSource.setUrl("jdbc:mysql:///test");
    basicDataSource.setUsername("root");
    basicDataSource.setPassword("123456");
    try {
        //从连接池中获取连接
        Connection connection = basicDataSource.getConnection();
        String sql = "select * from account";
        PreparedStatement stmt = connection.prepareStatement(sql);
        ResultSet set = stmt.executeQuery();
        while(set.next()){
            System.out.println(set.getString("name"));
        }
        //释放资源
        JDBCUtils.release(stmt, connection);
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

Now run the test code
Here Insert Picture Description
successfully query to the table data. But this writing has limitations, should be written to the database parameter configuration file to accommodate flexible user needs.
New Profile dbcp.properties in the src directory

driverClassName = com.mysql.jdbc.Driver
url = jdbc:mysql:///test
username = root
password =123456

Write test code

@Test
public void demo2() throws Exception{
    //读取dbcp.properties
    Properties properties = new Properties();
    properties.load(new FileInputStream(this.getClass().getResource("/dbcp.properties").getFile()));
    DataSource dataSource = BasicDataSourceFactory.createDataSource(properties);
    //从连接池中获取连接
    Connection connection = dataSource.getConnection();
    String sql = "select * from account";
    PreparedStatement stmt = connection.prepareStatement(sql);
    ResultSet set = stmt.executeQuery();
    while(set.next()){
        System.out.println(set.getString("name"));
    }
    //释放资源
    JDBCUtils.release(stmt, connection);
}

Then run
Here Insert Picture Description
run successfully.
Attach a more comprehensive configuration file.

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

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

#最大连接数量
maxActive=50

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

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

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


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

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

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

Download jar package: https://sourceforge.net/projects/c3p0/
official website address: https://www.mchange.com/projects/c3p0/
official website download and there was an inlet, and tutorial database connection pool.
Documents tutorial official website is very detailed, so it is, but more details.
Directly on the case.
Write test code

@Test
public void demo1() throws Exception{
    //创建一个连接池
    ComboPooledDataSource dataSource = new ComboPooledDataSource();
    //设置四个参数
    dataSource.setDriverClass("com.mysql.jdbc.Driver");
    dataSource.setJdbcUrl("jdbc:mysql:///test");
    dataSource.setUser("root");
    dataSource.setPassword("123456");
    
    Connection connection = dataSource.getConnection();
    String sql = "select * from account";
    PreparedStatement stmt = connection.prepareStatement(sql);
    ResultSet set = stmt.executeQuery();
    while(set.next()){
        System.out.println(set.getString("name"));
    }
    JDBCUtils.release(stmt, connection);
}

Note that, if you run Times ClassNotFoundExecption abnormalities, indicating that your jar package version is later c3p0-0.9.2, version after version of the need to add a secondary package, mchange-commons-java-0.2.3.4.jar .
This is the download address a jar. Link: https: //pan.baidu.com/s/17o0s92Us-UPQPJFeJjpOzQ
extraction code: lt2v
copy the contents of this open Baidu network disk phone App, the operation more convenient oh

Similarly, the configuration file to achieve it.
In the src directory New File 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:///test</property>
        <property name="user">root</property>
        <property name="password">123456</property>
        
        <property name="automaticTestTable">con_test</property>
        <property name="checkoutTimeout">30000</property>
        <property name="idleConnectionTestPeriod">30</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>

        <user-overrides user="test-user">
            <property name="maxPoolSize">10</property>
            <property name="minPoolSize">1</property>
            <property name="maxStatements">0</property>
        </user-overrides>

    </default-config>

    <!-- This app is massive! -->
    <named-config name="intergalactoApp">
        <property name="acquireIncrement">50</property>
        <property name="initialPoolSize">100</property>
        <property name="minPoolSize">50</property>
        <property name="maxPoolSize">1000</property>

        <!-- intergalactoApp adopts a different approach to configuring statement 
            caching -->
        <property name="maxStatements">0</property>
        <property name="maxStatementsPerConnection">5</property>

        <!-- he's important, but there's only one of him -->
        <user-overrides user="master-of-the-universe">
            <property name="acquireIncrement">1</property>
            <property name="initialPoolSize">1</property>
            <property name="minPoolSize">1</property>
            <property name="maxPoolSize">5</property>
            <property name="maxStatementsPerConnection">50</property>
        </user-overrides>
    </named-config>
</c3p0-config>

This is copied directly from the official document down. Then add the four database configuration parameters needed.
Then write test code

@Test
public void demo2() throws Exception{
    //使用c3p0配置文件
    ComboPooledDataSource dataSource = new ComboPooledDataSource();
    Connection connection = dataSource.getConnection();
    String sql = "select * from account";
    PreparedStatement stmt = connection.prepareStatement(sql);
    ResultSet set = stmt.executeQuery();
    while(set.next()){
        System.out.println(set.getString("name"));
    }
    JDBCUtils.release(stmt, connection);
}

Note, c3p0 database connection pool is not required to manually load the configuration file, c3p0 very humane, this step has been good package. After you create an object directly call ComboPooledDataSource getConnection () method to get connected. Provided that your configuration file name must be c3p0-config.xml, and the file must be placed under the src directory. As for some other configuration information in the document had a meaning, you can learn to read on their own.

ComboPooledDataSource There are two ways to create an object, call the constructor without parameters using a configuration file in the default configuration, but if you call the constructor have parameters, the configuration file tag name attribute values ​​passed, will use the configuration information in the tag.

3, Tomcat built connection pool

Need to know is, Tomcat connection pool is content DBCP.
We know that will be deployed to Tomcat web project in three ways:

  • Configuring server.xml, add label
  • Configure a separate xml file, add label
  • Directly copy the Web directory to the Tomcat webapps directory

Any project to be able to run Tomcat, needs a virtual directory. Virtual Directory refers to what? Context refers to the elements. When we need to use connection pooling, you need to make the following configuration Context

<Context path="/DBTest" docBase="DBTest"
        debug="5" reloadable="true" crossContext="true">

    <!-- maxActive: Maximum number of dB connections in pool. Make sure you
         configure your mysqld max_connections large enough to handle
         all of your db connections. Set to -1 for no limit.
         -->

    <!-- maxIdle: Maximum number of idle dB connections to retain in pool.
         Set to -1 for no limit.  See also the DBCP documentation on this
         and the minEvictableIdleTimeMillis configuration parameter.
         -->

    <!-- maxWait: Maximum time to wait for a dB connection to become available
         in ms, in this example 10 seconds. An Exception is thrown if
         this timeout is exceeded.  Set to -1 to wait indefinitely.
         -->

    <!-- username and password: MySQL dB username and password for dB connections  -->

    <!-- driverClassName: Class name for the old mm.mysql JDBC driver is
         org.gjt.mm.mysql.Driver - we recommend using Connector/J though.
         Class name for the official MySQL Connector/J driver is com.mysql.jdbc.Driver.
         -->
    
    <!-- url: The JDBC connection url for connecting to your MySQL dB.
         -->

  <Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource"
               maxActive="100" maxIdle="30" maxWait="10000"
               username="javauser" password="javadude" driverClassName="com.mysql.jdbc.Driver"
               url="jdbc:mysql://localhost:3306/javatest"/>

</Context>

It was copied down from the official website.
Then the Context configuration element of it where?
Context elements arranged three positions:

  • Tomcat installation directory /conf/context.xml (If you connect to the pool configuration file, it will valid for any current project all internal Tomcat virtual host)
  • Tomcat installation directory / conf / Catalina / virtual host directory /context.xml (If you connect to the pool configuration file, it will works on any current virtual hosts are valid)
  • The root of the web project /META-INF/context.xml (If you connect to the pool configuration file will only be valid for the current project)

The next presentation about a third configuration
META-INF files in the folder WebRoot create a new file context.xml

<?xml version="1.0" encoding="UTF-8"?>
<Context path="/DBTest" docBase="DBTest" debug="5" reloadable="true"
    crossContext="true">

    <Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource"
        maxActive="100" maxIdle="30" maxWait="10000" username="root"
        password="123456" driverClassName="com.mysql.jdbc.Driver"
        url="jdbc:mysql://localhost:3306/test" />

</Context>

After context.xml file write completed, start the Tomcat server, Tomcat will go automatically load the file and create a database connection pool, located in a Tomcat container. At this point we will be able to use JNDI technology to access the database connection pool.
JNDI children's shoes do not understand the technology, we can mention here a little

JNDI (Java Naming and Directory Interface) , Java Naming and Directory Interface, which corresponds to the J2SE javax.naming package,
the main effect is that this API: Java object that can be placed in a container (container support JNDI Tomcat) and a name for the container java objects, after the program want to get Java objects, just to name search through.
The core API is Context, which represents the JNDI container object retrieval method lookup name corresponding container.

Note:
Tomcat create a connection pool, database-driven need to connect with the database, copy the file to the lib mysql.jar under the Tomcat directory folder.
Java program in order to access objects through JNDI, it must be run in the same JNDI container. That is, the Java program must be run inside Tomcat, so using JNDI program generally Servlet or JSP.

Show you.
In a new project file is TomcatServlet Servlet

/**
 * 在该程序中,通过JNDI访问Tomcat内部的连接池
 * @author Administrator
 *
 */
public class TomcatServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            //创建一个检索的对象
            Context initCtx = new InitialContext();
            //默认查找顶级的Java名称串    这是固定的:java:comp/env
            Context envCtx = (Context) initCtx.lookup("java:comp/env");
            //根据设置名称查找连接池对象
            DataSource ds = (DataSource) envCtx.lookup("jdbc/TestDB");
            //获得连接池中的一个连接
            Connection conn = ds.getConnection();
            String sql = "select * from account";
            PreparedStatement stmt = conn.prepareStatement(sql);
            ResultSet set = stmt.executeQuery();
            while(set.next()){
                System.out.println(set.getString("name"));
            }
            JDBCUtils.release(stmt, conn);
        } catch (NamingException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

}

Do not forget to database-driven, copy the mysql-connector-java-5.1.47- bin.jar to install Tomcat lib directory of the file folder, and then run in MyEclipse deployment project. Then visit Servlet program in your browser
Here Insert Picture Description
instructions query is successful.

Guess you like

Origin www.cnblogs.com/blizzawang/p/11411383.html