随笔-17  评论-64  文章-79  trackbacks-1
配置Tomcat 4.1.29的连接池
Tomcat 4.1.29是目前的最高稳定版本,下面介绍一下它的连接池配置方法。
1)    连接池配置(Database Connection Pool (DBCP) Configurations)
DBCP使用的是Jakarta-Commons Database Connection Pool 要使用连接池需要如下的组件即jar文件。
Jakarta-Commons DBCP 1.1 对应commons-dbcp-1.1.jar。
Jakarta-Commons Collections 2.0 对应commons-collections.jar。
Jakarta-Commons Pool 1.1 对应commons-pool-1.1.jar。
这三个jar文件要与你的JDBC驱动程序一起放到【TOMCAT_HOME】\common\lib目录下以便让tomcat和你的web应用都能够找到。
注:这三个jar文件是默认存在与【TOMCAT_HOME】\common\lib下的。
需要注意的地方:第三方的驱动程序或者其他类只能以*.jar的形式放到Tomcat的common\lib目录中,因为Tomcat只把*.jar文件加到CLASSPATH中。
不要把上诉三个文件放到WEB-INF/lib或者其他地方因为这样会引起混淆。

2)    通过配置阻止连接池漏洞
数据库连接池创建和管理连接池中建立好的数据库连接,循环使用这些连接以得到更好的效率。这样比始终为一个用户保持一个连接和为用户的请求频繁的建立和销毁数据库连接要高效的多。
这样就有一个问题出现了,一个Web应用程序必须显示的释放ResultSet,Statement和Connection。如果在关闭这些资源的过程中失败将导致这些资源永远不在可用,这就是所谓的连接池漏洞。这个漏洞最终会导致连接池中所有的连接不可用。
通过配置Jakarta Common DBCP可以跟踪和恢复那些被遗弃的数据库连接。
以下是一系列相关配置:
    通过配置DBCP数据源中的参数removeAbandoned来保证删除被遗弃的连接使其可以被重新利用。
为ResourceParams(见下文的数据源配置)标签添加参数removeAbandoned
<parameter>
<name>removeAbandoned</name>
<value>true</value>
</parameter>
通过这样配置的以后当连接池中的有效连接接近用完时DBCP将试图恢复和重用被遗弃的连接。这个参数的值默认是false。
    通过设置removeAbandonedTimeout来设置被遗弃的连接的超时的时间,即当一个连接连接被遗弃的时间超过设置的时间时那么它会自动转换成可利用的连接。
    <parameter>
     <name>removeAbandonedTimeout</name>
     <value>60</value>
     </parameter>
    默认的超时时间是300秒。
    设置logAbandoned参数,这个参数的用处我没能够理解它的意义所以提供原文供大家参考。
The logAbandoned parameter can be set to true if you want DBCP to log a stack trace of the code which abandoned the dB connection resources。
<parameter>
<name>logAbandoned</name>
<value>true</value>
</parameter>
这个参数默认为false。

3)    下面以MySQL为例演示Tomcat数据库连接池的配置
    MySQL的版本以及对应的JDBC驱动程序
MySQL 3.23.47, MySQL 3.23.47 using InnoDB, MySQL 4.0.1alpha对应的驱动为mm.mysql 2.0.14 (JDBC Driver)。
    在MySQL中创建供测试的数据库,表结构以及数据
mysql> create database javatest;
mysql> use javatest;
mysql> create table testdata (
    ->   id int not null auto_increment primary key,
    ->   foo varchar(25), 
    ->   bar int);
    mysql> insert into testdata values(null, 'hello', 12345);
Query OK, 1 row affected (0.00 sec)

mysql> select * from testdata;
+----+-------+-------+
| ID | FOO   | BAR   |
+----+-------+-------+
|  1 | hello | 12345 |
+----+-------+-------+
1 row in set (0.00 sec)


    要注意的是登录的mysql用户要有创建数据库的权限还有注意要设置密码我用的是root^_^。
    配置Tomcat的server.xml文件
配置【TOMCAT_HOME】\common\lib下的server.xml文件,在</host>标签之前加入以下内容以添加JNDI数据源:
<Context path="/DBTest" docBase="DBTest"
        debug="5" reloadable="true" crossContext="true">
  <Logger className="org.apache.catalina.logger.FileLogger"
             prefix="localhost_DBTest_log." suffix=".txt"
             timestamp="true"/>
  <Resource name="jdbc/TestDB"
               auth="Container"
               type="javax.sql.DataSource"/>
  <ResourceParams name="jdbc/TestDB">
    <parameter>
      <name>factory</name>
    <value>org.apache.commons.dbcp.BasicDataSourceFactory</value>
    </parameter>
    <!-- Maximum number of dB connections in pool. Make sure you
         configure your mysqld max_connections large enough to handle
         all of your db connections. Set to 0 for no limit.
         -->
    <parameter>
      <name>maxActive</name>
      <value>100</value>
    </parameter>
    <!-- Maximum number of idle dB connections to retain in pool.
         Set to 0 for no limit.
         -->
    <parameter>
      <name>maxIdle</name>
      <value>30</value>
    </parameter>
    <!-- Maximum time to wait for a dB connection to become available
         in ms, in this example 10 seconds. An Exception is thrown if
         this timeout is exceeded.  Set to -1 to wait indefinitely.
         -->
    <parameter>
      <name>maxWait</name>
      <value>10000</value>
    </parameter>
    <!-- MySQL dB username and password for dB connections  -->
    <parameter>
     <name>username</name>
     <value>javauser</value>
    </parameter>
    <parameter>
     <name>password</name>
     <value>javadude</value>
    </parameter>
    <!-- Class name for mm.mysql JDBC driver -->
    <parameter>
       <name>driverClassName</name>
       <value>org.gjt.mm.mysql.Driver</value>
    </parameter>
    <!-- The JDBC connection url for connecting to your MySQL dB.
         The autoReconnect=true argument to the url makes sure that the
         mm.mysql JDBC Driver will automatically reconnect if mysqld closed the
         connection.  mysqld by default closes idle connections after 8 hours.
         -->
    <parameter>
      <name>url</name> <value>jdbc:mysql://localhost:3306/javatest?autoReconnect=true</value>
    </parameter>
  </ResourceParams>
</Context>
    配置Web应用程序的web.xml文件
<?xml version="1.0" encoding="ISO-8859-1"?>
    <!DOCTYPE web-app PUBLIC
    "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
  <description>MySQL Test App</description>
  <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>
  </resource-ref>
</web-app>

    测试代码
测试代码包括一个JSP文件和一个Java类。代码如下:
  1. <html>
  2.   <head>
  3.     <title>DB Test</title>
  4.   </head>
  5.   <body>
  6.   <%
  7.     foo.DBTest tst = new foo.DBTest();
  8.     tst.init();
  9.   %>
  10.   <h2>Results</h2>
  11.     Foo <%= tst.getFoo() %><br>
  12.     Bar <%= tst.getBar() %>
  13.   </body>
  14. </html>
  15. package foo;
  16. import javax.naming.*;
  17. import javax.sql.*;
  18. import java.sql.*;
  19. public class DBTest {
  20.   String foo = "Not Connected";
  21.   int bar = -1;
  22.     
  23.   public void init() {
  24.     try{
  25.       Context ctx = new InitialContext();
  26.       if(ctx == null ) 
  27.           throw new Exception("Boom - No Context");
  28.       DataSource ds = 
  29.             (DataSource)ctx.lookup(
  30.                "java:comp/env/jdbc/TestDB");
  31.       if (ds != null) {
  32.         Connection conn = ds.getConnection();     
  33.         if(conn != null)  {
  34.             foo = "Got Connection "+conn.toString();
  35.             Statement stmt = conn.createStatement();
  36.             ResultSet rst = 
  37.                 stmt.executeQuery(
  38.                   "select id, foo, bar from testdata");
  39.             if(rst.next()) {
  40.                foo=rst.getString(2);
  41.                bar=rst.getInt(3);
  42.             }
  43.             conn.close();
  44.         }
  45.       }
  46.     }catch(Exception e) {
  47.       e.printStackTrace();
  48.     }
  49.  }
  50.  public String getFoo() { return foo; }
  51.  public int getBar() { return bar;}
  52. }

最后在Tomcat的webapps目录下建立DBTest然后将应用程序文件拷贝到这个目录下即可。
    重新启动Tomcat在浏览器上http://localhost:8080/DBTest/test.jsp即可看到结果。
Results
Foo hello
Bar 12345

4)    一些常见的问题
    由于垃圾收集器的运行而导致连接超时
Tomcat是运行在JVM中的,JVM要周期性的执行GC(垃圾收集器)来清除不再被引用的Java对象。在GC运行时Tomcat将会冻结,如果在设置连接池中的连接的最大等待时间(MaxWait)小于GC的运行时间的话那么你很可能在使用数据库连接时失败。推荐将连接的超时时间设置成10到15秒。
注意连接的超时时间与被遗弃的连接的超时时间的区别。
    重复关闭连接引发的异常
这种情况发生在当响应一个客户的请求时从数据库连接池里取得了连接但是关闭了两次。使用连接池中的连接与使用直接与数据库建立的连接是不一样的,连接池中的连接在释放时只是将连接返回到连接池而不是释放连接的资源。Tomcat使用多线程来处理并发的请求,以下实例演示了一个在Tomcat中可以导致出错的过程:
请求A在线程A中运行并从连接池中得到一个连接
请求A关闭了这个连接
JVM转到线程B
请求B在线程B中运行并取得一个连接(这个连接是请求A刚刚返回的那个)
JVM转到线程A
请求A在finally块中又一次关闭连接(因为第一次没有设置连接引用为null)
JVM转到线程B
请求B试图使用得到的连接但连接已经被请求A返回到了连接池中所以请求B的操作失败
以下是一段公认的恰当的代码可以避免以上的问题
  1.   Connection conn = null;
  2.   Statement stmt = null;  // Or PreparedStatement if needed
  3.   ResultSet rs = null;
  4.   try {
  5.     conn = ... get connection from connection pool ...
  6.     stmt = conn.createStatement("select ...");
  7.     rs = stmt.executeQuery();
  8.     ... iterate through the result set ...
  9.     rs.close();
  10.     rs = null;
  11.     stmt.close();
  12.     stmt = null;
  13.     conn.close(); // Return to connection pool
  14.     conn = null;  // Make sure we don't close it twice
  15.   } catch (SQLException e) {
  16.     ... deal with errors ...
  17.   } finally {
  18.     // Always make sure result sets and statements are closed,
  19.     // and the connection is returned to the pool
  20.     if (rs != null) {
  21.       try { rs.close(); } catch (SQLException e) { ; }
  22.       rs = null;
  23.     }
  24.     if (stmt != null) {
  25.       try { stmt.close(); } catch (SQLException e) { ; }
  26.       stmt = null;
  27.     }
  28.     if (conn != null) {
  29.       try { conn.close(); } catch (SQLException e) { ; }
  30.       conn = null;
  31.     }
  32.   }
posted on 2006-05-18 13:45 飞鸟 阅读(572) 评论(0)  编辑  收藏 所属分类: JSP

只有注册用户登录后才能发表评论。


网站导航: