Several methods of java database connection pool configuration

Today, I encountered a problem about the configuration of the data source connection pool. I found that there are many ways to configure it. The summary is as follows, and I hope it will help you: (Mysql database is used as an example)

First, Tomcat configuration data source:

Method 1: Create a folder META-INF under WebRoot, and create a file context.xml in it, the content is as follows:
< Context>
     <Resource name="jdbc/test" auth="Container" type="javax.sql.DataSource"
     maxActive="50" maxIdle="30" maxWait="10000" logAbandoned="true"
     username="root" password="111111" driverClassName="com.mysql.jdbc.Driver"
     url="jdbc:mysql:// localhost:3306/testdb" />
</Context>

Method 2: In the context.xml under the directory conf of tomcat6.0, modify the original context tag and change it to the following content:
< Context>

    <!-- Default set of monitored resources -->
    <WatchedResource>WEB-INF/web.xml</WatchedResource>

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

</Context>

Method 3: When configuring the virtual directory, that is, when configuring the server.xml under conf, change the context tag to the following form:
< Context path="/WebRoot" reloadable="true" docBase="E:/workspace /DataSource/WebRoot" >
    <Resource name="jdbc/test" auth="Container" type="javax.sql.DataSource"
    maxActive="50" maxIdle="30" maxWait="10000" logAbandoned="true"
    username ="root" password="111111" driverClassName="com.mysql.jdbc.Driver"
    url="jdbc:mysql://localhost:3306/testdb" />
< /Context> 

The meaning of each attribute in the Resource tag in the configuration file:

driverClassName - The full class name of the database driver used by JDBC.

maxActive - The maximum number of active connections provided by the connection pool at the same time.

maxIdle - The maximum number of connections the connection pool will keep during idle time.

maxWait - The maximum number of milliseconds the database waits when an exception occurs (when no connections are available).

password - the password to connect to the database.

url - The URL to connect to the driver. (For backward compatibility, DRIVERNAME is also allowed.)

user - the database username.

The scope of various configuration methods should also be different. I won't go into details here, in short, just configure a Resource tag under the Context tag.

Test code:
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/test");
System. out.println(ds.getConnection()); If
it is not null, it should be successful.
Note that when testing, you need to test in tomcat, that is, in the container of TOMCAT (don't bother, write a simple JSP page to test, just use <%...%>, it's quite simple) . If it is not tested in the tomcat container, an exception will be thrown:

... javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial

Second, Hibernate has three ways to configure connection pools:

Method 1 Use the connection pool that comes with Hibernate.

<hibernate-configuration>
< session-factory >
< !--JDBC driver-->
< property name="connection.driver_class">com.mysql.jdbc.Driver</property>
< !-- URL to connect to database- ->
< property name="connection.url">
jdbc:mysql://localhost:3306/feifei
< /property>
< !--Connection login-->
< property name="connection.username">root< /property>
< !--Login password-->
< property name="connection.password"></property>
< !--Whether to output the SQL generated during runtime to the log for debugging-->
< property name= "show_sql">true</property>
< !--Specify the language of the connection-->
< property name="dialect">org.hibernate.dialect.MySQLDialect</property>
< !--mapping resource-->
< mapping resource="/xx/xx.hbm.xml" />
< /session-factory>
< /hibernate-configuration>
My own configuration is as follows, the commented part is public, and other connection pools need to be used!
< hibernate-configuration>
< session-factory>
< property name="show_sql">true</property>
< !-- common conf dbcp/c3p0 needed
< property name="connection.username">informix</property>
< property name="connection.password">informix</property>
< property name="connection.driver_class">com.informix.jdbc.IfxDriver</property>
< property name="connection.url">
jdbc:informix-sqli: //192.168.0.188:1526/db_crm:informixserver=ol_sx;NEWLOCALE=zh_cn,en_us;NEWCODESET=gbk,8859_1,819;
</property>

com.huatech.sysframe.webapp.common.dao.hibernate.dialet.BaseInformixDialect
< /property>
-->
... ... ... ...
< /session-factory>
< /hibernate-configuration>

===================================================== ================================
Method 2: Use the database connection pool specified by the configuration file.
The connection pool now has dbcp, c3p0, and proxoop. In fact, I knew that
the configuration of dbcp and c3p0 in dbcp only needs to add some configuration to the above configuration, and hibernate will automatically identify the database connection pool.

配置dbcp需要加入:
< !-- dbcp conf
< property name="dbcp.maxActive">100</property>
< property name="dbcp.whenExhaustedAction">1</property>
< property name="dbcp.maxWait">60000</property>
< property name="dbcp.maxIdle">10</property>

<property name="dbcp.ps.maxActive">100</property>
< property name="dbcp.ps.whenExhaustedAction">1</property>
< property name="dbcp.ps.maxWait">60000</property>
< property name="dbcp.ps.maxIdle">10</property>
-->
配置c3p0需要加入:
< !-- c3p0 conf
< property name="c3p0.min_size">5</property>
< property name="c3p0.max_size">30</property>
< property name="c3p0.time_out">1800</property>
< property name="c3p0.max_statement">50</property>
-->

The configuration of proxoop is a bit different, you can't just add it, but also need to change: the
basic configuration is as follows:
< property name="proxool.pool_alias">dbpool</property>
< property name="proxool.xml">test/huatech/conf/ProxoolConf. xml</property>
< property name="connection.provider_class">org.hibernate.connection.ProxoolConnectionProvider</property>

Special attention: The path of the following files must be configured correctly, otherwise the FileNotFound
associated file: test/huatech/conf/ProxoolConf.xml is configured as follows:

<?xml version="1.0" encoding="utf-8"?>
< something-else-entirely>
< proxool>
< alias>dbpool</alias>
< !--proxool can only manage connections generated by itself-- >
<driver-url>
jdbc:informix-sqli://192.168.0.188:1526/db_crm:informixserver=ol_sx;NEWLOCALE=zh_cn,en_us;NEWCODESET=gbk,8859_1,819;
</driver-url>
< driver-class >com.informix.jdbc.IfxDriver</driver-class>
< driver-properties>
< property name="user" value="informix" />
< property name="password" value="informix" />
< /driver -properties>
<!-- The time interval (milliseconds) that proxool automatically detects the status of each connection, the idle connection is recovered immediately, and the timeout is destroyed -->
<house-keeping-sleep-time>90000</house-keeping-sleep-time>
< !-- refers to the maximum number of requests waiting in the queue because there is no idle connection to allocate, and user connections that exceed this number of requests will not be connected will be accepted -->
< maximum-new-connections>20</maximum-new-connections>
< !-- Minimum number of idle connections to keep -->
< prototype-count>5</prototype-count>
< !-- Maximum number of connections allowed, If this connection is exceeded, when there are more requests, it will wait in the queue. The maximum number of waiting requests is determined by maximum-new-connections -->
< maximum-connection-count>100</maximum-connection-count>
< ! -- Minimum number of connections-->
< minimum-connection-count>10</minimum-connection-count>
< /proxool>
< /something-else-entirely>

=================================================================================

Method 3: Obtain the connection pool from the container (such as: Tomcat)
and use the connection pool of the server itself: such as Tomcat, resin, weblogic, etc. The
hibernate configuration is as follows:
< !--
< property name="hibernate.connection.datasource">
java :comp/env/jdbc/crm
< /property>
< property name="show_sql">true</property>
< property name="dialect">
com.huatech.sysframe.webapp.common.dao.hibernate.dialet.BaseInformixDialect
< /property>
< property name="hibernate.generate_statistics">true</property>
-->
where jdbc/crm of java:comp/env/jdbc/crm is the name of the database connection pool in the corresponding server, which needs to be set in the corresponding configuration in the environment

The Tomcat configuration is described in the first Tomcat configuration method. Note that the name of jndi should be modified according to the situation and should correspond to the name used by hibernate.

===================================================== ================================
The above configuration needs to use the jar package of the respective database connection pool, which is in the hibernate package , if you need the latest one, you can download it from the respective website.

Third, the method of Spring configuration connection pool:

<bean id="dataSource"  class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
  <property name="driverClassName">
    <value>com.mysql.jdbc.Driver</value>
  </property>
  <property name="url">
    <value>jdbc:mysql://localhost:3306/dbname</value>
  </property>
  <property name="username">
     <value>root</value>
  </property>
  <property name="password">
     <value>******</value>
  </property>
  <property name="maxActive">  

     <value>100</value>
  </property>
  <property name="maxWait">

     <value>1000</value>
  </property>
  <property name="maxIdle">
     <value>30</value>
  </property>

  <property name="defaultAutoCommit">
     <value>true</value>  
  </property>
  <property name="removeAbandoned"> //自动回收连接池,避免连接池泄露
     <value>true</value> 
  </property>
  <property name="removeAbandonedTimeout">
     <value>60</value> 
  </property>

</bean>

Fourth, and the last one I want to talk about today, is to configure the connection pool by writing code. The code is as follows:

import  java.sql.*;

import  java.sql.DataSource;

import  org.apache.commons.dbcp.BasicDataSource;

public class ConnectionPool{

    private static BasicDataSource dbs = null;

    public static DataSource setupDataSource(){

        bds = new BasicDataSource();

        //set the driver

        bds.sestDriverClassName("com.mysql.jdbc.Driver");

        //Set the connection user name

        bds.setUsername("root");

        //Set the connection password

        bds.setPassword("root");

        //Set the connection address

        bds.setUrl("jdbc:mysql://localhost:3306/databasename");

        //Set the total number of initialized connections

        bds.setInitialSize(50);

        //Set the total number of connections applied at the same time

        bds.setMaxActive(-1);

        //Set the maximum number of connections in the buffer pool

        bds.setMaxIdle(-1);

        //Set the minimum number of connections in the buffer pool

        bds.setMinIdle(0);

        //Set the maximum waiting time

        bds.setMaxWait(-1);

        return (DataSource)bds;

    }

    //Method to display the number of connections in the connection pool

    public static void printDataSourceStats(DataSource ds) throws SQLException{

        bds = (BasicDataSource)ds;

        System.out.println();

        System.out.println();

    }

     // method to close the connection pool

     public static void shutdownDataSource(DataSource ds) throws SQLException{

         bds = (BasicDataSource)ds;

         bds.close();

     }

}

To get the connection pool only use the static method setupDataSource() of this class

The above are several methods of configuring database connection pools that I have summarized. These are just a few commonly used configuration methods. There should be other methods. As long as you put in the effort, you can always find a configuration method that suits you. I wish you good luck!

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325490557&siteId=291194637