`
fengyong0912
  • 浏览: 103906 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

TOMCATE 数据库连接池

    博客分类:
  • JAVA
阅读更多

一.在tomcat_home\common\lib下放入jdbc的驱动程序,额外说一下,如果是使用sql server的话,有至少两个驱动可以选择,一个是微软提供的,另一个是 jtds,比微软的要好很多,推荐使用

二.配置文件,tomcat 不同的版本配置文件略有不同,下面以tomcat5..5.*为例。

三.如果配置不正确会出现javax.naming.NameNotFoundException: Name is not bound in this Context 错误
方式一、全局数据库连接池
1、通过管理界面配置连接池,或者直接在tomcat\conf\server.xml的GlobalNamingResources中增加
<Resource name="jdbc/mydb" type="javax.sql.DataSource" password="mypwd" driverClassName="com.microsoft.jdbc.sqlserver.SQLServerDriver" maxIdle="2" maxWait="5000" validationQuery="select 1" username="sa" url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=mydb" maxActive="4"/>
2、在tomcat\webapps\myapp\META-INF\context.xml的Context中增加:
<ResourceLink global="jdbc/mydb" name="jdbc/mydb" type="javax.sql.DataSource"/>
这样就可以了。
方式二、全局数据库连接池
1、同上
2、在tomcat\conf\context.xml的Context中增加:
<ResourceLink global="jdbc/mydb" name="jdbc/mydb" type="javax.sql.DataSource"/>
方式三、局部数据库连接池
只需在tomcat\webapps\myapps\META-INF\context.xml的Context中增加:
<Resource name="jdbc/mydb" type="javax.sql.DataSource" password="mypwd" driverClassName="com.microsoft.jdbc.sqlserver.SQLServerDriver" maxIdle="2" maxWait="5000" validationQuery="select 1" username="sa" url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=mydb" maxActive="4"/>
参数说明:
driveClassName:JDBC驱动类的完整的名称;
maxActive:同时能够从连接池中被分配的可用实例的最大数;
maxIdle:可以同时闲置在连接池中的连接的最大数;
maxWait:最大超时时间,以毫秒计;
password:用户密码;
url:到JDBC的URL连接;
user:用户名称;
validationQuery:用来查询池中空闲的连接。
以上三种方式在tomcat 5.5.4下都可以。另外,sql server的jdbc driver是从微软网站上下载的sql server jdbc (sp3)。

下面 分别举tomcat5.0 和tomcat 5.5   配置文件 的例子(将此配置文件置于Tomcat \conf\Catalina\localhost 下)

tomcat5.0

<Resource name="jdbc/test" auth="Container" type="javax.sql.DataSource"/>
     <ResourceParams name="jdbc/test">
         <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>sa</value>
         </parameter>
         <parameter>
             <name>password</name>
             <value>test</value>
         </parameter>
         <!-- Class name for JDBC driver -->
         <parameter>
             <name>driverClassName</name>
             <value>net.sourceforge.jtds.jdbc.Driver</value>
         </parameter>
         <!-- Autocommit setting.   This setting is required to make
              Hibernate work.   Or you can remove calls to commit(). -->
         <parameter>
             <name>defaultAutoCommit</name>
             <value>true</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:jtds:sqlserver://url/filedb;charset=gb2312;autoReconnect=true</value>
         </parameter>
         <!-- Recover abandoned connections -->
         <parameter>
             <name>removeAbandoned</name>
             <value>true</value>
         </parameter>
         <!-- Set the number of seconds a dB connection has been idle
              before it is considered abandoned.
              -->
         <parameter>
             <name>removeAbandonedTimeout</name>
             <value>60</value>
         </parameter>
         <!-- Log a stack trace of the code which abandoned the dB
              connection resources.
              -->
         <parameter>
             <name>logAbandoned</name>
             <value>true</value>
         </parameter>
     </ResourceParams>

tomcat 5.5

   <Resource name="jdbc/test" auth="Container" type="javax.sql.DataSource"
               maxActive="100" maxIdle="30" maxWait="10000"
               driverClassName="oracle.jdbc.driver.OracleDriver"
               username="test" password="test"
               url="jdbc:oracle:thin:@url:1521:dcdb"
               defaultAutoCommit="true" removeAbandoned="true"
               removeAbandonedTimeout="60" logAbandoned="true"/>

 

 

 

 

1.将数据库驱动程序的JAR文件放在Tomcat的 common/lib 中;

2.在TOMCATE中的server.xml中设置数据源,以MySQL数据库为例,如下:
在<GlobalNamingResources> </GlobalNamingResources>节点中加入,
        <Resource
        name="jdbc/WSPool"
        type="javax.sql.DataSource"
        password="root"
        driverClassName="com.mysql.jdbc.Driver"
        maxIdle="2"
        maxWait="5000"
        username="root"
        url="jdbc:mysql://127.0.0.1:3306/test"
        maxActive="4"/>
     属性说明:name,数据源名称,通常取”jdbc/XXX”的格式;
              type,”javax.sql.DataSource”;
              password,数据库用户密码;
              driveClassName,数据库驱动;
              maxIdle,最大空闲数,数据库连接的最大空闲时间。超过空闲时间,数据库连
                       接将被标记为不可用,然后被释放。设为0表示无限制。
              MaxActive,连接池的最大数据库连接数。设为0表示无限制。
              maxWait ,最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示
                       无限制。

3.在个人的web应用程序的web.xml中设置数据源参考,如下:
    在<web-app></web-app>节点中加入,
    <resource-ref>
      <description>DB Connection Pool</description>
      <res-ref-name>jdbc/WSPool</res-ref-name>
      <res-type>javax.sql.DataSource</res-type>
      <res-auth>Container</res-auth>
      <res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
    子节点说明: description,描述信息;
                 res-ref-name,参考数据源名字,同上一步的属性name;
                 res-type,资源类型,”javax.sql.DataSource”;
                 res-auth,”Container”;
                 res-sharing-scope,”Shareable”;

4.在TOMCATE中的web应用程序的context.xml中设置数据源链接,如下:
    在<Context></Context>节点中加入,
    <ResourceLink
     name="jdbc/WSPool"
     type="javax.sql.DataSource"
     global="jdbc/WSPool"/>
     属性说明:name,同第2步和第3步的属性name值,和子节点res-ref-name值;
               type,同样取”javax.sql.DataSource”;
               global,同name值。

至此,设置完成,下面是如何使用数据库连接池。
1.建立一个连接池类,DBPool.java,用来创建连接池,代码如下:
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class DBPool {
      private static DataSource pool;
      static {
           Context env = null;
            try {
                env = (Context) new InitialContext().lookup("java:comp/env");
                pool = (DataSource)env.lookup("jdbc/WSPool");
                if(pool==null)
                    System.err.println("'DBPool' is an unknown DataSource");
                 } catch(NamingException ne) {
                    ne.printStackTrace();
            }
        }
      public static DataSource getPool() {
          return pool;
      }
}

2.在要用到数据库操作的类或jsp页面中,用DBPool.getPool().getConnection(),获得一个Connection对象,就可以进行数据库操作,最后别忘了对Connection对象调用close()方法,注意:这里不会关闭这个Connection,而是将这个Connection放回数据库连接池。

 

 

 

1)启动Tomcat服务器,打开浏览器,输入http://localhost:8080/admin(其中localhost是名称服务器或称为主机),
进入管理界面的登陆页面,这时候请输入原来安装时要求输入的用户名和密码,登陆到管理界面,

2)选择Resources-Data sources进入配置数据源界面,选择
 Data Source Actions ->选择Create New Data Source,进入配置详细信息界面
主要内容例如下:
JNDI Name:   ->jdbc/mysql
Data Source URL  ->jdbc:mysql://localhost:3306/test
JDBC Driver Class-> org.gjt.mm.mysql.Driver
3)修改\conf\Catalina\localhost目录下建立一个xml文件,名称为你所发布的web应用的名称.xml,(如testpool.xml)打开添加内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<Context>
 <Resource
      name="jdbc/mysql"
      type="javax.sql.DataSource"
      password="123456"
      driverClassName="org.gjt.mm.mysql.Driver"
      maxIdle="2"
      maxWait="50"
      username="root"
      url="jdbc:mysql://localhost:3306/test"
      maxActive="4"/>

</Context>
内容同conf/server.xml中<GlobalNamingResources>
 <Resource
      name="jdbc/mysql"
      type="javax.sql.DataSource"
      password="123456"
      driverClassName="org.gjt.mm.mysql.Driver"
      maxIdle="2"
      maxWait="50"
      username="root"
      url="jdbc:mysql://localhost:3306/test"
      maxActive="4"/>
  </GlobalNamingResources>

少了这一步会报错:Cannot create JDBC driver of class '' for connect URL 'null'
4)修改web.xml

打开%TOMCAT_HOME%\conf\web.xml或yourwebapp/web-inf/web.xml,添加以下内容:
    <resource-ref>
    <description>DB Connection</description>
    <res-ref-name>jdbc/mysql</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
    </resource-ref>
    注意res-ref-name填写的内容要与在上文提到的JNDI Name名称一致。
 到这里,配置工作就基本完成了!

5)引用JNDI时用"java:comp/env/jdbc/mysql";
建立文件测试 test.jsp:
<%@page contentType="text/html;charset=utf-8" %>
<%@page import="java.sql.*" %>
<%@page import="javax.sql.*" %>
<%@page import="javax.naming.*" %>
<html>
<head>
<title>Tomcat连接池测试</title>
</head>
<body>
<%
  Context ctx=new InitialContext();
  Connection conn=null;
  DataSource ds=(DataSource)ctx.lookup("java:comp/env/jdbc/mysql");
  conn=ds.getConnection();
  Statement stmt=conn.createStatement(ResultSet.CONCUR_READ_ONLY,ResultSet.CONCUR_UPDATABLE);
  ResultSet rs=stmt.executeQuery("select * from testexample");
  while(rs.next()){
  out.println(rs.getInt(1));
  out.println(rs.getString(2));
  out.println(rs.getString(3));
  }
  out.println("数据库操作成功!");
  rs.close();
  stmt.close();
  conn.close();
   
 %>
</body>
</html>

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics