Tomcat连接池

news/2024/5/19 0:21:17 标签: tomcat, thread, null, jvm, jdbc, 应用服务器
 Tomcat连接池的配置,官方文档,在此记录一下。

        1.MySQL
            1.1 Context configuration:
<Context path="/DBTest" docBase="DBTest"
        debug="5" reloadable="true" crossContext="true"<
        <Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource"
               maxActive="100" maxIdle="30" maxWait="10000"
               username="javauser" password="javadude" driverClassName="com.mysql.jdbc.Driver"
               url="jdbc:mysql://localhost:3306/javatest?autoReconnect=true"/<
</Context<
             1.2 web.xml configuration:
<resource-ref<
      <description<DB Connection</description<
      <res-ref-name<jdbc/TestDB</res-ref-name<
      <res-type<javax.sql.DataSource</res-type<
      <res-auth<Container</res-auth<     / /据说还可以是Application
  </resource-ref<                
            1.3 Test code 还可以在jsp中直接使用数据源
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %<
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %<
...
<sql:query var="rs" dataSource="jdbc/TestDB"<
        select id, foo, bar from testdata
</sql:query<
...
<c:forEach var="row" items="${rs.rows}"<
    Foo ${row.foo}<br/<
    Bar ${row.bar}<br/<
</c:forEach<

        2. Oracle
            2.1 Context configuration:
<Resource name="jdbc/myoracle" auth="Container"
              type="javax.sql.DataSource" driverClassName="oracle.jdbc.OracleDriver"
              url="jdbc:oracle:thin:@127.0.0.1:1521:mysid"
              username="scott" password="tiger" maxActive="20" maxIdle="10"
              maxWait="-1"/<
            2.2 web.xml configuration:
<resource-ref<
    <description<Oracle Datasource example</description<
    <res-ref-name<jdbc/myoracle</res-ref-name<
    <res-type<javax.sql.DataSource</res-type<
    <res-auth<Container</res-auth<
</resource-ref<
            2.3 Test code
Context initContext = new InitialContext();
Context envContext  = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/myoracle");
Connection conn = ds.getConnection();
//etc.

        把配置放在Context 标签对里面只对当前应用有效,要想对整个TomCat有效,可以放到GlobalNamingResources里面。(强烈申明,此种情况好像是5.0版本前是这样设置的,5.5和6.0版本如果要是全局的话,就在Tomcat_Home\conf下的context.xml文件直接配置)

        Tomcat6的连接池设置有一些不一样,在server.xml中文配置老是报Cannot create JDBC driver of class '' for connect URL 'null' 的错误,需要将Tomcat6安装路径的conf目录下的context.xml文件拷贝到自己应用的META-INF目录下,并添加<Resource /<的配置。

        连接池使用的问题,官方说明如下,水平太次,不敢翻译,抄录之:
Intermittent dB Connection Failures:
       
Tomcat runs within a JVM. The JVM periodically performs garbage collection (GC) to remove java objects which are no longer being used. When the JVM performs GC execution of code within Tomcat freezes. If the maximum time configured for establishment of a dB connection is less than the amount of time garbage collection took you can get a db conneciton failure. 
        To collect data on how long garbage collection is taking add the -verbose:gc argument to your CATALINA_OPTS environment variable when starting Tomcat. When verbose gc is enabled your $CATALINA_BASE/logs/catalina.out log file will include data for every garbage collection including how long it took.
        When your JVM is tuned correctly 99% of the time a GC will take less than one second. The remainder will only take a few seconds. Rarely, if ever should a GC take more than 10 seconds.
        Make sure that the db connection timeout is set to 10-15 seconds. For the DBCP you set this using the parameter maxWait.
Random Connection Closed Exceptions:
        These can occur when one request gets a db connection from the connection pool and closes it twice. When using a connection pool, closing the connection just returns it to the pool for reuse by another request, it doesn't close the connection. And Tomcat uses multiple threads to handle concurrent requests. Here is an example of the sequence of events which could cause this error in Tomcat:
----------------------------------------------------------------------------------------------
  Request 1 running in Thread 1 gets a db connection.
  Request 1 closes the db connection.
  The JVM switches the running thread to Thread 2
  Request 2 running in Thread 2 gets a db connection
  (the same db connection just closed by Request 1).
  The JVM switches the running thread back to Thread 1
  Request 1 closes the db connection a second time in a finally block.
  The JVM switches the running thread back to Thread 2
  Request 2 Thread 2 tries to use the db connection but fails
  because Request 1 closed it.
----------------------------------------------------------------------------------------------
Here is an example of properly written code to use a db connection obtained from a connection pool:
Connection conn = null;
  Statement stmt = null;  // Or PreparedStatement if needed
  ResultSet rs = null;
  try {
    conn = ... get connection from connection pool ...
    stmt = conn.createStatement("select ...");
    rs = stmt.executeQuery();
    ... iterate through the result set ...
    rs.close();
    rs = null;
    stmt.close();
    stmt = null;
    conn.close(); // Return to connection pool
    conn = null;  // Make sure we don't close it twice
  } catch (SQLException e) {
    ... deal with errors ...
  } finally {
    // Always make sure result sets and statements are closed,
    // and the connection is returned to the pool
    if (rs != null) {
      try { rs.close(); } catch (SQLException e) { ; }
      rs = null;    //方便gc进行垃圾回收
    }
    if (stmt != null) {
      try { stmt.close(); } catch (SQLException e) { ; }
      stmt = null;
    }
    if (conn != null) {
      try { conn.close(); } catch (SQLException e) { ; }
      conn = null;
    }
  }

在spring中使用TomCat已配好的数据源:

  1. <!-- 通过JNDI 使用应用服务器 的Connection Pool--<  
  2. <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"<  
  3.     <property name="jndiName" value="java:comp/env/jdbc/coral"/<  
  4. </bean< 
 

http://www.niftyadmin.cn/n/1760260.html

相关文章

线性代数---矩阵---特征值和特征向量

转自&#xff1a;https://jingyan.baidu.com/article/27fa7326afb4c146f8271ff3.html 一、特征值和特征向量的定义 首先让我们来了解一下特征值和特征向量的定义&#xff0c;如下&#xff1a; 特征子空间基本定义&#xff0c;如下&#xff1a; 二、特征值和特征向量的求法三 、…

阿里云搭建nginx + uWSGI 实现 django 项目

系统版本 CentOS/7 64位 1.安装使用python3 创建python3目录 sudo mkdir /usr/local/python3 进入python3目录 cd /usr/local/python3 下载python3压缩包 sudo wget https://www.python.org/ftp/python/3.6.1/Python-3.6.1.tgz 解压 tar -zxvf Python-3.6.1.tgz 编译前需要多个…

MyEclipse中取消js的语法错误提示

MyEclipse 中对 jquey.js 里的语句提示错误了&#xff0c;这是由于MyEclipse对其语法要求相当严格所造成的&#xff0c;而这些文件本身是可以运行并没有什么错误的&#xff0c;在你实际应用部署中并无影响。可以不用管它&#xff0c;照样部署运行。可是一直有这样的错误提示总是…

使用AOP实现日志处理

需求 希望对于每一个请求&#xff0c;都能在日志中记录 ① 请求的url ② 访问者ip ③ 调用的方法 ④ 参数 ⑤ 返回内容 实现 1. 配置日志 默认日志 Logback&#xff1a; 默认情况下&#xff0c;Spring Boot会用Logback来记录日志&#xff0c;并用INFO级别输出到控制台。在运…

2018杭州初雪

上面这两张拍摄于浙大玉泉校区 下面这一张拍摄于西湖 此情此景记于此处&#xff0c;也许若干年后&#xff0c;我也会怀念这段时光吧。也许吧&#xff0c;谁知道呢&#xff1f; 转载于:https://www.cnblogs.com/yanxingang/p/10099790.html

用户故事与敏捷方法笔记 --- 估算与计划

估算用户故事 故事点&#xff1a;代表时间的模糊单位&#xff0c;叫NUT&#xff08;Nebulous Units of Time&#xff09;。 故事点的特性是团队可以定义自己认为合适的故事点大小。它可以是一个理想日的工作&#xff0c;也可以是一个故事复杂度的测量。因此不同的团队&#xff…

上下界通配符

转载 <? extends T>和<? super T>是Java泛型中的“通配符&#xff08;Wildcards&#xff09;”和“边界&#xff08;Bounds&#xff09;”的概念。 ① <? extends T>&#xff1a;是指 “上界通配符&#xff08;Upper Bounds Wildcards&#xff09;” ②…

中文到unicode编码转换

代码&#xff1a;/*** 中文到unicode编码的转换*/public class UnicodeTest {public static void main(String[] args) {String cn "怀念外婆屋后的柚子树";System.out.println(cnToUnicode(cn));// 字符串 : \u5f00\u59cb\u4efb\u52a1 &#xff0c;由于 \ 在java里…