posts - 19, comments - 53, trackbacks - 0, articles - 283
            BlogJava :: 首頁(yè) :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理

          DBCP連接池----Tomcat

          Posted on 2009-06-27 00:26 Gavin.lee 閱讀(2227) 評(píng)論(0)  編輯  收藏 所屬分類(lèi): JDBC
          api:http://egee-jra1-integration.web.cern.ch/egee-jra1-integration/repository/commons-dbcp/1.1/share/docs/apidocs/index.html  
          jar包&源碼:http://www.jdocs.com/dbcp/1.2.1/org/apache/commons/dbcp/BasicDataSource.html
          對(duì)于DBCP連接池的使用:

          1.要在tomcat下的conf包中的server.xml中加入數(shù)據(jù)庫(kù)連接池配置信息:

          a.在<Host>標(biāo)簽下加入

           <Context path="/myweb" docBase="D:"apache-tomcat-6.0.18"webapps"myweb" > 

           <Resource auth="Container" name="jdbc/jlndb" type="javax.sql.DataSource"

              factory="org.apache.commons.dbcp.BasicDataSourceFactory" 

              driverClassName="oracle.jdbc.OracleDriver"     

              url="jdbc:oracle:thin:@localhost:1521:JLNDB" 

              username="db" 

              password="db" 

              maxActive="10000" 

              maxIdle="10000" 

              maxWait="10000"  

              removeAbandoned="true" 

              removeAbandonedTimeOut="10" 

              logAbandoned="true"/>

             </Context>

          注釋?zhuān)?/span>

          path指定訪(fǎng)問(wèn)Web應(yīng)用的URL入口,注意/myweb,而不是myweb,必須有/。

          docBase:表示的項(xiàng)目的具體路徑。

          < Resource >元素為JNDI,lookup是要查找的資源,

          name:表示JNDIlookup是輸入的資源名。

          auth:是連接池管理權(quán)屬性,Container表示容器管理。

          name:表示你的連接池的名稱(chēng)也就是你要訪(fǎng)問(wèn)連接池的地址。

          type:是對(duì)象的類(lèi)型。

          driverClassName:是數(shù)據(jù)庫(kù)驅(qū)動(dòng)的名稱(chēng)。

          url:是數(shù)據(jù)庫(kù)的地址。

          username:是登陸數(shù)據(jù)庫(kù)的用戶(hù)名。

          password:是登陸數(shù)據(jù)庫(kù)的密碼。

          MaxActive:連接池的最大數(shù)據(jù)庫(kù)連接數(shù)。設(shè)為0表示無(wú)限制。

          maxIdle:最大空閑數(shù),數(shù)據(jù)庫(kù)連接的最大空閑時(shí)間。超過(guò)空閑時(shí)間,數(shù)據(jù)庫(kù)連接將被標(biāo)記為不可用,然后被釋放。設(shè)為0表示無(wú)限制。

          maxWait :最大建立連接等待時(shí)間。如果超過(guò)此時(shí)間將接到異常。設(shè)為-1表示無(wú)限制。

          removeAbandoned:是否自我中斷,默認(rèn)是 false 。

          removeAbandonedTimeout:幾秒后數(shù)據(jù)連接會(huì)自動(dòng)斷開(kāi),在removeAbandonedtrue,提供該值。

          logAbandoned:是否記錄中斷事件, 默認(rèn)為 false。

          注意:

          其中factory="org.apache.commons.dbcp.BasicDataSourceFactory" 也可以配置

          factory="org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory" 

          *maxActive:最大連接數(shù)據(jù)庫(kù)連接數(shù),設(shè) 0 為沒(méi)有限制

          *maxIdle:最大等待連接中的數(shù)量,設(shè) 0 為沒(méi)有限制

          *maxWait:最大等待毫秒數(shù), 單位為 ms, 超過(guò)時(shí)間會(huì)出錯(cuò)誤信息

          b.web.xml中加入配置信息:

          數(shù)據(jù)庫(kù)資源映射信息

           <resource-ref id="db">

              <description>DB Connection</description>

              <res-ref-name>jdbc/jlndb</res-ref-name>

              <res-type>javax.sql.DataSource</res-type>

              <res-auth>Container</res-auth>

           </resource-ref>

          其中id可以不寫(xiě)。

          注意:這里我沒(méi)有配置web.xml也成功了。

          c.添加架包,使用dbcp需要3個(gè)包:
          common-dbcp.jar,
          common-pool.jar,
          common-collections.jar

          數(shù)據(jù)庫(kù)的驅(qū)動(dòng)包:具體看數(shù)據(jù)庫(kù)而定

          2.需要一個(gè)servlet來(lái)初始化監(jiān)視器

          package com.handson.bbs.servlet;

          import java.sql.SQLException;

          import javax.naming.Context;
          import javax.naming.InitialContext;
          import javax.naming.NamingException;
          import javax.servlet.ServletContextEvent;
          import javax.servlet.ServletContextListener;

          import org.apache.commons.dbcp.BasicDataSource;

          import com.handson.commons.jdbc.DataSourceProvider;
          /**
           * **********************************************
           * @description 通過(guò)監(jiān)視器,在項(xiàng)目啟動(dòng)時(shí)初始化連接池
           * 
          @author Gavin.lee
           * @date Jun 27, 2009    1:13:28 PM
           * 
          @version 1.0
           ***********************************************
           
          */

          public class DBCPInitListener implements ServletContextListener {
              
              
          //釋放連接池的資源
              public void contextDestroyed(ServletContextEvent event) {
                  BasicDataSource ds 
          = (BasicDataSource)DataSourceProvider.getInstance().getDataSource();
                  
          if(ds != null{
                      
          try {
                          ds.close();
                      }
           catch (SQLException e) {
                          e.printStackTrace();
                      }

                  }

              }


              
          //初始化連接池
              public void contextInitialized(ServletContextEvent event) {
                  
          try {
                      Context cxt 
          = new InitialContext();
                      BasicDataSource ds 
          = (BasicDataSource)cxt.lookup("java:/comp/env/jdbc/dataSource");
                      DataSourceProvider.getInstance().initDataSource(ds);
                  }
           catch (NamingException e) {
                      e.printStackTrace();
                  }

              }


          }

          3.web.xml配置
               監(jiān)視器
            <listener>
                
          <listener-class>com.handson.bbs.servlet.DBCPInitListener</listener-class>
            
          </listener>

          4.DataSourceProvider用來(lái)初始化BasicDataSource
          package com.handson.commons.jdbc;

          import javax.sql.DataSource;
          /**
           * **********************************************
           * @description 單態(tài)類(lèi)初始化數(shù)據(jù)源
           * 
          @author Gavin.lee
           * @date Jun 27, 2009    1:19:21 PM
           * 
          @version 1.0
           ***********************************************
           
          */

          public class DataSourceProvider {
              
              
          private DataSource ds;
              
              
          private static DataSourceProvider instance;
              
              
          private DataSourceProvider() {
              }

              
              
          public static DataSourceProvider getInstance() {
                  
          if(instance == null{
                      instance 
          = new DataSourceProvider();
                  }

                  
                  
          return instance;
              }

              
              
          public void initDataSource(DataSource ds) {
                  
          this.ds = ds;
              }


              
          public DataSource getDataSource() {
                  
          return ds;
              }

          }


          5.DAO層可以使用DBCP連接池資源了,這里為了擴(kuò)展,封裝了一個(gè)DBUtil類(lèi)(不喜歡的話(huà)可以直接在DAO通過(guò)連接DataSourceProvider初始化資源)
          package com.handson.commons.jdbc;

          import java.io.*;
          import java.sql.*;

          import javax.sql.*;
          /**
           * **********************************************
           * @description DBUtil類(lèi),為擴(kuò)展用
           * 
          @author Gavin.lee
           * @date Jun 27, 2009    1:23:57 PM
           * 
          @version 1.0
           ***********************************************
           
          */

          public class DBUtil {
              
          private Connection conn = null;
              
          private PreparedStatement prepStmt = null;
              
              
              
          public DBUtil(String sql) throws SQLException  {
                  DataSourceProvider provider 
          = DataSourceProvider.getInstance();
                  
          this.conn = provider.getDataSource().getConnection();
                  prepStmt 
          = conn.prepareStatement(sql,
                          ResultSet.TYPE_SCROLL_INSENSITIVE,
                          ResultSet.CONCUR_READ_ONLY);
              }

              
          public DBUtil(Connection conn, String sql) throws SQLException  {
                  
          this.conn = conn;
                  prepStmt 
          = conn.prepareStatement(sql,
                          ResultSet.TYPE_SCROLL_INSENSITIVE,
                          ResultSet.CONCUR_READ_ONLY);
              }

              
              
          public DBUtil(DataSource ds, String sql) throws SQLException  {
                  conn 
          = ds.getConnection();
                  prepStmt 
          = conn.prepareStatement(sql,
                          ResultSet.TYPE_SCROLL_INSENSITIVE,
                          ResultSet.CONCUR_READ_ONLY);
              }

              
              
          public Connection getConnection() {
                  
          return conn;
              }

              
              
          public PreparedStatement getPreparedStatement() {
                  
          return prepStmt;
              }

                  
              
          public boolean execute() throws SQLException {
                  
          if(prepStmt == null)
                      
          return false;
                  
          return prepStmt.execute();
              }

              
              
          public ResultSet executeQuery() throws SQLException {        
                  
          return prepStmt.executeQuery();
              }

              
              
          public int executeUpdate() throws SQLException {
                  
          if(prepStmt == null){
                      
          return -1;
                  }

                  
          return prepStmt.executeUpdate();
              }

              
              
          public void close() {
                  
          try {
                      
          if (prepStmt != null{
                          prepStmt.close();
                          prepStmt 
          = null;
                      }

                      
          if(conn != null{
                          conn.close();
                          conn 
          = null;
                      }

                  }
           catch (Exception e) {
                      e.printStackTrace();
                  }

              }

              
              
          public void setString(int index,String value) throws SQLException {
                  prepStmt.setString(index,value);
              }

              
              
          public void setInt(int index,int value) throws SQLException {
                  prepStmt.setInt(index,value);
              }

              
              
          public void setBoolean(int index,boolean value) throws SQLException {
                  prepStmt.setBoolean(index,value);
              }

              
              
          public void setDate(int index,Date value) throws SQLException {
                  prepStmt.setDate(index,value);
              }

              
              
          public void setDate(int index, java.util.Date value) throws SQLException {
                  java.sql.Date date 
          = new java.sql.Date(value.getTime());
                  prepStmt.setDate(index, date);
              }

              
              
          public void setTime(int index,Time value) throws SQLException {
                  prepStmt.setTime(index,value);
              }

              
              
          public void setTimestamp(int index,Timestamp value) throws SQLException {
                  prepStmt.setTimestamp(index,value);
              }

              
              
          public void setLong(int index,long value) throws SQLException {
                  prepStmt.setLong(index,value);
              }

              
              
          public void setFloat(int index,float value) throws SQLException {
                  prepStmt.setFloat(index,value);
              }

              
              
          public void setObject(int index, Object obj) throws SQLException {
                  prepStmt.setObject(index, obj);
              }

              
              
          /**
               * File file = new File("test/data.txt");
               * int fileLength = file.length();
               * InputStream fin = new java.io.FileInputStream(file);
               * mysql.setBinaryStream(5,fin,fileLength);
               
          */

              
          public void setBinaryStream(int index,InputStream in,int length) throws SQLException {
                  prepStmt.setBinaryStream(index,in,length);
              }

              
              
          public void commit() {
                  
          try {
                      conn.commit();
                  }
           catch(Exception e) {
                      e.printStackTrace();
                  }

              }

              
              
          public void rollback() {
                  
          try {
                      conn.rollback();
                  }
           catch(Exception e) {
                      e.printStackTrace();
                  }

              }

              
              
          public static void main(String[] args) {
              }



              
          }

          6.具體的一個(gè)使用實(shí)例
          private DataSource ds;
              
              
          public ForumDAO(){
                  
          this.ds = DataSourceProvider.getInstance().getDataSource();
              }

              
          /*
               * 通過(guò)帖子的主題來(lái)查找帖子
               * (non-Javadoc)
               * @see com.handson.bbs.dao.IForumDAO#searchForumsBySubject(java.lang.String)
               
          */

              
          public List<Forum> searchForumsBySubject(String subject) {
                  
                  String sql 
          = "select * from forum where subject like '%" + subject + "%'";
                  DBUtil db 
          = null;
                  List
          <Forum> forums = null;
                  
          try{
                      db 
          = new DBUtil(ds,sql); 
                      
          //db.setString(1,subject);
                      ResultSet rs = db.executeQuery();            
                      Forum forum 
          = null;
                      
          while(rs.next()){
                          forums 
          = new ArrayList<Forum>();
                          forum 
          = this.populate(rs);
                          
                          forums.add(forum);                
                      }

                      
                  }
          catch(Exception e){
                      e.printStackTrace();
                  }
          finally{
                      db.close();
                  }

                  
                  
          return forums;
              }


          主站蜘蛛池模板: 名山县| 报价| 娱乐| 从江县| 夹江县| 宁强县| 金塔县| 揭阳市| 霍邱县| 新竹市| 泗水县| 沙田区| 寿光市| 大英县| 白朗县| 叶城县| 建德市| 忻城县| 贵州省| 景泰县| 邢台市| 临朐县| 姜堰市| 衢州市| 南澳县| 武鸣县| 安泽县| 博野县| 神池县| 巴马| 曲周县| 易门县| 景洪市| 新巴尔虎左旗| 五莲县| 文山县| 保定市| 朝阳县| 尼木县| 庄浪县| 新宾|