配置tomcat7自带jdbc连接池、简单好用!

来源:互联网 发布:as3.0 外部js接口 编辑:程序博客网 时间:2024/06/06 13:52

一直都很想做一个连接池,上网查资料时偶然发现tomcat有自己现成的连接池,但是tomcat7和之前版本的连接池不大一样,区别请参考tomcat官方连接池文档英文好的同学可以参考这里,然后写一遍之后发现挺简单的,实现步骤如下:

1.在MyEclips中新建一个javaweb项目TomcatPool

2.配置jdbc数据源(datasource),这里顺便说下数据源的由来:

     在Java开发中,使用JDBC操作数据库的四个步骤如下:

      ①加载数据库驱动程序(Class.forName("数据库驱动类");)
      ②连接数据库(Connection con  = DriverManager.getConnection();)
      ③操作数据库(PreparedStatement stat = con.prepareStatement(sql);stat.executeQuery();)
      ④关闭数据库,释放连接(con.close();)
        也就是说,所有的用户都需要经过此四步进行操作,但是这四步之中有三步(①加载数据库驱动程序、②连接数据库、④关闭数据库,释放连接)对所有人都是一样的,而所有人只有在操作数据库上是不一样,那么这就造成了性能的损耗。
        那么最好的做法是,准备出一个空间,此空间里专门保存着全部的数据库连接,以后用户用数据库操作的时候不用再重新加载驱动、连接数据库之类的,而直接从此空间中取走连接,关闭的时候直接把连接放回到此空间之中。
    那么此空间就可以称为连接池(保存所有的数据库连接),但是如果要想实现此空间的话,则必须有一个问题要考虑?
      1、 如果没有任何一个用户使用连接,那么那么应该维持一定数量的连接,等待用户使用。
      2、 如果连接已经满了,则必须打开新的连接,供更多用户使用。
      3、 如果一个服务器就只能有100个连接,那么如果有第101个人过来呢?应该等待其他用户释放连接
      4、 如果一个用户等待时间太长了,则应该告诉用户,操作是失败的。
          如果直接用程序实现以上功能,则会比较麻烦,所以在Tomcat 4.1.27之后,在服务器上就直接增加了数据源的配置选项, 直接在服务器上配置好数据源连接池即可。在J2EE服务器上保存着一个数据库的多个连接。每一个连接通过DataSource可 以找到。DataSource被绑定在了JNDI树上(为每一个DataSource提供一个名字)客户端通过名称找到在JNDI树上绑定的 DataSource,再由DataSource找到一个连接。
     数据源可以给项目单独配置,也可以全局配置:

     单独配置:在项目META-INF下新建context.xml,内容如下:
<?xml version="1.0" encoding="UTF-8"?><Context><Resource name="jdbc/Mobile"          auth="Container"          type="javax.sql.DataSource"          factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"          testWhileIdle="true"          testOnBorrow="true"          testOnReturn="false"          validationQuery="SELECT 1"          validationInterval="30000"          timeBetweenEvictionRunsMillis="30000"          maxActive="100"          minIdle="10"          maxWait="10000"          initialSize="10"          removeAbandonedTimeout="60"          removeAbandoned="true"          logAbandoned="false"          minEvictableIdleTimeMillis="30000"          jmxEnabled="true"          fairQueue="true"          jdbcInterceptors="org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;            org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer"          username="root"          password='root'          driverClassName="com.mysql.jdbc.Driver"          url="jdbc:mysql://127.0.0.1:3306/hsdb?useUnicode=true&characterEncoding=utf-8&autoReconnect=true"/></Context>
   
 全局设置:在tomcat中conf目录下的context.xml文件 context节点下添加上面的resource。
<?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>    <!-- Uncomment this to disable session persistence across Tomcat restarts -->    <Manager pathname="" />    <!-- Uncomment this to enable Comet connection tacking (provides events         on session expiration as well as webapp lifecycle) -->    <!--    <Valve className="org.apache.catalina.valves.CometConnectionManagerValve" />    --><Resource name="jdbc/Mobile"          auth="Container"          type="javax.sql.DataSource"          factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"          testWhileIdle="true"          testOnBorrow="true"          testOnReturn="false"          validationQuery="SELECT 1"          validationInterval="30000"          timeBetweenEvictionRunsMillis="30000"          maxActive="100"          minIdle="10"          maxWait="10000"          initialSize="10"          removeAbandonedTimeout="60"          removeAbandoned="true"          logAbandoned="false"          minEvictableIdleTimeMillis="30000"          jmxEnabled="true"          fairQueue="true"          jdbcInterceptors="org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;            org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer"          username="root"          password='root'          driverClassName="com.mysql.jdbc.Driver"          url="jdbc:mysql://127.0.0.1:3306/hsdb?useUnicode=true&characterEncoding=utf-8&autoReconnect=true"/>//连接的数据库名</Context>
我们这里设置成单项目配置:

3.将tomcat lib中的tomcat-jdbc.jar包和mysql的jar包放到TomcatPool的lib下。

4.在web.xml中添加对数据源的引用。
<resource-ref>    <description>DB Connection</description>    <res-ref-name><span style="color:#ff0000;">jdbc/Mobile<</span>/res-ref-name>    <res-type>javax.sql.DataSource</res-type>    <res-auth>Container</res-auth></resource-ref>
5.在代码中获取jdbc数据源和连接:

package com.hs.db;import java.sql.Connection;import java.sql.SQLException;import java.util.concurrent.ExecutionException;import java.util.concurrent.Future;import javax.naming.Context;import javax.naming.InitialContext;import javax.naming.NamingException;import org.apache.tomcat.jdbc.pool.DataSource;public class TestDB {private static DataSource datasource;/** * get the jdbc datasource *  * @return datasource * @throws NamingException */private static DataSource getDataSource() throws NamingException{if(datasource == null){Context initContext = new InitialContext();Context evenContext = (Context)initContext.lookup("java:/comp/env");//这个里面的参数是固定的//java:comp/env/是一个J2EE环境的定义,说白了就是代表当前J2EE应用的环境datasource = (DataSource) evenContext.lookup("jdbc/Mobile");//上面方法的参数是context中resource配置的name值}return datasource;}/** * get the java.sql.connection * @return connection */private static Connection getConnection(){Connection conn = null;try {datasource = getDataSource();Future<Connection> future = datasource.getConnectionAsync();//异步获取连接while (!future.isDone()) {System.out.println("Connection is not yet available. Do some background work");try {Thread.sleep(100);} catch (InterruptedException e) {Thread.currentThread().interrupt();}}conn = future.get();// should return instantly} catch (NamingException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();} catch (InterruptedException e) {e.printStackTrace();} catch (ExecutionException e) {e.printStackTrace();}return conn;}}
6.测试,新建servlet文件TestServlet:
package com.hs.servlet;import java.io.IOException;import java.io.PrintWriter;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.hs.db.TestDB;@WebServlet(value = "/test.do")public class TestServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {doPost(req, resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {PrintWriter out = resp.getWriter();Connection conn = null;PreparedStatement ps = null;ResultSet rs = null;try {conn = TestDB.getConnection();String sql = "select * from tb_test where id = 1";ps = conn.prepareStatement(sql);rs = ps.executeQuery();while (rs.next()) {out.print(rs.getInt(1) + "----" + rs.getString(2) + "----"+ rs.getInt(3) + "----" + rs.getString(4) + "----"+ rs.getString(5));//将查询的结果输出到页面out.flush();out.close();}} catch (SQLException e) {e.printStackTrace();} finally {try {rs.close();ps.close();conn.close();} catch (SQLException e) {e.printStackTrace();}}}}
往hsdb(resource中配置的数据库名)下的tb_test表中添加一条数据:
访问test.do servlet会通过连接池获取连接进行查找,结果如下:

到此配置完成!





0 0
原创粉丝点击