今天就跟大家聊聊有關(guān)Java中怎么利用JDBC實(shí)現(xiàn)數(shù)據(jù)庫(kù)連接池,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
昆都侖ssl適用于網(wǎng)站、小程序/APP、API接口等需要進(jìn)行數(shù)據(jù)傳輸應(yīng)用場(chǎng)景,ssl證書(shū)未來(lái)市場(chǎng)廣闊!成為創(chuàng)新互聯(lián)建站的ssl證書(shū)銷(xiāo)售渠道,可以享受市場(chǎng)價(jià)格4-6折優(yōu)惠!如果有意向歡迎電話聯(lián)系或者加微信:18980820575(備注:SSL證書(shū)合作)期待與您的合作!
Java程序員都很羨慕Windows ADO ,只需要new Connection 就可以直接從數(shù)據(jù)庫(kù)連接池中返回Connection。并且 ADO Connection 是線程安全的,多個(gè)線程可以共用一個(gè)Connection,所以ASP程序一般都把getConnection 放在 Global.asa 文件中,在 IIS 啟動(dòng)時(shí)建立數(shù)據(jù)庫(kù)連接。ADO 的Connection 和Result 都有很好的緩沖,并且很容易使用。
其實(shí)我們可以自己寫(xiě)一個(gè)JDBC數(shù)據(jù)庫(kù)連接池。
寫(xiě)JDBC connection pool 的注意事項(xiàng)有:
1. 有一個(gè)簡(jiǎn)單的函數(shù)從連接池中得到一個(gè) Connection。
2. close 函數(shù)必須將connection 放回 數(shù)據(jù)庫(kù)連接池。
3. 當(dāng)數(shù)據(jù)庫(kù)連接池中沒(méi)有空閑的connection,數(shù)據(jù)庫(kù)連接池必須能夠自動(dòng)增加connection 個(gè)數(shù)。
4. 當(dāng)數(shù)據(jù)庫(kù)連接池中的connection 個(gè)數(shù)在某一個(gè)特別的時(shí)間變得很大,但是以后很長(zhǎng)時(shí)間只用其中一小部分,應(yīng)該可以自動(dòng)將多余的connection 關(guān)閉掉。
5. 如果可能,應(yīng)該提供debug 信息報(bào)告沒(méi)有關(guān)閉的new Connection 。
如果要new Connection 就可以直接從數(shù)據(jù)庫(kù)連接池中返回Connection, 可以這樣寫(xiě)( Mediator pattern ) (以下代碼中使用了中文全角空格):
public class EasyConnection implements java.sql.Connection{ private Connection m_delegate = null; public EasyConnection(){ m_delegate = getConnectionFromPool(); } public void close(){ putConnectionBackToPool(m_delegate); } public PreparedStatement prepareStatement(String sql) throws SQLException{ m_delegate.prepareStatement(sql); } //...... other method }
看來(lái)并不難。不過(guò)不建議這種寫(xiě)法,因?yàn)閼?yīng)該盡量避免使用Java Interface, 關(guān)于Java Interface 的缺點(diǎn)我另外再寫(xiě)文章討論。大家關(guān)注的是Connection Pool 的實(shí)現(xiàn)方法。下面給出一種實(shí)現(xiàn)方法。
import java.sql.*; import java.lang.reflect.*; import java.util.*; import java.io.*; public class SimpleConnetionPool { private static LinkedList m_notUsedConnection = new LinkedList(); private static HashSet m_usedUsedConnection = new HashSet(); private static String m_url = ""; private static String m_user = ""; private static String m_password = ""; static final boolean DEBUG = true; static private long m_lastClearClosedConnection = System.currentTimeMillis(); public static long CHECK_CLOSED_CONNECTION_TIME = 4 * 60 * 60 * 1000; //4 hours static { initDriver(); } private SimpleConnetionPool() { } private static void initDriver() { Driver driver = null; //load MySQL driver try { driver = (Driver) Class.forName("com.mysql.jdbc.Driver").newInstance(); installDriver(driver); } catch (Exception e) { } //load postgresql driver try { driver = (Driver) Class.forName("org.postgresql.Driver").newInstance(); installDriver(driver); } catch (Exception e) { } } public static void installDriver(Driver driver) { try { DriverManager.registerDriver(driver); } catch (Exception e) { e.printStackTrace(); } } public static synchronized Connection getConnection() { clearClosedConnection(); while (m_notUsedConnection.size() > 0) { try { ConnectionWrapper wrapper = (ConnectionWrapper) m_notUsedConnection.removeFirst(); if (wrapper.connection.isClosed()) { continue; } m_usedUsedConnection.add(wrapper); if (DEBUG) { wrapper.debugInfo = new Throwable("Connection initial statement"); } return wrapper.connection; } catch (Exception e) { } } int newCount = getIncreasingConnectionCount(); LinkedList list = new LinkedList(); ConnectionWrapper wrapper = null; for (int i = 0; i < newCount; i++) { wrapper = getNewConnection(); if (wrapper != null) { list.add(wrapper); } } if (list.size() == 0) { return null; } wrapper = (ConnectionWrapper) list.removeFirst(); m_usedUsedConnection.add(wrapper); m_notUsedConnection.addAll(list); list.clear(); return wrapper.connection; } private static ConnectionWrapper getNewConnection() { try { Connection con = DriverManager.getConnection(m_url, m_user, m_password); ConnectionWrapper wrapper = new ConnectionWrapper(con); return wrapper; } catch (Exception e) { e.printStackTrace(); } return null; } static synchronized void pushConnectionBackToPool(ConnectionWrapper con) { boolean exist = m_usedUsedConnection.remove(con); if (exist) { m_notUsedConnection.addLast(con); } } public static int close() { int count = 0; Iterator iterator = m_notUsedConnection.iterator(); while (iterator.hasNext()) { try { ( (ConnectionWrapper) iterator.next()).close(); count++; } catch (Exception e) { } } m_notUsedConnection.clear(); iterator = m_usedUsedConnection.iterator(); while (iterator.hasNext()) { try { ConnectionWrapper wrapper = (ConnectionWrapper) iterator.next(); wrapper.close(); if (DEBUG) { wrapper.debugInfo.printStackTrace(); } count++; } catch (Exception e) { } } m_usedUsedConnection.clear(); return count; } private static void clearClosedConnection() { long time = System.currentTimeMillis(); //sometimes user change system time,just return if (time < m_lastClearClosedConnection) { time = m_lastClearClosedConnection; return; } //no need check very often if (time - m_lastClearClosedConnection < CHECK_CLOSED_CONNECTION_TIME) { return; } m_lastClearClosedConnection = time; //begin check Iterator iterator = m_notUsedConnection.iterator(); while (iterator.hasNext()) { ConnectionWrapper wrapper = (ConnectionWrapper) iterator.next(); try { if (wrapper.connection.isClosed()) { iterator.remove(); } } catch (Exception e) { iterator.remove(); if (DEBUG) { System.out.println("connection is closed, this connection initial StackTrace"); wrapper.debugInfo.printStackTrace(); } } } //make connection pool size smaller if too big int decrease = getDecreasingConnectionCount(); if (m_notUsedConnection.size() < decrease) { return; } while (decrease-- > 0) { ConnectionWrapper wrapper = (ConnectionWrapper) m_notUsedConnection.removeFirst(); try { wrapper.connection.close(); } catch (Exception e) { } } } /** * get increasing connection count, not just add 1 connection * @return count */ public static int getIncreasingConnectionCount() { int count = 1; int current = getConnectionCount(); count = current / 4; if (count < 1) { count = 1; } return count; } /** * get decreasing connection count, not just remove 1 connection * @return count */ public static int getDecreasingConnectionCount() { int count = 0; int current = getConnectionCount(); if (current < 10) { return 0; } return current / 3; } public synchronized static void printDebugMsg() { printDebugMsg(System.out); } public synchronized static void printDebugMsg(PrintStream out) { if (DEBUG == false) { return; } StringBuffer msg = new StringBuffer(); msg.append("debug message in " + SimpleConnetionPool.class.getName()); msg.append("\r\n"); msg.append("total count is connection pool: " + getConnectionCount()); msg.append("\r\n"); msg.append("not used connection count: " + getNotUsedConnectionCount()); msg.append("\r\n"); msg.append("used connection, count: " + getUsedConnectionCount()); out.println(msg); Iterator iterator = m_usedUsedConnection.iterator(); while (iterator.hasNext()) { ConnectionWrapper wrapper = (ConnectionWrapper) iterator.next(); wrapper.debugInfo.printStackTrace(out); } out.println(); } public static synchronized int getNotUsedConnectionCount() { return m_notUsedConnection.size(); } public static synchronized int getUsedConnectionCount() { return m_usedUsedConnection.size(); } public static synchronized int getConnectionCount() { return m_notUsedConnection.size() + m_usedUsedConnection.size(); } public static String getUrl() { return m_url; } public static void setUrl(String url) { if (url == null) { return; } m_url = url.trim(); } public static String getUser() { return m_user; } public static void setUser(String user) { if (user == null) { return; } m_user = user.trim(); } public static String getPassword() { return m_password; } public static void setPassword(String password) { if (password == null) { return; } m_password = password.trim(); } } class ConnectionWrapper implements InvocationHandler { private final static String CLOSE_METHOD_NAME = "close"; public Connection connection = null; private Connection m_originConnection = null; public long lastAccessTime = System.currentTimeMillis(); Throwable debugInfo = new Throwable("Connection initial statement"); ConnectionWrapper(Connection con) { this.connection = (Connection) Proxy.newProxyInstance( con.getClass().getClassLoader(), con.getClass().getInterfaces(), this); m_originConnection = con; } void close() throws SQLException { m_originConnection.close(); } public Object invoke(Object proxy, Method m, Object[] args) throws Throwable { Object obj = null; if (CLOSE_METHOD_NAME.equals(m.getName())) { SimpleConnetionPool.pushConnectionBackToPool(this); } else { obj = m.invoke(m_originConnection, args); } lastAccessTime = System.currentTimeMillis(); return obj; } }
使用方法
public class TestConnectionPool{ public static void main(String[] args) { SimpleConnetionPool.setUrl(DBTools.getDatabaseUrl()); SimpleConnetionPool.setUser(DBTools.getDatabaseUserName()); SimpleConnetionPool.setPassword(DBTools.getDatabasePassword()); Connection con = SimpleConnetionPool.getConnection(); Connection con1 = SimpleConnetionPool.getConnection(); Connection con2 = SimpleConnetionPool.getConnection(); //do something with con ... try { con.close(); } catch (Exception e) {} try { con1.close(); } catch (Exception e) {} try { con2.close(); } catch (Exception e) {} con = SimpleConnetionPool.getConnection(); con1 = SimpleConnetionPool.getConnection(); try { con1.close(); } catch (Exception e) {} con2 = SimpleConnetionPool.getConnection(); SimpleConnetionPool.printDebugMsg(); } }
運(yùn)行測(cè)試程序后打印JDBC數(shù)據(jù)庫(kù)連接池中Connection狀態(tài),以及正在使用的沒(méi)有關(guān)閉Connection信息。
看完上述內(nèi)容,你們對(duì)Java中怎么利用JDBC實(shí)現(xiàn)數(shù)據(jù)庫(kù)連接池有進(jìn)一步的了解嗎?如果還想了解更多知識(shí)或者相關(guān)內(nèi)容,請(qǐng)關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝大家的支持。
網(wǎng)站標(biāo)題:Java中怎么利用JDBC實(shí)現(xiàn)數(shù)據(jù)庫(kù)連接池
文章轉(zhuǎn)載:http://jinyejixie.com/article18/psisgp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供品牌網(wǎng)站制作、域名注冊(cè)、全網(wǎng)營(yíng)銷(xiāo)推廣、品牌網(wǎng)站建設(shè)、手機(jī)網(wǎng)站建設(shè)、動(dòng)態(tài)網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)