配置Tomcat 4.1.29的连接池
2005-06-05 12:59
495 查看
配置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中创建供测试的数据库,表结构以及数据
[pre]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)[/pre]
要注意的是登录的mysql用户要有创建数据库的权限还有注意要设置密码我用的是root^_^。
配置Tomcat的server.xml文件
配置【TOMCAT_HOME】/common/lib下的server.xml文件,在</host>标签之前加入以下内容以添加JNDI数据源:
[pre]<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/javat
4000
est?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>[/pre]
测试代码
测试代码包括一个JSP文件和一个Java类。代码如下:
<html>
<head>
<title>DB Test</title>
</head>
<body>
<%
foo.DBTest tst = new foo.DBTest();
tst.init();
%>
<h2>Results</h2>
Foo <%= tst.getFoo() %><br>
Bar <%= tst.getBar() %>
</body>
</html>
package foo;
import javax.naming.*;
import javax.sql.*;
import java.sql.*;
public class DBTest {
String foo = "Not Connected";
int bar = -1;
public void init() {
try{
Context ctx = new InitialContext();
if(ctx == null )
throw new Exception("Boom - No Context");
DataSource ds =
(DataSource)ctx.lookup(
"java:comp/env/jdbc/TestDB");
if (ds != null) {
Connection conn = ds.getConnection();
if(conn != null) {
foo = "Got Connection "+conn.toString();
Statement stmt = conn.createStatement();
ResultSet rst =
stmt.executeQuery(
"select id, foo, bar from testdata");
if(rst.next()) {
foo=rst.getString(2);
bar=rst.getInt(3);
}
conn.close();
}
}
}catch(Exception e) {
e.printStackTrace();
}
}
public String getFoo() { return foo; }
public int getBar() { return bar;}
}
最后在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的操作失败
以下是一段公认的恰当的代码可以避免以上的问题
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;
}
if (stmt != null) {
try { stmt.close(); } catch (SQLException e) { ; }
stmt = null;
}
if (conn != null) {
try { conn.close(); } catch (SQLException e) { ; }
conn = null;
}
}
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中创建供测试的数据库,表结构以及数据
[pre]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)[/pre]
要注意的是登录的mysql用户要有创建数据库的权限还有注意要设置密码我用的是root^_^。
配置Tomcat的server.xml文件
配置【TOMCAT_HOME】/common/lib下的server.xml文件,在</host>标签之前加入以下内容以添加JNDI数据源:
[pre]<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/javat
4000
est?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>[/pre]
测试代码
测试代码包括一个JSP文件和一个Java类。代码如下:
<html>
<head>
<title>DB Test</title>
</head>
<body>
<%
foo.DBTest tst = new foo.DBTest();
tst.init();
%>
<h2>Results</h2>
Foo <%= tst.getFoo() %><br>
Bar <%= tst.getBar() %>
</body>
</html>
package foo;
import javax.naming.*;
import javax.sql.*;
import java.sql.*;
public class DBTest {
String foo = "Not Connected";
int bar = -1;
public void init() {
try{
Context ctx = new InitialContext();
if(ctx == null )
throw new Exception("Boom - No Context");
DataSource ds =
(DataSource)ctx.lookup(
"java:comp/env/jdbc/TestDB");
if (ds != null) {
Connection conn = ds.getConnection();
if(conn != null) {
foo = "Got Connection "+conn.toString();
Statement stmt = conn.createStatement();
ResultSet rst =
stmt.executeQuery(
"select id, foo, bar from testdata");
if(rst.next()) {
foo=rst.getString(2);
bar=rst.getInt(3);
}
conn.close();
}
}
}catch(Exception e) {
e.printStackTrace();
}
}
public String getFoo() { return foo; }
public int getBar() { return bar;}
}
最后在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的操作失败
以下是一段公认的恰当的代码可以避免以上的问题
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;
}
if (stmt != null) {
try { stmt.close(); } catch (SQLException e) { ; }
stmt = null;
}
if (conn != null) {
try { conn.close(); } catch (SQLException e) { ; }
conn = null;
}
}
相关文章推荐
- Java web----Tomcat配置连接池
- jboss-3.2.0_tomcat-4.1.24 连接池配置方法
- tomcat5.5配置MYSQL数据库连接池
- Tomcat6.0连接池配置(oracle)
- win2000+Tomcat5.0.27+Oracle8.1.7配置连接池(同时在54bk上发表)
- tomcat配置连接池错误解决
- tomcat 连接池配置
- Spring+Tomcat的JNDI数据源连接池简单配置
- Proxool连接池在tomcat+mysql环境下的配置
- Tomcat5.5 连接池配置
- Tomcat下配置连接池
- Tomcat+Oracle配置连接池的例子
- JSP中tomcat的SQL Server2000数据库连接池的配置
- tomcat中的几种连接池配置代码(包括tomcat5.0,tomcat5.5x,tomcat6.0)
- tomcat6.0 连接池配置
- Eclipse 下配置MySql5.6的连接池,使用Tomcat7.0
- tomcat 连接池(mysql)配置
- tomcat6.0中jdni连接池的配置
- Tomcat5.5.23 配置mysql数据库连接池
- JSP中tomcat的SQL Server2000数据库连接池的配置