the5fire

关注Python、Django、Vim、Linux、Web开发、团队管理和互联网--Life is short, we need Python.


tomcat配置数据库连接池

作者:the5fire | 标签:     | 发布:2011-01-07 5:29 p.m. | 阅读量: 9396, 9186

其实就是一个挺简单的配置,可却花费了我不少时间,何故?都是那个界面惹的祸呀。

数据库连接池是干啥的我就不用多少了,从名字上就可以看的出来(A:我看不出来。B:去看百科:http://baike.baidu.com/view/84055.htm)。因此在这就说一下简单的配置经过。

本来想通过tomcat 管理界面来完成数据库连接池配置,结果到apache官网下面一个apache-tomcat-5.5.31-admin,下载下来怎么搞也出来了界面,把所有的异常提示都看了,也查了,依然没有解决问题,貌似网上那些写文章的人都是经过一些挫折后都顺利通过,可我这确实试了网上各种方法,依然无法解决。郁闷。。。有知道的告诉俺一声。 于是跳过了界面的配置,毕竟界面不过是一个人性化的工具,重点还是配置文件的编写。

要配置数据库连接池需要用到一个配置文件: context.xml,在tomcat的conf目录下的文件。这里需要说明一下,配置conf下的context.xml文件之后,以后由该tomcat启动的网站都将会使用数据库连接池来进行连接,如果你只是想当前项目使用,那么你需要把这个context.xml文件剪切到项目中的META-INFO里面下。

具体配置,在context.xml里面的<Content></Content>标签中间添加:

<Resource name="jdbc/drp1"
     auth="Container" type="javax.sql.DataSource"
     driverClassName="com.mysql.jdbc.Driver"
     maxIdle="20"
     maxWait="500"
     username="root"
     password="root"
     url="jdbc:mysql://192.168.1.100/drp1"
     maxActive="1000"
     removeAbandoned="true"
     removeAbandonedTimeout="60"
     logAbandoned="true"/>

比如我的是这样的:

<?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.
-->
<!-- The contents of this file will be loaded for each web application -->
<Context>

    <!-- Default set of monitored resources -->
    <WatchedResource>WEB-INF/web.xml</WatchedResource>

    <!-- <ResourceLink name="jdbc/drp1" global="jdbc/drp1" type="javax.sql.DataSource"/> -->
    <!-- Uncomment this to disable session persistence across Tomcat restarts -->
    <!--
    <Manager pathname="" />
    -->

    <Resource name="jdbc/drp1"
         auth="Container" type="javax.sql.DataSource"
         driverClassName="com.mysql.jdbc.Driver"
         maxIdle="20"
         maxWait="500"
         username="root"
         password="root"
         url="jdbc:mysql://192.168.1.100/drp1"
         maxActive="1000"
         removeAbandoned="true"
         removeAbandonedTimeout="60"
         logAbandoned="true"/>

    <!-- Uncomment this to enable Comet connection tacking (provides events
         on session expiration as well as webapp lifecycle) -->
    <!--
    <Valve className="org.apache.catalina.valves.CometConnectionManagerValve" />
    -->

</Context>

测试代码testDB.jsp:

<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<%@page import="java.sql.Connection"%>
<%@page import="javax.naming.Context"%>
<%@page import="javax.naming.InitialContext"%>
<%@page import="javax.sql.DataSource"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.ResultSet"%>
<%
   //连接池的获取
    Connection conn = null;
    ResultSet rs  =null;
    Statement stmt = null;
    // 初始化查找命名空间
    Context initContext = new InitialContext();
    // 找到DataSource
    DataSource ds = (DataSource) initContext.lookup("java:comp/env/jdbc/drp1");
    if(ds!=null){
        out.println("已经获得DataSource!");
        out.println("<br>");
        conn = ds.getConnection();
       try{
        stmt = conn.createStatement();
        String sql ="select * from t_user";
        rs = stmt.executeQuery(sql);
        out.println("以下是从数据库中读取出来的数据:<br>");
            while(rs.next()){
                out.println("<br>");
                out.println(rs.getString("user_id"));
            }
       }catch(Exception ex){
         ex.printStackTrace();
       }finally{
          //conn.close();
          rs.close();
          stmt.close();
       }
   }
%>

如果测试或者启动tomcat失败,可能是因为你没有把相应的包拷贝到tomcat的lib目录下:需要的jar有: commons-logging-x.x.x.jar(一些列文件) http://mirror.bjtu.edu.cn/apache/commons/logging/ ,commons-modeler-x.x.x.jar(一系列文件)http://mirror.bjtu.edu.cn/apache//commons/modeler/ ,要连接的数据库驱动,我这里是mysql 具体效果你可以把七宗的maxActive的值做一下修改,然后启动之后打开testDB页面,疯狂的刷新,如果发现没有出现错误,那你需要修改一下测试代码中关于conn.close这一块,你让它不关闭。这样的结果是你每次请求都会从连接池中拿出来一个连接,但是却不放回去,如果拿的数量达到了你设置的maxActive就会出现Timeout waiting for idle object异常。 因此在进行数据库方面的编程的时候要特别注意conn的操作,每次打开都要对应着关闭。养成良好的习惯。

补充一下,忘了配置web.xml文件了。在web.xml中需要添加<resource-ref></resource-ref> 标签:

<resource-ref>
    <description>DB Connection</description>
    <res-ref-name>jdbc/drp1</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
</resource-ref>

解释:为了让 JNDI 解析 java:comp/env/jdbc/drp1 引用,部署人员必须把 <resource-ref> 标签插入 web.xml 文件(Web 应用程序的部署描述符)。 <resource-ref> 标签的意思就是“这个组件依赖于外部资源”。

深入了解JNDI:http://www.ibm.com/developerworks/cn/java/j-jndi/index.html强力推荐

- from the5fire.com
----EOF-----

微信公众号:Python程序员杂谈

【上一篇】 java类加载器加载机制
【下一篇】 JNDI:如同胶水

其他分类: