免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1502 | 回复: 0
打印 上一主题 下一主题

Tomcat 5.5.x和 MySQL连接池的配置(JNDI) [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2006-01-07 20:02 |只看该作者 |倒序浏览

Tomcat 5.5.x和 MySQL连接池的配置(JNDI)
                              
大型数据库课程设计中想使用的技术,花点时间研究了下J

注意:
首先,Tomcat 5.5.x 中的连接池配置和Tomcat 5.0.x中有了较大变化
其次,配置TOMCAT连接池需要修改Tomcat 的配置文件 SERVER.XML(详情如下所述)
第三,jdbc驱动程序不要使用mysql-connector-java-[version](例如3.1.12) debug目录下的mysql-connector-java-[version]-bin-g.jar,这点在文档里有详细说明。Docs目录下,文档1.2.1.3. Installing the Driver and Configuring the CLASSPATH ,说明如下
You should not use the "debug" build of the driver unless instructed do do so when reporting a problem or bug to MySQL AB, as it is not designed to be run in production environments, and will have adverse performance impact when used. The debug binary also depends on the Aspect/J runtime library, which is located in the src/lib/aspectjrt.jar file that comes with the Connector/J distribution.
You will need to use the appropriate gui or command-line utility to un-archive the distribution (for example, WinZip for the .zip archive, and "tar" for the .tar.gz archive). Because there are potentially long filenames in the distribution, we use the GNU tar archive format. You will need to use GNU tar (or an application that understands the GNU tar archive format) to unpack the .tar.gz variant of the distribution.
Once you have extracted the distribution archive, you can install the driver by placing mysql-connector-java-[version]-bin.jar in your classpath, either by adding the FULL path to it to your CLASSPATH enviornment variable, or by directly specifying it with the commandline switch -cp when starting your JVM
当然,其中提到CLASSPATH的地方都不是针对Tomcat的,我们在web app中使用mysql-connector-java的时候,应将它复制到Servlet/JSP容器的 lib目录中,对于Tomcat就是%TOMCAT_HONE%/comman/lib,其他容器稍有不同

我的配置过程:
首先在 Eclipse中建立工程TestDB
然后参照mysql-connector-java-3.1.12中的文档,修改如图这个SERVER.XML,

注意:部署的时候是修改%TOMCAT_HONE%/CONF/SERVER.XML
在之前加入代码,如下:
                                               path="/TestDB" reloadable="true">

                                               
                                                        className="org.apache.catalina.logger.FileLogger"
                                                        prefix="localhost_DBTest_log." suffix=".txt" timestamp="true" />

                                               
                                                        type="javax.sql.DataSource" />

                                               
                                                        
                                                                 factory
                                                                 
                                                                           org.apache.commons.dbcp.BasicDataSourceFactory
                                                                 
                                                        

                                                        
                                                                 configure your mysqld max_connections large enough to handle
                                                                 all of your db connections. Set to 0 for no limit.
                                                        -->
                                                        
                                                                 maxActive
                                                                 100
                                                        

                                                        
                                                                 Set to -1 for no limit.  See also the DBCP documentation on this
                                                                 and the minEvictableIdleTimeMillis configuration parameter.
                                                        -->
                                                        
                                                                 maxIdle
                                                                 30
                                                        

                                                        
                                                                 in ms, in this example 10 seconds. An Exception is thrown if
                                                                 this timeout is exceeded.  Set to -1 to wait indefinitely.
                                                        -->
                                                        
                                                                 maxWait
                                                                 10000
                                                        
                                                        
                                                                 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.
                                                        -->
                                                        
                                                                 URL
                                                                  
                                                                           jdbc:mysql://localhost:3306/connectionpool?autoReconnect=true
                                                                 
                                                        
                                                          -->
                                                        
                                                                 username
                                                                 javauser
                                                        
                                                        
                                                                 password
                                                                 javadude
                                                        

                                                        
                                                                 if you want to use this driver - we recommend using Connector/J though
                                                                 
                                                                 driverClassName
                                                                 org.gjt.mm.mysql.Driver
                                                                 
                                                        -->

                                                        
                                                        
                                                                 driverClassName
                                                                 com.mysql.jdbc.Driver
                                                        

这段xml的配置是根据 Tomcat官方网站的说明来改的,按理说因该没有什么问题,以致后来出了问题我也没有把焦点放在它上面。

接下来修改TestDB工程的web.xml文件, 和之间加入如下代码(这里以及DAO中使用连接池的时候用到了JNDI)



resource-ref>
       description>JNDI DataSource Testdescription>
       res-ref-name>jdbc/TestDBres-ref-name>
       res-type>javax.sql.DataSourceres-type>
       res-auth>Containerres-auth>
       res-sharing-scope>Shareableres-sharing-scope>
    resource-ref>

做完这两部的配置以后,可以开始编码了
这里我去掉了很多注释,大家可以参看源文件

ConnectionPool.java( DAO,利用JNDI找到连接池,打开一个连接,向test表插入一条记录)
package cmn;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import javax.naming.InitialContext;
import javax.sql.DataSource;

public class ConnectionPool {

     public void doSomething() throws Exception {

         InitialContext ctx = new InitialContext();
         DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/TestDB");

         Connection conn = null;
         Statement stmt = null;

         try {
              conn = ds.getConnection();

              stmt = conn.createStatement();
              stmt.execute("insert into test values(null,'William','7113736')");

              stmt.close();
              stmt = null;

              conn.close();
              conn = null;
         } finally {

              if (stmt != null) {
                   try {
                       stmt.close();
                   } catch (SQLException sqlex) {
                       // ignore -- as we can't do anything about it here
                   }
                   stmt = null;
              }

              if (conn != null) {
                   try {
                       conn.close();
                   } catch (SQLException sqlex) {
                       // ignore -- as we can't do anything about it here
                   }
                   conn = null;
              }
         }
     }
}

InsertServlet.java (调用DAO,然后转向index.jsp成功则返回success)

package cmn;

import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* Servlet implementation class for Servlet: InsertServlet
*
*/
public class InsertServlet extends javax.servlet.http.HttpServlet implements
         javax.servlet.Servlet {

     private static final long serialVersionUID = 1L;

     public InsertServlet() {
         super();
     }

     protected void doGet(HttpServletRequest request,
              HttpServletResponse response) throws ServletException, IOException {
         // TODO doPost() impementation

         String target=target="/index.jsp";
         
         ConnectionPool cp = new ConnectionPool();
         try {
              cp.doSomething();
              request.setAttribute("status","success");
         } catch (Exception e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
         }

         
         //设置转向
         ServletContext context=getServletContext();
         RequestDispatcher requestDis = context.getRequestDispatcher(target);
         requestDis.forward(request, response);
     }

     protected void doPost(HttpServletRequest request,
              HttpServletResponse response) throws ServletException, IOException {
         // TODO Do the same as doGet()
         doGet(request, response);
     }
}

Index.jsp (没什么内容J)
page language="java" contentType="text/html; charset=GBK"
    pageEncoding="GBK"%>
    String status=(String)request.getAttribute("status"); %>
DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
html>
head>
meta http-equiv="Content-Type" content="text/html; charset=GBK">
title>testtitle>
head>
body>
table>tr>
td>a href="/TestDB/InsertServlet">InsertServleta>td>tr>table>
if (status!=null) out.print(status); %>
body>
html>

关于数据库的说明
Test表的结构(属于connectionpool数据库)
+-------+------------------+------+-----+---------+----------------+
| Field | Type               | Null | Key | Default | Extra             |
+-------+------------------+------+-----+---------+----------------+
| id    | int(10) unsigned | NO    | PRI | NULL     | auto_increment  |
| name  | varchar(45)       | NO    |     |            |                    |
| tel   | varchar(45)       | NO    |     |            |                    |
+-------+------------------+------+-----+---------+-----------------+

执行成功以…
mysql> select * from test;
+----+---------+---------+
| id | name    | tel     |
+----+---------+---------+
|  1 | William | 7113736 |
+----+---------+---------+

问题:
Exception!!!

org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create JDBC driver of class '' for connect URL 'null'
google的结果告诉我这是 server.xml配置有误,NND这怎么可能,官方的配置实例还有错?!
想到刚才测试standalone app的时候提示class not found exception,很快认为是没有找到Driver,搞了好久,什么改CLASSPATH啊,将commons-dbcp-1.2.1.jar、commons-pool-1.2.jar、commons-collections-3.1.jar放到tomcat的common/lib下啊,试了遍,依旧无果!

解决问题:累了,喝杯水,翻了一下doc 在1.4.2. Using Connector/J with Tomcat 的最下面看到这样一段话,感觉有点&^*#@......

In general, you should follow the installation instructions that come with your version of Tomcat, as the way you configure datasources in Tomcat changes from time-to-time, and unfortunately if you use the wrong syntax in your XML file, you will most likely end up with an exception similar to the following:
Error: java.sql.SQLException: Cannot load JDBC driver class 'null ' SQL
state: null


靠,这不和我遇到的问题很像嘛,立马google,keyword :Cannot create JDBC driver of class '' for connect URL 'null'

找到了这个
http://www.evolutionnext.com/blog/2005/10/13/1129259088959.html
好小子,耍我!Tomcat官方的文档还没有来得及更新,使针对 Tomcat 5.0.x !

把Server.xml改成这样
Context crossContext="true" debug="5" docBase="TestDB"
                    path="/TestDB" reloadable="true">
        Resource name="jdbc/TestDB"
                type="javax.sql.DataSource" auth="Container"
                driverClassName="com.mysql.jdbc.Driver" maxActive="100"
                maxIdle="30" maxWait="10000"                url="jdbc:mysql://localhost:3306/connectionpool?autoReconnect=true"
                username="root" password="admin" />
Context>
说明:这里的
url="jdbc:mysql://localhost:3306/connectionpool?autoReconnect=true"
中的connectionpool为数据库名

编译,执行,Success!

参考资料:
http://www.evolutionnext.com/blog/2005/10/13/1129259088959.html
connector-j online doc
tomcat online doc
O’reilly - Java Server Pages

附件:Connectionpool Example.rar Eclipse工程文件

文件:
Connectionpool Example.rar
大小:
6KB
下载:
下载

1/7/2006



本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/4296/showart_66056.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP