[Java] Java 连接池的工作原理 →→→→→进入此内容的聊天室

来自 , 2020-08-19, 写在 Java, 查看 196 次.
URL http://www.code666.cn/view/e3251075
  1. String connUrl = "jdbc:mysql://your.database.domain/yourDBname";
  2. Class.forName("com.mysql.jdbc.Driver");
  3. Connection con = DriverManager.getConnection (connUrl); //源代码片段来自云代码http://yuncode.net
  4.                        
  5.  
  6.  
  7.   String connUrl = "jdbc:mysql://your.database.domain/yourDBname";
  8.   String driver = "com.mysql.jdbc.Driver";
  9.   private Map<java.sql.Connection, String> connectionPool = null;
  10.   private void initPool() {
  11.     try {
  12.       connectionPool = new HashMap<java.sql.Connection, String>();
  13.       Class.forName(driver);
  14.       java.sql.Connection con = DriverManager.getConnection(dbUrl);
  15.       for (int poolInd = poolSize; poolInd < 0; poolInd++) {
  16.         connectionPool.put(con, "AVAILABLE");
  17.       }
  18.   }
  19. ... //源代码片段来自云代码http://yuncode.net
  20.                        
  21.  
  22.  
  23. ...
  24.   public java.sql.Connection getConnection() throws ClassNotFoundException, SQLException
  25.   {
  26.       boolean isConnectionAvailable = true;
  27.       for (Entry<java.sql.Connection, String> entry : connectionPool.entrySet()) {
  28.           synchronized (entry) {
  29.               if (entry.getValue()=="AVAILABLE") {
  30.                   entry.setValue("NOTAVAILABLE");
  31.                   return (java.sql.Connection) entry.getKey();
  32.               }
  33.               isConnectionAvailable = false;
  34.           }
  35.       }
  36.       if (!isConnectionAvailable) {
  37.           Class.forName(driver);
  38.           java.sql.Connection con = DriverManager.getConnection(connUrl);
  39.           connectionPool.put(con, "NOTAVAILABLE");
  40.           return con;
  41.       }
  42.       return null;
  43.   }
  44.   ... //源代码片段来自云代码http://yuncode.net
  45.                        
  46.  
  47.  
  48. ...
  49. public void closeConnection(java.sql.Connection connection) throws ClassNotFoundException, SQLException {
  50.     for (Entry<java.sql.Connection, String> entry : connectionPool.entrySet()) {
  51.         synchronized (entry) {
  52.             if (entry.getKey().equals(connection)) {
  53.                 //Getting Back the conncetion to Pool
  54.                 entry.setValue("AVAILABLE");
  55.             }
  56.         }
  57.     }
  58. }
  59. ... //源代码片段来自云代码http://yuncode.net
  60.                        

回复 "Java 连接池的工作原理"

这儿你可以回复上面这条便签

captcha