2009年8月3日 星期一

Mysql+tomcat 6.0.14使用Connection Pool之設定方法

1.修改server.xml
(此檔位於Tomcat安裝之目錄下,如c:\Program Files\Apache Software Foundation\Tomcat 6.0\conf)內容如下:
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--><!-- Note: A "Server" is not itself a "Container", so you may not
define subcomponents such as "Valves" at this level.
Documentation at /docs/config/server.html
--><Server port="8005" shutdown="SHUTDOWN">
<!--APR library loader. Documentation at /docs/apr.html -->
<Listener SSLEngine="on" className="org.apache.catalina.core.AprLifecycleListener"/>
<!--Initialize Jasper prior to webapps are loaded. Documentation at /docs/jasper-howto.html -->
<Listener className="org.apache.catalina.core.JasperListener"/>
<!-- JMX Support for the Tomcat server. Documentation at /docs/non-existent.html -->
<Listener className="org.apache.catalina.mbeans.ServerLifecycleListener"/>
<Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener"/>
<!-- Global JNDI resources
Documentation at /docs/jndi-resources-howto.html
-->
<GlobalNamingResources>
<!-- Editable user database that can also be used by
UserDatabaseRealm to authenticate users
-->
<Resource auth="Container" description="User database that can be updated and saved" factory="org.apache.catalina.users.MemoryUserDatabaseFactory" name="UserDatabase" pathname="conf/tomcat-users.xml" type="org.apache.catalina.UserDatabase"/>
</GlobalNamingResources>
<!-- A "Service" is a collection of one or more "Connectors" that share
a single "Container" Note: A "Service" is not itself a "Container",
so you may not define subcomponents such as "Valves" at this level.
Documentation at /docs/config/service.html
-->
<Service name="Catalina">
<!--The connectors can use a shared executor, you can define one or more named thread pools-->
<!--
<Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
maxThreads="150" minSpareThreads="4"/>
-->
<!-- A "Connector" represents an endpoint by which requests are received
and responses are returned. Documentation at :
Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)
Java AJP Connector: /docs/config/ajp.html
APR (HTTP/AJP) Connector: /docs/apr.html
Define a non-SSL HTTP/1.1 Connector on port 8080
-->
<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>
<!-- A "Connector" using the shared thread pool-->
<!--
<Connector executor="tomcatThreadPool"
port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
-->
<!-- Define a SSL HTTP/1.1 Connector on port 8443
This connector uses the JSSE configuration, when using APR, the
connector should be using the OpenSSL style configuration
described in the APR documentation -->
<!--
<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
maxThreads="150" scheme="https" secure="true"
clientAuth="false" sslProtocol="TLS" />
-->
<!-- Define an AJP 1.3 Connector on port 8009 -->
<Connector port="8009" protocol="AJP/1.3" redirectPort="8443"/>
<!-- An Engine represents the entry point (within Catalina) that processes
every request. The Engine implementation for Tomcat stand alone
analyzes the HTTP headers included with the request, and passes them
on to the appropriate Host (virtual host).
Documentation at /docs/config/engine.html -->
<!-- You should set jvmRoute to support load-balancing via AJP ie :
<Engine name="Standalone" defaultHost="localhost" jvmRoute="jvm1">
-->
<Engine defaultHost="localhost" name="Catalina">
<!--For clustering, please take a look at documentation at:
/docs/cluster-howto.html (simple how to)
/docs/config/cluster.html (reference documentation) -->
<!--
<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
-->
<!-- The request dumper valve dumps useful debugging information about
the request and response data received and sent by Tomcat.
Documentation at: /docs/config/valve.html -->
<!--
<Valve className="org.apache.catalina.valves.RequestDumperValve"/>
-->
<!-- This Realm uses the UserDatabase configured in the global JNDI
resources under the key "UserDatabase". Any edits
that are performed against this UserDatabase are immediately
available for use by the Realm. -->
<Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase"/>
<!-- Define the default virtual host
Note: XML Schema validation will not work with Xerces 2.2.
-->
<Host appBase="webapps" autoDeploy="true" name="localhost" unpackWARs="true" xmlNamespaceAware="false" xmlValidation="false">
<!-- SingleSignOn valve, share authentication between web applications
Documentation at: /docs/config/valve.html -->
<!--
<Valve className="org.apache.catalina.authenticator.SingleSignOn" />
-->
<!-- Access log processes all example.
Documentation at: /docs/config/valve.html -->
<!--
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
prefix="localhost_access_log." suffix=".txt" pattern="common" resolveHosts="false"/>
-->
<Context docBase="Study" path="/Study" reloadable="true" source="org.eclipse.jst.jee.server:Study">
<!-- add by Nelson for mysql JNDI DataSource on 2009/08/03 ,start -->
<!-- maxActive: 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 -1 for no limit.
-->
<!-- maxIdle: Maximum number of idle dB connections to retain in pool.
Set to -1 for no limit. See also the DBCP documentation on this
and the minEvictableIdleTimeMillis configuration parameter.
-->
<!-- maxWait: 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.
-->
<!-- username and password: MySQL dB username and password for dB connections -->
<!-- driverClassName: Class name for the old mm.mysql JDBC driver is
org.gjt.mm.mysql.Driver - we recommend using Connector/J though.
Class name for the official MySQL Connector/J driver is com.mysql.jdbc.Driver.
-->
<!-- url: 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.
-->
<Resource name="jdbc/manningDB" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="manning" password="action" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/manning"/>
<!-- add by Nelson for mysql JNDI DataSource on 2009/08/03 ,end -->
</Context>
</Host>
</Engine>
</Service>
</Server>
==========================================
2.修改web.xml,內容如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>Study</display-name>
<!-- for Struts2 start -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- for Struts2 end -->
<!-- add by Nelson for mysql JNDI DataSource on 2009/08/03 ,start -->
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/manningDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
<!-- add by Nelson for mysql JNDI DataSource on 2009/08/03 ,end -->
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
=======================================
3.將下面4個jar檔放置於Tomcat安裝之目錄下(c:\Program Files\pache Software Foundation\Tomcat 6.0\lib):
3.1. commons-dbcp-1.2.2.jar
3.2. commons-collections-3.2.1.jar
3.3. commons-pool-1.5.2.jar
3.4. mysql-connector-java-5.1.5-bin.jar
4.DataAccess Class加入一個Method(getConnectionPool),內容如下:
package study;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.sql.DataSource;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class DataAccess {
private Connection conn;
private DataSource ds;
private static final String driver="com.mysql.jdbc.Driver";
private static final String url="jdbc:mysql://localhost:3306/manning";
private static final String username="manning";
private static final String password="action";
public Connection getConnection()throws Exception{
try{
Class.forName(driver);
conn = DriverManager.getConnection(url,username,password);
}catch(ClassNotFoundException cnfe){
cnfe.printStackTrace();
throw new Exception(cnfe.getMessage());
}catch(SQLException sqle){
sqle.printStackTrace();
throw new Exception(sqle.getMessage());
}
return conn;
}
public Connection getConnectionPool()throws Exception{
try{
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
ds = (DataSource)envContext.lookup("jdbc/manningDB");
}catch(NamingException ne){
ne.printStackTrace();
throw new Exception(ne.getMessage());
}
try{
conn = ds.getConnection();
}catch(SQLException sqle){
sqle.printStackTrace();
throw new Exception(sqle.getMessage());
}
return conn;
}
}
==========================================
5.修改PageDAO Class改以Connection Pool方法,內容如下:

package study;
import java.util.List;
import java.util.ArrayList;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class PageDAO{
private Connection conn;
private PreparedStatement pstmt;
private ResultSet rs;
private DataAccess da = new DataAccess();
private Student student;
public List<Student> queryByPage(int pageSize,int pageNow)throws Exception{
List<Student> list = new ArrayList<Student>();
String sql=null;
if(conn==null){
//conn = da.getConnection();
conn = da.getConnectionPool();
}
try{
if(conn!=null && pageSize>0 && pageNow>0){
sql = "select * from student order by stu_id limit ";
sql = sql+(pageNow*pageSize-pageSize)+","+pageSize;
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
while(rs.next()){
student = new Student();
student.setStu_id(rs.getInt("stu_id"));
student.setStuName(rs.getString("stuName"));
student.setAddress(rs.getString("address"));
student.setStuPhone(rs.getString("stuPhone"));
list.add(student);
}
}
}catch(SQLException sqle){
sqle.printStackTrace();
throw new Exception(sqle.getMessage());
}finally{
if(!conn.isClosed()){
if(rs!=null){
rs.close();
}
if(pstmt!=null){
pstmt.close();
}
conn.close();
conn=null;
}
}
return list;
}
public int getCount()throws Exception{
String sql = null;
int count = 0;
if(conn==null){
//conn = da.getConnection();
conn = da.getConnectionPool();
}
try{
if(conn!=null){
sql = "select count(stu_id) as count from student";
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
while(rs.next()){
count = rs.getInt("count");
}
}
}catch(SQLException sqle){
sqle.printStackTrace();
throw new Exception(sqle.getMessage());
}catch(Exception e){
e.printStackTrace();
throw new Exception(e.getMessage());
}finally{
if(!conn.isClosed()){
if(rs!=null){
rs.close();
}
if(pstmt!=null){
pstmt.close();
}
conn.close();
conn=null;
}
}
return count;
}
}

==========================================
6.測試結果:

沒有留言:

張貼留言