首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Tomcat 6.x + Struts 1.x + MySQL 5.x 資料庫連線池配置實戰

     編輯:Java 相關知識

配置檔位置:META-INF/context.xml

Tomcat 6+ 自動掃描專案 WebRoot/META-INF/context.xml(或 src/main/webapp/META-INF/context.xml),無需在 web.xml 額外設定。

<?xml version="1.0" encoding="UTF-8"?>
<Context reloadable="true" crossContext="true">
  <Resource name="jdbc/test" 
            auth="Container"
            type="javax.sql.DataSource"
            driverClassName="com.mysql.jdbc.Driver"
            url="jdbc:mysql://localhost:3306/haotian?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8"
            username="root"
            password="root"
            maxActive="20"
            maxIdle="10"
            maxWait="-1"
            validationQuery="SELECT 1"
            testOnBorrow="true"
            removeAbandoned="true"
            removeAbandonedTimeout="60"
            logAbandoned="true" />
</Context>

關鍵屬性:

  • validationQuery + testOnBorrow:借用連線前自動驗證,防止 MySQL 8 小時斷連導致的 Communications link failure。
  • removeAbandoned:自動回收未正確關閉的連線,避免洩漏耗盡連線池。

Java 取得連線

public class DBConnection {
    public Connection getConnection() throws NamingException, SQLException {
        Context initCtx = new InitialContext();
        Context envCtx = (Context) initCtx.lookup("java:comp/env");
        DataSource ds = (DataSource) envCtx.lookup("jdbc/test"); // 對應 Resource name
        return ds.getConnection();
    }
}

建議搭配 try-with-resources 自動關閉:

try (Connection conn = new DBConnection().getConnection();
     PreparedStatement ps = conn.prepareStatement(sql);
     ResultSet rs = ps.executeQuery()) {
    // 業務邏輯
}

驅動包放置位置:$CATALINA_HOME/lib/

必須將 MySQL Connector/J (mysql-connector-java-x.x.x.jar) 放入 Tomcat 的 lib/ 目錄,而非專案 WEB-INF/lib/。原因:

  • DataSource 由 Tomcat 容器建立,類別載入器為 Common ClassLoader。
  • 若放在專案 lib,容器看不見驅動類別,拋出 ClassNotFoundException: com.mysql.jdbc.Driver。

測試方式

不可在 main() 方法直接測試**,因無 JNDI 環境會拋出 NoInitialContextException。正確做法:

  1. 部署 WAR 到 Tomcat。
  2. 透過瀏覽器訪問呼叫 DBConnection 的 Servlet/JSP。
  3. 觀察日誌與資料庫連線數(show processlist)。

常見坑點

現象原因解決
Communications link failureMySQL wait_timeout 過短加 validationQuery + testOnBorrow
Connection leak未在 finally 關閉連線try-with-resources / removeAbandoned
ClassNotFoundException驅動包放錯位置移至 $CATALINA_HOME/lib
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved