关闭

Tomcat连接池

551人阅读 评论(0) 收藏 举报
 Tomcat连接池的配置,官方文档,在此记录一下。

        1.MySQL
            1.1 Context configuration:
<Context path="/DBTest" docBase="DBTest"
        debug="5" reloadable="true" crossContext="true"<
        <Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource"
               maxActive="100" maxIdle="30" maxWait="10000"
               username="javauser" password="javadude" driverClassName="com.mysql.jdbc.Driver"
               url="jdbc:mysql://localhost:3306/javatest?autoReconnect=true"/<
</Context<
             1.2 web.xml configuration:
<resource-ref<
      <description<DB Connection</description<
      <res-ref-name<jdbc/TestDB</res-ref-name<
      <res-type<javax.sql.DataSource</res-type<
      <res-auth<Container</res-auth<     / /据说还可以是Application
  </resource-ref<                
            1.3 Test code 还可以在jsp中直接使用数据源
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %<
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %<
...
<sql:query var="rs" dataSource="jdbc/TestDB"<
        select id, foo, bar from testdata
</sql:query<
...
<c:forEach var="row" items="${rs.rows}"<
    Foo ${row.foo}<br/<
    Bar ${row.bar}<br/<
</c:forEach<

        2. Oracle
            2.1 Context configuration:
<Resource name="jdbc/myoracle" auth="Container"
              type="javax.sql.DataSource" driverClassName="oracle.jdbc.OracleDriver"
              url="jdbc:oracle:thin:@127.0.0.1:1521:mysid"
              username="scott" password="tiger" maxActive="20" maxIdle="10"
              maxWait="-1"/<
            2.2 web.xml configuration:
<resource-ref<
    <description<Oracle Datasource example</description<
    <res-ref-name<jdbc/myoracle</res-ref-name<
    <res-type<javax.sql.DataSource</res-type<
    <res-auth<Container</res-auth<
</resource-ref<
            2.3 Test code
Context initContext = new InitialContext();
Context envContext  = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/myoracle");
Connection conn = ds.getConnection();
//etc.

        把配置放在Context 标签对里面只对当前应用有效,要想对整个TomCat有效,可以放到GlobalNamingResources里面。(强烈申明,此种情况好像是5.0版本前是这样设置的,5.5和6.0版本如果要是全局的话,就在Tomcat_Home\conf下的context.xml文件直接配置)

        Tomcat6的连接池设置有一些不一样,在server.xml中文配置老是报Cannot create JDBC driver of class '' for connect URL 'null' 的错误,需要将Tomcat6安装路径的conf目录下的context.xml文件拷贝到自己应用的META-INF目录下,并添加<Resource /<的配置。

        连接池使用的问题,官方说明如下,水平太次,不敢翻译,抄录之:
Intermittent dB Connection Failures:
       
Tomcat runs within a JVM. The JVM periodically performs garbage collection (GC) to remove java objects which are no longer being used. When the JVM performs GC execution of code within Tomcat freezes. If the maximum time configured for establishment of a dB connection is less than the amount of time garbage collection took you can get a db conneciton failure. 
        To collect data on how long garbage collection is taking add the -verbose:gc argument to your CATALINA_OPTS environment variable when starting Tomcat. When verbose gc is enabled your $CATALINA_BASE/logs/catalina.out log file will include data for every garbage collection including how long it took.
        When your JVM is tuned correctly 99% of the time a GC will take less than one second. The remainder will only take a few seconds. Rarely, if ever should a GC take more than 10 seconds.
        Make sure that the db connection timeout is set to 10-15 seconds. For the DBCP you set this using the parameter maxWait.
Random Connection Closed Exceptions:
        These can occur when one request gets a db connection from the connection pool and closes it twice. When using a connection pool, closing the connection just returns it to the pool for reuse by another request, it doesn't close the connection. And Tomcat uses multiple threads to handle concurrent requests. Here is an example of the sequence of events which could cause this error in Tomcat:
----------------------------------------------------------------------------------------------
  Request 1 running in Thread 1 gets a db connection.
  Request 1 closes the db connection.
  The JVM switches the running thread to Thread 2
  Request 2 running in Thread 2 gets a db connection
  (the same db connection just closed by Request 1).
  The JVM switches the running thread back to Thread 1
  Request 1 closes the db connection a second time in a finally block.
  The JVM switches the running thread back to Thread 2
  Request 2 Thread 2 tries to use the db connection but fails
  because Request 1 closed it.
----------------------------------------------------------------------------------------------
Here is an example of properly written code to use a db connection obtained from a connection pool:
Connection conn = null;
  Statement stmt = null;  // Or PreparedStatement if needed
  ResultSet rs = null;
  try {
    conn = ... get connection from connection pool ...
    stmt = conn.createStatement("select ...");
    rs = stmt.executeQuery();
    ... iterate through the result set ...
    rs.close();
    rs = null;
    stmt.close();
    stmt = null;
    conn.close(); // Return to connection pool
    conn = null;  // Make sure we don't close it twice
  } catch (SQLException e) {
    ... deal with errors ...
  } finally {
    // Always make sure result sets and statements are closed,
    // and the connection is returned to the pool
    if (rs != null) {
      try { rs.close(); } catch (SQLException e) { ; }
      rs = null;    //方便gc进行垃圾回收
    }
    if (stmt != null) {
      try { stmt.close(); } catch (SQLException e) { ; }
      stmt = null;
    }
    if (conn != null) {
      try { conn.close(); } catch (SQLException e) { ; }
      conn = null;
    }
  }

在spring中使用TomCat已配好的数据源:

  1. <!-- 通过JNDI 使用应用服务器 的Connection Pool--<  
  2. <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"<  
  3.     <property name="jndiName" value="java:comp/env/jdbc/coral"/<  
  4. </bean< 
 
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:803725次
    • 积分:8396
    • 等级:
    • 排名:第2433名
    • 原创:74篇
    • 转载:431篇
    • 译文:0篇
    • 评论:41条
    最新评论