使用數據庫鏈接池提升執行效率

利用數據庫鏈接池可有效提升數據庫操做效率,避免重複打開和關閉數據庫鏈接。具體方法和測試結果以下:java

首先創建一個屬性文件,將相應的數據庫鏈接方法加入其中:sql

屬性文件具體設定以下:數據庫

driverClassName=oracle.jdbc.driver.OracleDriver
username=ORATEST
password=ORATEST
url=jdbc\:oracle\:thin\:@vOracle.imStudio.com\:1521\:vOracle
poolSize=10

而後創建數據庫鏈接池操做類ConnectionPoolTool.java設計模式

import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import java.util.Vector;

public class ConnectionPoolTool {
    
    private Vector<Connection> pool;
    private String url;
    private String username;
    private String password;
    private String driverClassName;

    /**
     * 鏈接池的大小,也就是鏈接池中有多少個數據庫鏈接。
     */
    private int poolSize = 1;

    private static ConnectionPoolTool instance = null;

    /**
     * 私有的構造方法,禁止外部建立本類的對象,要想得到本類的對象,經過<code>getIstance</code>方法。
     * 使用了設計模式中的單子模式。
     */
    private ConnectionPoolTool() {
        init();
    }

    /**
     * 鏈接池初始化方法,讀取屬性文件的內容 創建鏈接池中的初始鏈接
     */
    private void init() {
        pool = new Vector<Connection>(poolSize);
        readConfig();
        addConnection();
    }

    /**
     * 返回鏈接到鏈接池中
     */
    public synchronized void release(Connection conn) {
        pool.add(conn);

    }

    /**
     * 關閉鏈接池中的全部數據庫鏈接
     */
    public synchronized void closePool() {
        for (int i = 0; i < pool.size(); i++) {
            try {
                ((Connection) pool.get(i)).close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            pool.remove(i);
        }
    }

    /**
     * 返回當前鏈接池的一個對象
     */
    public static ConnectionPoolTool getInstance() {
        if (instance == null) {
            instance = new ConnectionPoolTool();
        }
        return instance;
    }

    /**
     * 返回鏈接池中的一個數據庫鏈接
     */
    public synchronized Connection getConnection() { 
        if (pool.size() > 0) {
            Connection conn = pool.get(0);
            pool.remove(conn);
            return conn;
        } else {
            return null;
        }
    }

    /**
     * 在鏈接池中建立初始設置的的數據庫鏈接
     */
    private void addConnection() {
        Connection conn = null;
        for (int i = 0; i < poolSize; i++) {

            try {
                Class.forName(driverClassName);
                conn = java.sql.DriverManager.getConnection(url, username, password);
                pool.add(conn);

            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }
    }

    /**
     * 讀取設置鏈接池的屬性文件
     */
    private void readConfig() {
        try {
            String path = System.getProperty("user.dir") + "\\dbpool.properties";
            FileInputStream is = new FileInputStream(path);
            Properties props = new Properties();
            props.load(is);
            this.driverClassName = props.getProperty("driverClassName");
            this.username = props.getProperty("username");
            this.password = props.getProperty("password");
            this.url = props.getProperty("url");
            this.poolSize = Integer.parseInt(props.getProperty("poolSize"));
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("讀取屬性文件出錯. ");        
        }
    }

}

再加入數據庫鏈接池測試方法ConnectionPoolTest.javaoracle

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class ConnectionPoolTest {

    /**
     * @param args
     */
    public static void main(String[] args)throws Exception {
        // TODO Auto-generated method stub
        String sql = "select userid,username,password from tbluser";
        long start = System.currentTimeMillis();
        ConnectionPoolTool pool = null;

        for (int i = 0; i < 100; i++) {
            pool = ConnectionPoolTool.getInstance();
            Connection conn = pool.getConnection();
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(sql);
            while (rs.next()) {
            }
            rs.close();
            stmt.close();
            pool.release(conn);
        }
        pool.closePool();
        System.out.println("通過100次的循環調用,使用鏈接池花費的時間:" + (System.currentTimeMillis() - start) + "ms\n");

        String hostName = "vOracle.imStudio.com";
        String driverClass = "oracle.jdbc.driver.OracleDriver";
        String url = "jdbc:oracle:thin:@" + hostName + ":1521:vOracle";
        String user = "ORATEST";
        String password = "ORATEST";
        start = System.currentTimeMillis();
        
        for (int i = 0; i < 100; i++) {
            Class.forName(driverClass);
            Connection conn = DriverManager.getConnection(url, user, password);
            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");
    }

}

編寫完成後,進行測試運行,以下爲我本機測試結果:
測試

相關文章
相關標籤/搜索