Java數據庫連接池實現原理
阿新 • • 發佈:2017-12-05
fix 獲取 時有 .get soft div port 構造 定義
①裝載數據庫驅動程序;
②通過jdbc建立數據庫連接;
③訪問數據庫,執行sql語句;
ConnectionPoolTest.java
一般來說,Java應用程序訪問數據庫的過程是:
①裝載數據庫驅動程序;
②通過jdbc建立數據庫連接;
③訪問數據庫,執行sql語句;
④斷開數據庫連接。
[java] view plain copy print?
- public class DBConnection {
- private Connection con; //定義數據庫連接類對象
- private PreparedStatement pstm;
- private String user="root"; //連接數據庫用戶名
- private String password="123456"; //連接數據庫密碼
- private String driverName="com.mysql.jdbc.Driver"; //數據庫驅動
- private String url="jdbc:mysql://localhost:3306/qingqingtuan";
- //連接數據庫的URL,後面的是為了防止插入數據 庫出現亂碼,?useUnicode=true&characterEncoding=UTF-8
- //構造函數
- public DBConnection(){
- }
- /**創建數據庫連接*/
- public Connection getConnection(){
- try{
- Class.forName("com.mysql.jdbc.Driver");
- }catch(ClassNotFoundException e){
- System.out.println("加載數據庫驅動失敗!");
- e.printStackTrace();
- }
- try {
- con=DriverManager.getConnection(url,user,password); //獲取數據庫連接
- } catch (SQLException e) {
- System.out.println("創建數據庫連接失敗!");
- con=null;
- e.printStackTrace();
- }
- return con; //返回數據庫連接對象
- }
- List<Shop> mShopList=new ArrayList<Shop>();
- mConnection=new DBConnection().getConnection();
- if(mConnection!=null){
- try {
- String sql="select * from shop";
- PreparedStatement pstm=mConnection.prepareStatement(sql);
- ResultSet rs=pstm.executeQuery();
- while(rs.next()){
- ......//封裝PoPj的操作
- }
- rs.close();
- pstm.close();
- } catch (SQLException e) {
- e.printStackTrace();
- }finally{
- try {
- if(mConnection!=null){
- mConnection.close();
- }
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
程序開發過程中,存在很多問題:
首先,每一次web請求都要建立一次數據庫連接。建立連接是一個費時的活動,每次都得花費0.05s~1s的時間,而且系統還要分配內存資源。這個時間對於一次或幾次數據庫操作,或許感覺不出系統有多大的開銷。
可是對於現在的web應用,尤其是大型電子商務網站,同時有幾百人甚至幾千人在線是很正常的事。在這種情況下,頻繁的進行數據庫連接操作勢必占用很多的系統資源,網站的響應速度必定下降,嚴重的甚至會造成服務器的崩潰。不是危言聳聽,這就是制約某些電子商務網站發展的技術瓶頸問題。其次,對於每一次數據庫連接,使用完後都得斷開。否則,如果程序出現異常而未能關閉,將會導致數據庫系統中的內存泄漏,最終將不得不重啟數據庫
通過上面的分析,我們可以看出來,“數據庫連接”是一種稀缺的資源,為了保障網站的正常使用,應該對其進行妥善管理。實現getConnection()從連接庫中獲取一個可用的連接
③ returnConnection(conn) 提供將連接放回連接池中方法
ConnectionPool.java
[java] view plain copy print?
- //////////////////////////////// 數據庫連接池類 ConnectionPool.java ////////////////////////////////////////
- /*
- 這個例子是根據POSTGRESQL數據庫寫的,
- 請用的時候根據實際的數據庫調整。
- 調用方法如下:
- ① ConnectionPool connPool
- = new ConnectionPool("com.microsoft.jdbc.sqlserver.SQLServerDriver"
- ,"jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=MyDataForTest"
- ,"Username"
- ,"Password");
- ② connPool .createPool();
- Connection conn = connPool .getConnection();
- connPool.returnConnection(conn);
- connPool.refreshConnections();
- connPool.closeConnectionPool();
- */
- import java.sql.Connection;
- import java.sql.DatabaseMetaData;
- import java.sql.Driver;
- import java.sql.DriverManager;
- import java.sql.SQLException;
- import java.sql.Statement;
- import java.util.Enumeration;
- import java.util.Vector;
- public class ConnectionPool {
- private String jdbcDriver = ""; // 數據庫驅動
- private String dbUrl = ""; // 數據 URL
- private String dbUsername = ""; // 數據庫用戶名
- private String dbPassword = ""; // 數據庫用戶密碼
- private String testTable = ""; // 測試連接是否可用的測試表名,默認沒有測試表
- private int initialConnections = 10; // 連接池的初始大小
- private int incrementalConnections = 5;// 連接池自動增加的大小
- private int maxConnections = 50; // 連接池最大的大小
- private Vector connections = null; // 存放連接池中數據庫連接的向量 , 初始時為 null
- // 它中存放的對象為 PooledConnection 型
- /**
- * 構造函數
- *
- * @param jdbcDriver
- * String JDBC 驅動類串
- * @param dbUrl
- * String 數據庫 URL
- * @param dbUsername
- * String 連接數據庫用戶名
- * @param dbPassword
- * String 連接數據庫用戶的密碼
- *
- */
- public ConnectionPool(String jdbcDriver, String dbUrl, String dbUsername,
- String dbPassword) {
- this.jdbcDriver = jdbcDriver;
- this.dbUrl = dbUrl;
- this.dbUsername = dbUsername;
- this.dbPassword = dbPassword;
- }
- /**
- * 返回連接池的初始大小
- *
- * @return 初始連接池中可獲得的連接數量
- */
- public int getInitialConnections() {
- return this.initialConnections;
- }
- /**
- * 設置連接池的初始大小
- *
- * @param 用於設置初始連接池中連接的數量
- */
- public void setInitialConnections(int initialConnections) {
- this.initialConnections = initialConnections;
- }
- /**
- * 返回連接池自動增加的大小 、
- *
- * @return 連接池自動增加的大小
- */
- public int getIncrementalConnections() {
- return this.incrementalConnections;
- }
- /**
- * 設置連接池自動增加的大小
- *
- * @param 連接池自動增加的大小
- */
- public void setIncrementalConnections(int incrementalConnections) {
- this.incrementalConnections = incrementalConnections;
- }
- /**
- * 返回連接池中最大的可用連接數量
- *
- * @return 連接池中最大的可用連接數量
- */
- public int getMaxConnections() {
- return this.maxConnections;
- }
- /**
- * 設置連接池中最大可用的連接數量
- *
- * @param 設置連接池中最大可用的連接數量值
- */
- public void setMaxConnections(int maxConnections) {
- this.maxConnections = maxConnections;
- }
- /**
- * 獲取測試數據庫表的名字
- *
- * @return 測試數據庫表的名字
- */
- public String getTestTable() {
- return this.testTable;
- }
- /**
- * 設置測試表的名字
- *
- * @param testTable
- * String 測試表的名字
- */
- public void setTestTable(String testTable) {
- this.testTable = testTable;
- }
- /**
- *
- * 創建一個數據庫連接池,連接池中的可用連接的數量采用類成員 initialConnections 中設置的值
- */
- public synchronized void createPool() throws Exception {
- // 確保連接池沒有創建
- // 如果連接池己經創建了,保存連接的向量 connections 不會為空
- if (connections != null) {
- return; // 如果己經創建,則返回
- }
- // 實例化 JDBC Driver 中指定的驅動類實例
- Driver driver = (Driver) (Class.forName(this.jdbcDriver).newInstance());
- DriverManager.registerDriver(driver); // 註冊 JDBC 驅動程序
- // 創建保存連接的向量 , 初始時有 0 個元素
- connections = new Vector();
- // 根據 initialConnections 中設置的值,創建連接。
- createConnections(this.initialConnections);
- // System.out.println(" 數據庫連接池創建成功! ");
- }
- /**
- * 創建由 numConnections 指定數目的數據庫連接 , 並把這些連接 放入 connections 向量中
- *
- * @param numConnections
- * 要創建的數據庫連接的數目
- */
- private void createConnections(int numConnections) throws SQLException {
- // 循環創建指定數目的數據庫連接
- for (int x = 0; x < numConnections; x++) {
- // 是否連接池中的數據庫連接的數量己經達到最大?最大值由類成員 maxConnections
- // 指出,如果 maxConnections 為 0 或負數,表示連接數量沒有限制。
- // 如果連接數己經達到最大,即退出。
- if (this.maxConnections > 0
- && this.connections.size() >= this.maxConnections) {
- break;
- }
- // add a new PooledConnection object to connections vector
- // 增加一個連接到連接池中(向量 connections 中)
- try {
- connections.addElement(new PooledConnection(newConnection()));
- } catch (SQLException e) {
- System.out.println(" 創建數據庫連接失敗! " + e.getMessage());
- throw new SQLException();
- }
- // System.out.println(" 數據庫連接己創建 ......");
- }
- }
- /**
- * 創建一個新的數據庫連接並返回它
- *
- * @return 返回一個新創建的數據庫連接
- */
- private Connection newConnection() throws SQLException {
- // 創建一個數據庫連接
- Connection conn = DriverManager.getConnection(dbUrl, dbUsername,
- dbPassword);
- // 如果這是第一次創建數據庫連接,即檢查數據庫,獲得此數據庫允許支持的
- // 最大客戶連接數目
- // connections.size()==0 表示目前沒有連接己被創建
- if (connections.size() == 0) {
- DatabaseMetaData metaData = conn.getMetaData();
- int driverMaxConnections = metaData.getMaxConnections();
- // 數據庫返回的 driverMaxConnections 若為 0 ,表示此數據庫沒有最大
- // 連接限制,或數據庫的最大連接限制不知道
- // driverMaxConnections 為返回的一個整數,表示此數據庫允許客戶連接的數目
- // 如果連接池中設置的最大連接數量大於數據庫允許的連接數目 , 則置連接池的最大
- // 連接數目為數據庫允許的最大數目
- if (driverMaxConnections > 0
- && this.maxConnections > driverMaxConnections) {
- this.maxConnections = driverMaxConnections;
- }
- }
- return conn; // 返回創建的新的數據庫連接
- }
- /**
- * 通過調用 getFreeConnection() 函數返回一個可用的數據庫連接 , 如果當前沒有可用的數據庫連接,並且更多的數據庫連接不能創
- * 建(如連接池大小的限制),此函數等待一會再嘗試獲取。
- *
- * @return 返回一個可用的數據庫連接對象
- */
- public synchronized Connection getConnection() throws SQLException {
- // 確保連接池己被創建
- if (connections == null) {
- return null; // 連接池還沒創建,則返回 null
- }
- Connection conn = getFreeConnection(); // 獲得一個可用的數據庫連接
- // 如果目前沒有可以使用的連接,即所有的連接都在使用中
- while (conn == null) {
- // 等一會再試
- // System.out.println("Wait");
- wait(250);
- conn = getFreeConnection(); // 重新再試,直到獲得可用的連接,如果
- // getFreeConnection() 返回的為 null
- // 則表明創建一批連接後也不可獲得可用連接
- }
- return conn;// 返回獲得的可用的連接
- }
- /**
- * 本函數從連接池向量 connections 中返回一個可用的的數據庫連接,如果 當前沒有可用的數據庫連接,本函數則根據
- * incrementalConnections 設置 的值創建幾個數據庫連接,並放入連接池中。 如果創建後,所有的連接仍都在使用中,則返回 null
- *
- * @return 返回一個可用的數據庫連接
- */
- private Connection getFreeConnection() throws SQLException {
- // 從連接池中獲得一個可用的數據庫連接
- Connection conn = findFreeConnection();
- if (conn == null) {
- // 如果目前連接池中沒有可用的連接
- // 創建一些連接
- createConnections(incrementalConnections);
- // 重新從池中查找是否有可用連接
- conn = findFreeConnection();
- if (conn == null) {
- // 如果創建連接後仍獲得不到可用的連接,則返回 null
- return null;
- }
- }
- return conn;
- }
- /**
- * 查找連接池中所有的連接,查找一個可用的數據庫連接, 如果沒有可用的連接,返回 null
- *
- * @return 返回一個可用的數據庫連接
- */
- private Connection findFreeConnection() throws SQLException {
- Connection conn = null;
- PooledConnection pConn = null;
- // 獲得連接池向量中所有的對象
- Enumeration enumerate = connections.elements();
- // 遍歷所有的對象,看是否有可用的連接
- while (enumerate.hasMoreElements()) {
- pConn = (PooledConnection) enumerate.nextElement();
- if (!pConn.isBusy()) {
- // 如果此對象不忙,則獲得它的數據庫連接並把它設為忙
- conn = pConn.getConnection();
- pConn.setBusy(true);
- // 測試此連接是否可用
- if (!testConnection(conn)) {
- // 如果此連接不可再用了,則創建一個新的連接,
- // 並替換此不可用的連接對象,如果創建失敗,返回 null
- try {
- conn = newConnection();
- } catch (SQLException e) {
- System.out.println(" 創建數據庫連接失敗! " + e.getMessage());
- return null;
- }
- pConn.setConnection(conn);
- }
- break; // 己經找到一個可用的連接,退出
- }
- }
- return conn;// 返回找到到的可用連接
- }
- /**
- * 測試一個連接是否可用,如果不可用,關掉它並返回 false 否則可用返回 true
- *
- * @param conn
- * 需要測試的數據庫連接
- * @return 返回 true 表示此連接可用, false 表示不可用
- */
- private boolean testConnection(Connection conn) {
- try {
- // 判斷測試表是否存在
- if (testTable.equals("")) {
- // 如果測試表為空,試著使用此連接的 setAutoCommit() 方法
- // 來判斷連接否可用(此方法只在部分數據庫可用,如果不可用 ,
- // 拋出異常)。註意:使用測試表的方法更可靠
- conn.setAutoCommit(true);
- } else {// 有測試表的時候使用測試表測試
- // check if this connection is valid
- Statement stmt = conn.createStatement();
- stmt.execute("select count(*) from " + testTable);
- }
- } catch (SQLException e) {
- // 上面拋出異常,此連接己不可用,關閉它,並返回 false;
- closeConnection(conn);
- return false;
- }
- // 連接可用,返回 true
- return true;
- }
- /**
- * 此函數返回一個數據庫連接到連接池中,並把此連接置為空閑。 所有使用連接池獲得的數據庫連接均應在不使用此連接時返回它。
- *
- * @param 需返回到連接池中的連接對象
- */
- public void returnConnection(Connection conn) {
- // 確保連接池存在,如果連接沒有創建(不存在),直接返回
- if (connections == null) {
- System.out.println(" 連接池不存在,無法返回此連接到連接池中 !");
- return;
- }
- PooledConnection pConn = null;
- Enumeration enumerate = connections.elements();
- // 遍歷連接池中的所有連接,找到這個要返回的連接對象
- while (enumerate.hasMoreElements()) {
- pConn = (PooledConnection) enumerate.nextElement();
- // 先找到連接池中的要返回的連接對象
- if (conn == pConn.getConnection()) {
- // 找到了 , 設置此連接為空閑狀態
- pConn.setBusy(false);
- break;
- }
- }
- }
- /**
- * 刷新連接池中所有的連接對象
- *
- */
- public synchronized void refreshConnections() throws SQLException {
- // 確保連接池己創新存在
- if (connections == null) {
- System.out.println(" 連接池不存在,無法刷新 !");
- return;
- }
- PooledConnection pConn = null;
- Enumeration enumerate = connections.elements();
- while (enumerate.hasMoreElements()) {
- // 獲得一個連接對象
- pConn = (PooledConnection) enumerate.nextElement();
- // 如果對象忙則等 5 秒 ,5 秒後直接刷新
- if (pConn.isBusy()) {
- wait(5000); // 等 5 秒
- }
- // 關閉此連接,用一個新的連接代替它。
- closeConnection(pConn.getConnection());
- pConn.setConnection(newConnection());
- pConn.setBusy(false);
- }
- }
- /**
- * 關閉連接池中所有的連接,並清空連接池。
- */
- public synchronized void closeConnectionPool() throws SQLException {
- // 確保連接池存在,如果不存在,返回
- if (connections == null) {
- System.out.println(" 連接池不存在,無法關閉 !");
- return;
- }
- PooledConnection pConn = null;
- Enumeration enumerate = connections.elements();
- while (enumerate.hasMoreElements()) {
- pConn = (PooledConnection) enumerate.nextElement();
- // 如果忙,等 5 秒
- if (pConn.isBusy()) {
- wait(5000); // 等 5 秒
- }
- // 5 秒後直接關閉它
- closeConnection(pConn.getConnection());
- // 從連接池向量中刪除它
- connections.removeElement(pConn);
- }
- // 置連接池為空
- connections = null;
- }
- /**
- * 關閉一個數據庫連接
- *
- * @param 需要關閉的數據庫連接
- */
- private void closeConnection(Connection conn) {
- try {
- conn.close();
- } catch (SQLException e) {
- System.out.println(" 關閉數據庫連接出錯: " + e.getMessage());
- }
- }
- /**
- * 使程序等待給定的毫秒數
- *
- * @param 給定的毫秒數
- */
- private void wait(int mSeconds) {
- try {
- Thread.sleep(mSeconds);
- } catch (InterruptedException e) {
- }
- }
- /**
- *
- * 內部使用的用於保存連接池中連接對象的類 此類中有兩個成員,一個是數據庫的連接,另一個是指示此連接是否 正在使用的標誌。
- */
- class PooledConnection {
- Connection connection = null;// 數據庫連接
- boolean busy = false; // 此連接是否正在使用的標誌,默認沒有正在使用
- // 構造函數,根據一個 Connection 構告一個 PooledConnection 對象
- public PooledConnection(Connection connection) {
- this.connection = connection;
- }
- // 返回此對象中的連接
- public Connection getConnection() {
- return connection;
- }
- // 設置此對象的,連接
- public void setConnection(Connection connection) {
- this.connection = connection;
- }
- // 獲得對象連接是否忙
- public boolean isBusy() {
- return busy;
- }
- // 設置對象的連接正在忙
- public void setBusy(boolean busy) {
- this.busy = busy;
- }
- }
- }
//////////////////////////////// 數據庫連接池類 ConnectionPool.java ////////////////////////////////////////ConnectionPoolUtils.java
[java] view plain copy print?
- /*連接池工具類,返回唯一的一個數據庫連接池對象,單例模式*/
- public class ConnectionPoolUtils {
- private ConnectionPoolUtils(){};//私有靜態方法
- private static ConnectionPool poolInstance = null;
- public static ConnectionPool GetPoolInstance(){
- if(poolInstance == null) {
- poolInstance = new ConnectionPool(
- "com.mysql.jdbc.Driver",
- "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8",
- "root", "123456");
- try {
- poolInstance.createPool();
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- return poolInstance;
- }
- }
ConnectionPoolTest.java
[java] view plain copy print?
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- public class ConnectionTest {
- /**
- * @param args
- * @throws Exception
- */
- public static void main(String[] args) throws Exception {
- try {
- /*使用連接池創建100個連接的時間*/
- /*// 創建數據庫連接庫對象
- ConnectionPool connPool = new ConnectionPool("com.mysql.jdbc.Driver","jdbc:mysql://localhost:3306/test", "root", "123456");
- // 新建數據庫連接庫
- connPool.createPool();*/
- ConnectionPool connPool=ConnectionPoolUtils.GetPoolInstance();//單例模式創建連接池對象
- // SQL測試語句
- String sql = "Select * from pet";
- // 設定程序運行起始時間
- long start = System.currentTimeMillis();
- // 循環測試100次數據庫連接
- for (int i = 0; i < 100; i++) {
- Connection conn = connPool.getConnection(); // 從連接庫中獲取一個可用的連接
- Statement stmt = conn.createStatement();
- ResultSet rs = stmt.executeQuery(sql);
- while (rs.next()) {
- String name = rs.getString("name");
- // System.out.println("查詢結果" + name);
- }
- rs.close();
- stmt.close();
- connPool.returnConnection(conn);// 連接使用完後釋放連接到連接池
- }
- System.out.println("經過100次的循環調用,使用連接池花費的時間:"+ (System.currentTimeMillis() - start) + "ms");
- // connPool.refreshConnections();//刷新數據庫連接池中所有連接,即不管連接是否正在運行,都把所有連接都釋放並放回到連接池。註意:這個耗時比較大。
- connPool.closeConnectionPool();// 關閉數據庫連接池。註意:這個耗時比較大。
- // 設定程序運行起始時間
- start = System.currentTimeMillis();
- /*不使用連接池創建100個連接的時間*/
- // 導入驅動
- Class.forName("com.mysql.jdbc.Driver");
- for (int i = 0; i < 100; i++) {
- // 創建連接
- Connection conn = DriverManager.getConnection(
- "jdbc:mysql://localhost:3306/test", "root", "123456");
- Statement stmt = conn.createStatement();
- ResultSet rs = stmt.executeQuery(sql);
- while (rs.next()) {
- }
- rs.close();
- stmt.close();
- conn.close();// 關閉連接
- }
- System.out.println("經過100次的循環調用,不使用連接池花費的時間:"
- + (System.currentTimeMillis() - start) + "ms");
- } catch (SQLException e) {
- e.printStackTrace();
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- }
- }
Java數據庫連接池實現原理