java 數據庫連接池配置

連接池配置所需jar包

Servlet-api.jar自行導入Tomcat 目錄下的jar包,其餘jar包如果沒有的話

請看下載鏈接----->  下載  (沒有辦法設置成免費,設成最低一積分下載了)

下載入口2 : YouDaoNote

這些jar包可以配置dbcp,c3p0等主流連接池配置

DBCP連接池配置

配置文件dp.properties建議房子src目錄下

配置文件的內容如下

db.driverClassName=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/databasename
db.username=username
db.password=password
dataSource.initialSize=10
dataSource.maxIdle=60
dataSource.minIdle=10
dataSource.maxActive=80
dataSource.maxWait=3000
removeAbandonedOnMaintenance=true
removeAbandonedOnBorrow=true
removeAbandonedTimeout=30

根據自己的數據庫配置修改對應的參數即可。

連接池連接獲取類

構建獲取連接的類,內容如下

package xxx.sqlcon;

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

import org.apache.commons.dbcp2.BasicDataSource;
public class ConnectionPool {
	private static BasicDataSource basicDataSource;

    /**
    * 讀取配置文件,並且初始化連接池
    */
    private static void init(){
        // 根據上面所放類路徑讀取配置文件
        java.io.InputStream inputStream = ConnectionPool.class.getClassLoader()
                .getResourceAsStream("db.properties");
        Properties properties = new Properties();
        try {
            // 加載properties文件
            properties.load(inputStream);

            // 新建一個BasicDataSource
            basicDataSource = new BasicDataSource();

            // 設置對應的參數
            basicDataSource.setUrl(properties.getProperty("db.url"));
            basicDataSource.setDriverClassName(properties.getProperty("db.driverClassName"));
            basicDataSource.setUsername(properties.getProperty("db.username"));
            basicDataSource.setPassword(properties.getProperty("db.password"));

            basicDataSource.setInitialSize(Integer.parseInt(properties.getProperty("dataSource.initialSize")));
            basicDataSource.setMaxIdle(Integer.parseInt(properties.getProperty("dataSource.maxIdle")));
            basicDataSource.setMinIdle(Integer.parseInt(properties.getProperty("dataSource.minIdle")));
            basicDataSource.setMaxWaitMillis(Integer.parseInt(properties.getProperty("dataSource.maxWait")));
            basicDataSource.setMaxTotal(Integer.parseInt(properties.getProperty("dataSource.maxActive")));

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 獲得Connection
     * @return Connection
     */
     public synchronized static Connection getConnection(){
            if (basicDataSource == null){
                init();
            }
            try {
                return basicDataSource.getConnection();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return null;
      }
}

調用getConnection() 函數即可獲得一個可用連接。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章