设为首页 收藏本站
查看: 368|回复: 0

[经验分享] 配置Tomcat 4.1.29的连接池

[复制链接]

尚未签到

发表于 2017-2-5 08:54:40 | 显示全部楼层 |阅读模式
  配置Tomcat 4.1.29的连接池
Tomcat 4.1.29是目前的最高稳定版本,下面介绍一下它的连接池配置方法。
1)    连接池配置(Database Connection Pool (DBCP) Configurations)
DBCP使用的是Jakarta-Commons Database Connection Pool 要使用连接池需要如下的组件即jar文件。
Jakarta-Commons DBCP 1.1 对应commons-dbcp-1.1.jar。
Jakarta-Commons Collections 2.0 对应commons-collections.jar。
Jakarta-Commons Pool 1.1 对应commons-pool-1.1.jar。
这三个jar文件要与你的JDBC驱动程序一起放到【TOMCAT_HOME】\common\lib目录下以便让tomcat和你的web应用都能够找到。
注:这三个jar文件是默认存在与【TOMCAT_HOME】\common\lib下的。
需要注意的地方:第三方的驱动程序或者其他类只能以*.jar的形式放到Tomcat的common\lib目录中,因为Tomcat只把*.jar文件加到CLASSPATH中。
不要把上诉三个文件放到WEB-INF/lib或者其他地方因为这样会引起混淆。
2)    通过配置阻止连接池漏洞
数据库连接池创建和管理连接池中建立好的数据库连接,循环使用这些连接以得到更好的效率。这样比始终为一个用户保持一个连接和为用户的请求频繁的建立和销毁数据库连接要高效的多。
这样就有一个问题出现了,一个Web应用程序必须显示的释放ResultSet,Statement和Connection。如果在关闭这些资源的过程中失败将导致这些资源永远不在可用,这就是所谓的连接池漏洞。这个漏洞最终会导致连接池中所有的连接不可用。
通过配置Jakarta Common DBCP可以跟踪和恢复那些被遗弃的数据库连接。
以下是一系列相关配置:
    通过配置DBCP数据源中的参数removeAbandoned来保证删除被遗弃的连接使其可以被重新利用。
为ResourceParams(见下文的数据源配置)标签添加参数removeAbandoned
<parameter>
<name>removeAbandoned</name>
<value>true</value>
</parameter>
通过这样配置的以后当连接池中的有效连接接近用完时DBCP将试图恢复和重用被遗弃的连接。这个参数的值默认是false。
    通过设置removeAbandonedTimeout来设置被遗弃的连接的超时的时间,即当一个连接连接被遗弃的时间超过设置的时间时那么它会自动转换成可利用的连接。
    <parameter>
     <name>removeAbandonedTimeout</name>
     <value>60</value>
     </parameter>
    默认的超时时间是300秒。
    设置logAbandoned参数,这个参数的用处我没能够理解它的意义所以提供原文供大家参考。
The logAbandoned parameter can be set to true if you want DBCP to log a stack trace of the code which abandoned the dB connection resources。
<parameter>
<name>logAbandoned</name>
<value>true</value>
</parameter>
这个参数默认为false。
3)    下面以MySQL为例演示Tomcat数据库连接池的配置
    MySQL的版本以及对应的JDBC驱动程序
MySQL 3.23.47, MySQL 3.23.47 using InnoDB, MySQL 4.0.1alpha对应的驱动为mm.mysql 2.0.14 (JDBC Driver)。
    在MySQL中创建供测试的数据库,表结构以及数据


mysql> create database javatest;
mysql> use javatest;
mysql> create table testdata (
    ->   id int not null auto_increment primary key,
    ->   foo varchar(25), 
    ->   bar int);
    mysql> insert into testdata values(null, 'hello', 12345);
Query OK, 1 row affected (0.00 sec)
mysql> select * from testdata;
+----+-------+-------+
| ID | FOO   | BAR   |
+----+-------+-------+
|  1 | hello | 12345 |
+----+-------+-------+
1 row in set (0.00 sec)
  
    要注意的是登录的mysql用户要有创建数据库的权限还有注意要设置密码我用的是root^_^。
    配置Tomcat的server.xml文件
配置【TOMCAT_HOME】\common\lib下的server.xml文件,在</host>标签之前加入以下内容以添加JNDI数据源:


xml 代码


  • <Context path="/DBTest" docBase="DBTest"        debug="5" reloadable="true" crossContext="true">     
  • <Logger className="org.apache.catalina.logger.FileLogger"             prefix="localhost_DBTest_log." suffix=".txt"             timestamp="true"/>     
  • <Resource name="jdbc/TestDB"               auth="Container"               type="javax.sql.DataSource"/>     
  • <ResourceParams name="jdbc/TestDB">       
  • <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>javauser</value>       
  • </parameter>       
  • <parameter>        
  • <name>password</name>        
  • <value>javadude</value>       
  • </parameter>       
  • <!-- Class name for mm.mysql JDBC driver -->       
  • <parameter>          
  • <name>driverClassName</name>          
  • <value>org.gjt.mm.mysql.Driver</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:mysql://localhost:3306/javatest?autoReconnect=true</value>       
  • </parameter>     
  • </ResourceParams>  
  • </Context>  


    配置Web应用程序的web.xml文件
xml 代码

  • <?xml version="1.0" encoding="ISO-8859-1"?>       
  • <!DOCTYPE web-app PUBLIC    "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"    "http://java.sun.com/dtd/web-app_2_3.dtd">  
  • <web-app>     
  • <description>MySQL Test App</description>     
  • <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>     
  • </resource-ref>  
  • </web-app>  




  
    测试代码
测试代码包括一个JSP文件和一个Java类。代码如下:


xml 代码



    • <html>    
    •   <head>    
    •     <title>DB Test</title>    
    •   </head>    
    •   <body>    
    •   <%    
    •     foo.DBTest tst = new foo.DBTest();    
    •     tst.init();    
    •   %>    
    •   <h2>Results</h2>    
    •     Foo <%= tst.getFoo() %><br>    
    •     Bar <%= tst.getBar() %>    
    •   </body>    
    • </html>   

    package
     foo;

  •  
  • import javax.naming.*;
  • import javax.sql.*;
  • import java.sql.*;
  •  
  • public class DBTest {
  •  
  •   String foo = "Not Connected";
  •   int bar = -1;
  •     
  •   public void init() {
  •     try{
  •       Context ctx = new InitialContext();
  •       if(ctx == null ) 
  •           throw new Exception("Boom - No Context");
  •       DataSource ds = 
  •             (DataSource)ctx.lookup(
  •                "java:comp/env/jdbc/TestDB");
  •       if (ds != null) {
  •         Connection conn = ds.getConnection();     
  •         if(conn != null)  {
  •             foo = "Got Connection "+conn.toString();
  •             Statement stmt = conn.createStatement();
  •             ResultSet rst = 
  •                 stmt.executeQuery(
  •                   "select id, foo, bar from testdata");
  •             if(rst.next()) {
  •                foo=rst.getString(2);
  •                bar=rst.getInt(3);
  •             }
  •             conn.close();
  •         }
  •       }
  •     }catch(Exception e) {
  •       e.printStackTrace();
  •     }
  •  }
  •  public String getFoo() { return foo; }
  •  public int getBar() { return bar;}
  • }


  
最后在Tomcat的webapps目录下建立DBTest然后将应用程序文件拷贝到这个目录下即可。
    重新启动Tomcat在浏览器上http://localhost:8080/DBTest/test.jsp即可看到结果。
Results
Foo hello
Bar 12345
4)    一些常见的问题
    由于垃圾收集器的运行而导致连接超时
Tomcat是运行在JVM中的,JVM要周期性的执行GC(垃圾收集器)来清除不再被引用的Java对象。在GC运行时Tomcat将会冻结,如果在设置连接池中的连接的最大等待时间(MaxWait)小于GC的运行时间的话那么你很可能在使用数据库连接时失败。推荐将连接的超时时间设置成10到15秒。
注意连接的超时时间与被遗弃的连接的超时时间的区别。
    重复关闭连接引发的异常
这种情况发生在当响应一个客户的请求时从数据库连接池里取得了连接但是关闭了两次。使用连接池中的连接与使用直接与数据库建立的连接是不一样的,连接池中的连接在释放时只是将连接返回到连接池而不是释放连接的资源。Tomcat使用多线程来处理并发的请求,以下实例演示了一个在Tomcat中可以导致出错的过程:
请求A在线程A中运行并从连接池中得到一个连接
请求A关闭了这个连接
JVM转到线程B
请求B在线程B中运行并取得一个连接(这个连接是请求A刚刚返回的那个)
JVM转到线程A
请求A在finally块中又一次关闭连接(因为第一次没有设置连接引用为null)
JVM转到线程B
请求B试图使用得到的连接但连接已经被请求A返回到了连接池中所以请求B的操作失败
以下是一段公认的恰当的代码可以避免以上的问题



  •   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;
  •     }
  •     if (stmt != null) {
  •       try { stmt.close(); } catch (SQLException e) { ; }
  •       stmt = null;
  •     }
  •     if (conn != null) {
  •       try { conn.close(); } catch (SQLException e) { ; }
  •       conn = null;
  •     }
  •   }


  
我个人认为以上的代码非常的安全,不过try块中释放资源的代码好像可以省略,不知到大家怎么看^_^
如果翻译和理解的有错误,欢迎大家批评指教^_^
来源于javaResearch

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-337613-1-1.html 上篇帖子: tomcat 下jsp乱码的原因分析(上) 下篇帖子: 用Solaris 10的SMF配置Tomcat为自动启动
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表