自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Java的JDBC數(shù)據(jù)庫連接池實現(xiàn)方法

開發(fā) 后端
雖然J2EE程序員一般都有現(xiàn)成的應用服務器所帶的JDBC數(shù)據(jù)庫連接池,不過對于開發(fā)一般的Java Application、 Applet或者JSP、velocity時,我們可用的JDBC數(shù)據(jù)庫連接池并不多,并且一般性能都不好。

Java程序員都很羨慕Windows ADO ,只需要new Connection 就可以直接從數(shù)據(jù)庫連接池中返回Connection。并且 ADO Connection 是線程安全的,多個線程可以共用一個Connection,所以ASP程序一般都把getConnection 放在 Global.asa 文件中,在 IIS 啟動時建立數(shù)據(jù)庫連接。ADO 的Connection 和Result 都有很好的緩沖,并且很容易使用。

其實我們可以自己寫一個JDBC數(shù)據(jù)庫連接池。

寫JDBC connection pool 的注意事項有:

1. 有一個簡單的函數(shù)從連接池中得到一個 Connection。

2. close 函數(shù)必須將connection 放回 數(shù)據(jù)庫連接池。

3. 當數(shù)據(jù)庫連接池中沒有空閑的connection,數(shù)據(jù)庫連接池必須能夠自動增加connection 個數(shù)。

4. 當數(shù)據(jù)庫連接池中的connection 個數(shù)在某一個特別的時間變得很大,但是以后很長時間只用其中一小部分,應該可以自動將多余的connection 關(guān)閉掉。

5. 如果可能,應該提供debug 信息報告沒有關(guān)閉的new Connection 。

如果要new Connection 就可以直接從數(shù)據(jù)庫連接池中返回Connection, 可以這樣寫( Mediator pattern ) (以下代碼中使用了中文全角空格):

  1. public class EasyConnection implements java.sql.Connection{  
  2.   private Connection m_delegate = null;  
  3.   public EasyConnection(){  
  4.     m_delegate = getConnectionFromPool();  
  5.   }  
  6.  public void close(){  
  7.     putConnectionBackToPool(m_delegate);  
  8.   }  
  9.   public PreparedStatement prepareStatement(String sql) throws SQLException{  
  10.     m_delegate.prepareStatement(sql);  
  11.   }  
  12.   //...... other method  

看來并不難。不過不建議這種寫法,因為應該盡量避免使用Java Interface, 關(guān)于Java Interface 的缺點我另外再寫文章討論。大家關(guān)注的是Connection Pool 的實現(xiàn)方法。下面給出一種實現(xiàn)方法。

  1. import java.sql.*;  
  2. import java.lang.reflect.*;  
  3. import java.util.*;  
  4. import java.io.*;  
  5.  
  6. public class SimpleConnetionPool {  
  7.   private static LinkedList m_notUsedConnection = new LinkedList();  
  8.   private static HashSet m_usedUsedConnection = new HashSet();  
  9.   private static String m_url = "";  
  10.   private static String m_user = "";  
  11.   private static String m_password = "";  
  12.   static final boolean DEBUG = true;  
  13.   static private long m_lastClearClosedConnection = System.currentTimeMillis();  
  14.   public static long CHECK_CLOSED_CONNECTION_TIME = 4 * 60 * 60 * 1000//4 hours  
  15.  
  16.   static {  
  17.     initDriver();  
  18.   }  
  19.  
  20.   private SimpleConnetionPool() {  
  21.   }  
  22.  
  23.   private static void initDriver() {  
  24.     Driver driver = null;  
  25.     //load mysql driver  
  26.     try {  
  27.       driver = (Driver) Class.forName("com.mysql.jdbc.Driver").newInstance();  
  28.       installDriver(driver);  
  29.     } catch (Exception e) {  
  30.     }  
  31.  
  32.     //load postgresql driver  
  33.     try {  
  34.       driver = (Driver) Class.forName("org.postgresql.Driver").newInstance();  
  35.       installDriver(driver);  
  36.     } catch (Exception e) {  
  37.     }  
  38.   }  
  39.  
  40.   public static void installDriver(Driver driver) {  
  41.     try {  
  42.       DriverManager.registerDriver(driver);  
  43.     } catch (Exception e) {  
  44.       e.printStackTrace();  
  45.     }  
  46.   }  
  47.  
  48.  
  49.   public static synchronized Connection getConnection() {  
  50.     clearClosedConnection();  
  51.     while (m_notUsedConnection.size() > 0) {  
  52.       try {  
  53.         ConnectionWrapper wrapper = (ConnectionWrapper) m_notUsedConnection.removeFirst();  
  54.         if (wrapper.connection.isClosed()) {  
  55.           continue;  
  56.         }  
  57.         m_usedUsedConnection.add(wrapper);  
  58.         if (DEBUG) {  
  59.           wrapper.debugInfo = new Throwable("Connection initial statement");  
  60.         }  
  61.         return wrapper.connection;  
  62.       } catch (Exception e) {  
  63.       }  
  64.     }  
  65.     int newCount = getIncreasingConnectionCount();  
  66.     LinkedList list = new LinkedList();  
  67.     ConnectionWrapper wrapper = null;  
  68.     for (int i = 0; i < newCount; i++) {  
  69.       wrapper = getNewConnection();  
  70.       if (wrapper != null) {  
  71.         list.add(wrapper);  
  72.       }  
  73.     }  
  74.     if (list.size() == 0) {  
  75.       return null;  
  76.     }  
  77.     wrapper = (ConnectionWrapper) list.removeFirst();  
  78.     m_usedUsedConnection.add(wrapper);  
  79.  
  80.     m_notUsedConnection.addAll(list);  
  81.     list.clear();  
  82.  
  83.     return wrapper.connection;  
  84.   }  
  85.  
  86.   private static ConnectionWrapper getNewConnection() {  
  87.     try {  
  88.       Connection con = DriverManager.getConnection(m_url, m_user, m_password);  
  89.       ConnectionWrapper wrapper = new ConnectionWrapper(con);  
  90.       return wrapper;  
  91.     } catch (Exception e) {  
  92.       e.printStackTrace();  
  93.     }  
  94.     return null;  
  95.   }  
  96.  
  97.   static synchronized void pushConnectionBackToPool(ConnectionWrapper con) {  
  98.     boolean exist = m_usedUsedConnection.remove(con);  
  99.     if (exist) {  
  100.       m_notUsedConnection.addLast(con);  
  101.     }  
  102.   }  
  103.  
  104.   public static int close() {  
  105.     int count = 0;  
  106.  
  107.     Iterator iterator = m_notUsedConnection.iterator();  
  108.     while (iterator.hasNext()) {  
  109.       try {  
  110.         ( (ConnectionWrapper) iterator.next()).close();  
  111.         count++;  
  112.       } catch (Exception e) {  
  113.       }  
  114.     }  
  115.     m_notUsedConnection.clear();  
  116.  
  117.     iterator = m_usedUsedConnection.iterator();  
  118.     while (iterator.hasNext()) {  
  119.       try {  
  120.         ConnectionWrapper wrapper = (ConnectionWrapper) iterator.next();  
  121.         wrapper.close();  
  122.         if (DEBUG) {  
  123.           wrapper.debugInfo.printStackTrace();  
  124.         }  
  125.         count++;  
  126.       } catch (Exception e) {  
  127.       }  
  128.     }  
  129.     m_usedUsedConnection.clear();  
  130.  
  131.     return count;  
  132.   }  
  133.  
  134.   private static void clearClosedConnection() {  
  135.     long time = System.currentTimeMillis();  
  136.     //sometimes user change system time,just return  
  137.     if (time < m_lastClearClosedConnection) {  
  138.       time = m_lastClearClosedConnection;  
  139.       return;  
  140.     }  
  141.     //no need check very often  
  142.     if (time - m_lastClearClosedConnection < CHECK_CLOSED_CONNECTION_TIME) {  
  143.       return;  
  144.     }  
  145.     m_lastClearClosedConnection = time;  
  146.  
  147.     //begin check  
  148.     Iterator iterator = m_notUsedConnection.iterator();  
  149.     while (iterator.hasNext()) {  
  150.       ConnectionWrapper wrapper = (ConnectionWrapper) iterator.next();  
  151.       try {  
  152.         if (wrapper.connection.isClosed()) {  
  153.           iterator.remove();  
  154.         }  
  155.       } catch (Exception e) {  
  156.         iterator.remove();  
  157.         if (DEBUG) {  
  158.           System.out.println("connection is closed, this connection initial StackTrace");  
  159.           wrapper.debugInfo.printStackTrace();  
  160.         }  
  161.       }  
  162.     }  
  163.  
  164.     //make connection pool size smaller if too big  
  165.     int decrease = getDecreasingConnectionCount();  
  166.     if (m_notUsedConnection.size() < decrease) {  
  167.       return;  
  168.     }  
  169.  
  170.     while (decrease-- > 0) {  
  171.       ConnectionWrapper wrapper = (ConnectionWrapper) m_notUsedConnection.removeFirst();  
  172.       try {  
  173.         wrapper.connection.close();  
  174.       } catch (Exception e) {  
  175.       }  
  176.     }  
  177.   }  
  178.  
  179.   /**  
  180.    * get increasing connection count, not just add 1 connection  
  181.    * @return count  
  182.    */ 
  183.   public static int getIncreasingConnectionCount() {  
  184.     int count = 1;  
  185.     int current = getConnectionCount();  
  186.     count = current / 4;  
  187.     if (count < 1) {  
  188.       count = 1;  
  189.     }  
  190.     return count;  
  191.   }  
  192.  
  193.   /**  
  194.    * get decreasing connection count, not just remove 1 connection  
  195.    * @return count  
  196.    */ 
  197.   public static int getDecreasingConnectionCount() {  
  198.     int count = 0;  
  199.     int current = getConnectionCount();  
  200.     if (current < 10) {  
  201.       return 0;  
  202.     }  
  203.     return current / 3;  
  204.   }  
  205.  
  206.   public synchronized static void printDebugMsg() {  
  207.     printDebugMsg(System.out);  
  208.   }  
  209.  
  210.   public synchronized static void printDebugMsg(PrintStream out) {  
  211.     if (DEBUG == false) {  
  212.       return;  
  213.     }  
  214.     StringBuffer msg = new StringBuffer();  
  215.     msg.append("debug message in " + SimpleConnetionPool.class.getName());  
  216.     msg.append("\r\n");  
  217.     msg.append("total count is connection pool: " + getConnectionCount());  
  218.     msg.append("\r\n");  
  219.     msg.append("not used connection count: " + getNotUsedConnectionCount());  
  220.     msg.append("\r\n");  
  221.     msg.append("used connection, count: " + getUsedConnectionCount());  
  222.     out.println(msg);  
  223.     Iterator iterator = m_usedUsedConnection.iterator();  
  224.     while (iterator.hasNext()) {  
  225.       ConnectionWrapper wrapper = (ConnectionWrapper) iterator.next();  
  226.       wrapper.debugInfo.printStackTrace(out);  
  227.     }  
  228.     out.println();  
  229.   }  
  230.  
  231.   public static synchronized int getNotUsedConnectionCount() {  
  232.     return m_notUsedConnection.size();  
  233.   }  
  234.  
  235.   public static synchronized int getUsedConnectionCount() {  
  236.     return m_usedUsedConnection.size();  
  237.   }  
  238.  
  239.   public static synchronized int getConnectionCount() {  
  240.     return m_notUsedConnection.size() + m_usedUsedConnection.size();  
  241.   }  
  242.  
  243.   public static String getUrl() {  
  244.     return m_url;  
  245.   }  
  246.  
  247.   public static void setUrl(String url) {  
  248.     if (url == null) {  
  249.       return;  
  250.     }  
  251.     m_url = url.trim();  
  252.   }  
  253.  
  254.   public static String getUser() {  
  255.     return m_user;  
  256.   }  
  257.  
  258.   public static void setUser(String user) {  
  259.     if (user == null) {  
  260.       return;  
  261.     }  
  262.     m_user = user.trim();  
  263.   }  
  264.  
  265.   public static String getPassword() {  
  266.     return m_password;  
  267.   }  
  268.  
  269.   public static void setPassword(String password) {  
  270.     if (password == null) {  
  271.       return;  
  272.     }  
  273.     m_password = password.trim();  
  274.   }  
  275.  
  276. }  
  277.  
  278. class ConnectionWrapper implements InvocationHandler {  
  279.   private final static String CLOSE_METHOD_NAME = "close";  
  280.   public Connection connection = null;  
  281.   private Connection m_originConnection = null;  
  282.   public long lastAccessTime = System.currentTimeMillis();  
  283.   Throwable debugInfo = new Throwable("Connection initial statement");  
  284.  
  285.   ConnectionWrapper(Connection con) {  
  286.     this.connection = (Connection) Proxy.newProxyInstance(  
  287.       con.getClass().getClassLoader(),  
  288.       con.getClass().getInterfaces(), this);  
  289.     m_originConnection = con;  
  290.   }  
  291.  
  292.   void close() throws SQLException {  
  293.     m_originConnection.close();  
  294.   }  
  295.  
  296.   public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {  
  297.     Object obj = null;  
  298.     if (CLOSE_METHOD_NAME.equals(m.getName())) {  
  299.       SimpleConnetionPool.pushConnectionBackToPool(this);  
  300.     }  
  301.     else {  
  302.       obj = m.invoke(m_originConnection, args);  
  303.     }  
  304.     lastAccessTime = System.currentTimeMillis();  
  305.     return obj;  
  306.   }  

使用方法

  1. public class TestConnectionPool{  
  2.   public static void main(String[] args) {  
  3.     SimpleConnetionPool.setUrl(DBTools.getDatabaseUrl());  
  4.     SimpleConnetionPool.setUser(DBTools.getDatabaseUserName());  
  5.     SimpleConnetionPool.setPassword(DBTools.getDatabasePassword());  
  6.  
  7.     Connection con = SimpleConnetionPool.getConnection();  
  8.     Connection con1 = SimpleConnetionPool.getConnection();  
  9.     Connection con2 = SimpleConnetionPool.getConnection();  
  10.  
  11.     //do something with con ...  
  12.  
  13.     try {  
  14.       con.close();  
  15.     } catch (Exception e) {}  
  16.  
  17.     try {  
  18.       con1.close();  
  19.     } catch (Exception e) {}  
  20.  
  21.     try {  
  22.       con2.close();  
  23.     } catch (Exception e) {}  
  24.  
  25.     con = SimpleConnetionPool.getConnection();  
  26.     con1 = SimpleConnetionPool.getConnection();  
  27.     try {  
  28.       con1.close();  
  29.     } catch (Exception e) {}  
  30.  
  31.     con2 = SimpleConnetionPool.getConnection();  
  32.     SimpleConnetionPool.printDebugMsg();  
  33.  
  34.   }  

運行測試程序后打印JDBC數(shù)據(jù)庫連接池中Connection狀態(tài),以及正在使用的沒有關(guān)閉Connection信息。

【編輯推薦】

  1. 談談優(yōu)化JDBC數(shù)據(jù)庫編程
  2. 實例說明對MySQL的JDBC連接設置
  3. 淺談如何利用JSP網(wǎng)頁中JDBC代碼連接MySQL
  4. 淺談JDBC代碼如何重復使用
  5. 如何進行Jython數(shù)據(jù)庫插入(JDBC)
責任編輯:彭凡 來源: 百度空間
相關(guān)推薦

2010-10-26 16:15:33

連接Oracle數(shù)據(jù)庫

2009-06-24 07:53:47

Hibernate數(shù)據(jù)

2010-12-10 16:19:04

JDBC數(shù)據(jù)庫連接池DDLSQLJ存儲過程

2010-03-18 15:09:15

python數(shù)據(jù)庫連接

2019-11-27 10:31:51

數(shù)據(jù)庫連接池內(nèi)存

2018-10-10 14:27:34

數(shù)據(jù)庫連接池MySQL

2017-06-22 14:13:07

PythonMySQLpymysqlpool

2009-06-16 09:25:31

JBoss配置

2009-07-22 14:30:53

JDBC連接池

2011-07-04 10:17:38

JDBC

2011-05-26 09:27:59

JDBC連接數(shù)據(jù)庫

2018-01-03 14:32:32

2011-05-19 09:53:33

數(shù)據(jù)庫連接池

2019-12-30 15:30:13

連接池請求PHP

2020-04-30 14:38:51

數(shù)據(jù)庫連接池線程

2021-08-12 06:52:01

.NET數(shù)據(jù)庫連接池

2025-02-07 12:11:52

2009-07-22 11:45:43

2009-07-03 17:37:54

JSP數(shù)據(jù)庫

2009-01-15 09:02:27

JMXJBossJMX監(jiān)控
點贊
收藏

51CTO技術(shù)棧公眾號