tomcat连接池配置 要求修改server.xml 修改方法以及测试程序如下 <!-- Tomcat Root Context --> <Context path="" docBase="ROOT" debug="0"> <Resource name="jdbc/Mysql" auth="SERVLET" type="javax.sql.DataSource"/> <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>root</value> </parameter> <parameter> <name>password</name> <value></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://192.168.238.35:3306/javatest</value> </parameter> </ResourceParams> <ResourceParams name="jdbc/Mysql"> <parameter> <name>factory</name> <value>org.apache.commons.dbcp.BasicDataSourceFactory</value> </parameter> <parameter> <name>driverClassName</name> <value>org.gjt.mm.mysql.Driver</value> </parameter> <parameter> <name>url</name> <value>jdbc:mysql://192.168.238.35/mail</value> </parameter> <parameter> <name>username</name> <value>root</value> </parameter>
<parameter>
<name>password</name>
<value></value>
</parameter>
<parameter>
<name>maxActive</name>
<value>20</value>
</parameter>
<parameter>
<name>maxIdle</name>
<value>10</value>
</parameter>
<parameter>
<name>maxWait</name>
<value>-1</value>
</parameter> </ResourceParams> </Context> </Host> </Engine> </Service> <!-- The MOD_WEBAPP connector is used to connect Apache 1.3 with Tomcat 4.0 as its servlet container. Please read the README.txt file coming with the WebApp Module distribution on how to build it. (Or check out the "jakarta-tomcat-connectors/webapp" CVS repository) To configure the Apache side, you must ensure that you have the "ServerName" and "Port" directives defined in "httpd.conf". Then, lines like these to the bottom of your "httpd.conf" file: LoadModule webapp_module libexec/mod_webapp.so WebAppConnection warpConnection warp localhost:8008 WebAppDeploy examples warpConnection /examples/ The next time you restart Apache (after restarting Tomcat, if needed) the connection will be established, and all applications you make visible via "WebAppDeploy" directives can be accessed through Apache. -->
如果要自己写连接池,可以参考DBConnectionManager之类的简单、经典的连接池。
***************************************
import javax.servlet.* ;
import javax.servlet.http.* ;
import java.io.* ;
import java.sql.* ;
import java.util.Vector;
import oracle.jdbc.driver.*;
import java.util.Enumeration;
import java.util.Properties;
import com.unitech.connectionpool.* ;
public class dbTest extends HttpServlet {
//Initialize global variables
public void init(ServletConfig config) throws ServletException {
super.init(config); }
// 数据库连接:Connetcion conn = null ;
Connection conn = null ;
//数据库查询内容执行:Statement stment = null ;
Statement stment = null ;
// 数据库连接池的初始化
DBConnectionManager connMgr = DBConnectionManager.getInstance(); //初始化数据库连接池,并且获取数据库连接
private void initDatabaseDriver () {
conn = connMgr.getConnection("oracle");
if (conn == null) {
System.out.println("数据库连接失败。");
return;
}
try {
stment = conn.createStatement();
}
catch (SQLException e) {
e.printStackTrace() ;
}
} //释放数据库连接
private void freeConnectionPool() {
connMgr.freeConnection("oracle", conn) ;
} //获取记录集,并返回给VERTOR V
public Vector getForumList() {
String[] s = {"","","","",""} ;//与选取的列数相等。
Vector v = new Vector() ;
this.initDatabaseDriver();
try{
String queryStr = null ;
queryStr = "SELECT BBS_ID,BBS_NAME,DESCRIPTION,MANAGER_ID, CREATE_DATE FROM BBS WHERE IS_SYSTEM='0' ORDER BY CREATE_DATE DESC" ;
ResultSet rSet = stment.executeQuery(queryStr) ;
while (rSet.next()) {
s[0] = Integer.toString(rSet.getInt("BBS_ID")) ;
s[1] = rSet.getString("BBS_NAME") ;
s[2] = rSet.getString("DESCRIPTION") ;
s[3] = rSet.getString("MANAGER_ID") ;
Timestamp createdate = rSet.getTimestamp("CREATE_DATE") ;
String tmp = createdate.toString() ;
s[4] = tmp.substring(0,(tmp.length()-2)) ;
v.addElement(s.clone());
}
rSet.close();
stment.close();
this.freeConnectionPool();
}
catch(Exception e) {
try {
stment.close();
this.freeConnectionPool();
}
catch(SQLException ee) {
ee.printStackTrace();
}
e.printStackTrace() ;
}
return v ;
} //Process the HTTP Get request
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = new PrintWriter (response.getOutputStream());
response.setContentType("text/html");
out.println("");
out.println("The servlet has received a GET. This is the reply.");
out.println("");
out.println(""); // 将记录集循环输出到页面。
Vector v = new Vector() ;
v = this.getForumList() ;
for (int i=0; i"
+ ""+s[0]+""
+ ""+s[1]+""
+ ""+s[2]+""
+ ""+s[3]+""
+ ""+s[4]+"");
}
out.println("");
out.close();
}
}
强烈建议用TOMCAT自带的连接池!
嘿嘿,TOMCAT也是世界上许许多多的顶极高手编写出来的。
<!-- Tomcat Root Context -->
<Context path="" docBase="ROOT" debug="0">
<Resource name="jdbc/Mysql" auth="SERVLET" type="javax.sql.DataSource"/>
<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>root</value>
</parameter>
<parameter>
<name>password</name>
<value></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://192.168.238.35:3306/javatest</value>
</parameter>
</ResourceParams>
<ResourceParams name="jdbc/Mysql">
<parameter>
<name>factory</name>
<value>org.apache.commons.dbcp.BasicDataSourceFactory</value>
</parameter>
<parameter>
<name>driverClassName</name>
<value>org.gjt.mm.mysql.Driver</value>
</parameter>
<parameter>
<name>url</name>
<value>jdbc:mysql://192.168.238.35/mail</value>
</parameter>
<parameter>
<name>username</name>
<value>root</value>
</parameter>
<parameter>
<name>password</name>
<value></value>
</parameter>
<parameter>
<name>maxActive</name>
<value>20</value>
</parameter>
<parameter>
<name>maxIdle</name>
<value>10</value>
</parameter>
<parameter>
<name>maxWait</name>
<value>-1</value>
</parameter>
</ResourceParams>
</Context>
</Host> </Engine> </Service> <!-- The MOD_WEBAPP connector is used to connect Apache 1.3 with Tomcat 4.0
as its servlet container. Please read the README.txt file coming with
the WebApp Module distribution on how to build it.
(Or check out the "jakarta-tomcat-connectors/webapp" CVS repository) To configure the Apache side, you must ensure that you have the
"ServerName" and "Port" directives defined in "httpd.conf". Then,
lines like these to the bottom of your "httpd.conf" file: LoadModule webapp_module libexec/mod_webapp.so
WebAppConnection warpConnection warp localhost:8008
WebAppDeploy examples warpConnection /examples/ The next time you restart Apache (after restarting Tomcat, if needed)
the connection will be established, and all applications you make
visible via "WebAppDeploy" directives can be accessed through Apache.
-->
<%@ page import= "java.sql.* "%>
<%@ page import= "javax.sql.DataSource"%>
<%@ page import= "javax.naming.*"%>
<html>
<head>
<title>DB Test</title>
</head>
<body> <%
String foo = "Not Connected";
int bar = -1; try{
Context ctx = new InitialContext();
if(ctx == null )
throw new Exception("Boom - No Context"); DataSource ds =
(DataSource)ctx.lookup(
"java:comp/env/jdbc/TestDB");
out.println("get here!!");
if (ds != null) {
Connection conn = ds.getConnection();
out.println("get here!!!!");
if(conn != null) {
foo = "Got Connection "+conn.toString();
Statement stmt = conn.createStatement();
ResultSet rst =
stmt.executeQuery(
"select id, foo, bar from testdata");
out.println("get here!!!!!");
//out.println(rst.next());
if(rst.next()) {
out.println("get here haha");
foo=rst.getString(2);
bar=rst.getInt(3);
out.println("foo is "+foo);
out.println("bar is "+bar);
}
conn.close();
}
}
}catch(Exception e) {
e.printStackTrace();
}
%> <h2>Results</h2>
</body>
</html>