druid簡單教程

目錄(?)[+]

Java程序很大一部分要操作數據庫,爲了提高性能操作數據庫的時候,有不得不使用數據庫連接池。數據庫連接池有很多選擇,c3p、dhcp、proxool等,druid作爲一名後起之秀,憑藉其出色的性能,也逐漸印入了大家的眼簾。接下來本教程就說一下druid的簡單使用。

 首先從http://repo1.maven.org/maven2/com/alibaba/druid/ 下載最新的jar包。如果想使用最新的源碼編譯,可以從https://github.com/alibaba/druid 下載源碼,然後使用maven命令行,或者導入到eclipse中進行編譯。

1 配置

和dbcp類似,druid的常用配置項如下

配置 缺省值 說明
name   配置這個屬性的意義在於,如果存在多個數據源,監控的時候
可以通過名字來區分開來。如果沒有配置,將會生成一個名字,
格式是:"DataSource-" + System.identityHashCode(this)
jdbcUrl   連接數據庫的url,不同數據庫不一樣。例如:
mysql : jdbc:mysql://10.20.153.104:3306/druid2 
oracle : jdbc:oracle:thin:@10.20.149.85:1521:ocnauto
username   連接數據庫的用戶名
password   連接數據庫的密碼。如果你不希望密碼直接寫在配置文件中,
可以使用ConfigFilter。詳細看這裏:
https://github.com/alibaba/druid/wiki/%E4%BD%BF%E7%94%A8ConfigFilter
driverClassName 根據url自動識別 這一項可配可不配,如果不配置druid會根據url自動識別dbType,
然後選擇相應的driverClassName
initialSize 0 初始化時建立物理連接的個數。初始化發生在顯示調用init方法,
或者第一次getConnection時
maxActive 8 最大連接池數量
maxIdle 8 已經不再使用,配置了也沒效果
minIdle   最小連接池數量
maxWait   獲取連接時最大等待時間,單位毫秒。配置了maxWait之後,
缺省啓用公平鎖,併發效率會有所下降,
如果需要可以通過配置useUnfairLock屬性爲true使用非公平鎖。
poolPreparedStatements false 是否緩存preparedStatement,也就是PSCache。
PSCache對支持遊標的數據庫性能提升巨大,比如說oracle。
在mysql5.5以下的版本中沒有PSCache功能,建議關閉掉。
5.5及以上版本有PSCache,建議開啓。
maxOpenPreparedStatements -1 要啓用PSCache,必須配置大於0,當大於0時,
poolPreparedStatements自動觸發修改爲true。
在Druid中,不會存在Oracle下PSCache佔用內存過多的問題,
可以把這個數值配置大一些,比如說100
validationQuery   用來檢測連接是否有效的sql,要求是一個查詢語句。
如果validationQuery爲null,testOnBorrow、testOnReturn、
testWhileIdle都不會其作用。在mysql中通常爲select 'x',在oracle中通常爲
select 1 from dual
testOnBorrow true 申請連接時執行validationQuery檢測連接是否有效,
做了這個配置會降低性能。
testOnReturn false 歸還連接時執行validationQuery檢測連接是否有效,
做了這個配置會降低性能
testWhileIdle false 建議配置爲true,不影響性能,並且保證安全性。
申請連接的時候檢測,如果空閒時間大於
timeBetweenEvictionRunsMillis,
執行validationQuery檢測連接是否有效。
timeBetweenEvictionRunsMillis   有兩個含義:
1) Destroy線程會檢測連接的間隔時間
 2) testWhileIdle的判斷依據,詳細看testWhileIdle屬性的說明
numTestsPerEvictionRun   不再使用,一個DruidDataSource只支持一個EvictionRun
minEvictableIdleTimeMillis   Destory線程中如果檢測到當前連接的最後活躍時間和當前時間的差值大於
minEvictableIdleTimeMillis,則關閉當前連接。
connectionInitSqls   物理連接初始化的時候執行的sql
exceptionSorter 根據dbType自動識別 當數據庫拋出一些不可恢復的異常時,拋棄連接
filters   屬性類型是字符串,通過別名的方式配置擴展插件,
常用的插件有:
監控統計用的filter:stat 
日誌用的filter:log4j
 防禦sql注入的filter:wall
proxyFilters   類型是List<com.alibaba.druid.filter.Filter>,
如果同時配置了filters和proxyFilters,
是組合關係,並非替換關係
removeAbandoned   對於建立時間超過removeAbandonedTimeout的連接強制關閉
removeAbandonedTimeout   指定連接建立多長時間就需要被強制關閉
logAbandoned   指定發生removeabandoned的時候,是否記錄當前線程的堆棧信息到日誌中

表1.1 配置屬性

表1.1僅僅列出了常用配置屬性,完整的屬性列表可以參考代碼類DruidDataSourceFactory 的ALL_PROPERTIES屬性,根據常用的配置屬性,首先給出一個如下的配置文件,放置於src目錄下。

[plain] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1. url:jdbc:mysql://localhost:3306/dragoon_v25_masterdb  
  2. driverClassName:com.mysql.jdbc.Driver  
  3. username:root  
  4. password:aaaaaaaa  
  5.        
  6. filters:stat  
  7.    
  8. maxActive:20  
  9. initialSize:1  
  10. maxWait:60000  
  11. minIdle:10  
  12. #maxIdle:15  
  13.    
  14. timeBetweenEvictionRunsMillis:60000  
  15. minEvictableIdleTimeMillis:300000  
  16.    
  17. validationQuery:SELECT 'x'  
  18. testWhileIdle:true  
  19. testOnBorrow:false  
  20. testOnReturn:false  
  21. #poolPreparedStatements:true  
  22. maxOpenPreparedStatements:20  

配置文件1.1 

配置項中指定了各個參數後,在連接池內部是這麼使用這些參數的。數據庫連接池在初始化的時候會創建initialSize個連接,當有數據庫操作時,會從池中取出一個連接。如果當前池中正在使用的連接數等於maxActive,則會等待一段時間,等待其他操作釋放掉某一個連接,如果這個等待時間超過了maxWait,則會報錯;如果當前正在使用的連接數沒有達到maxActive,則判斷當前是否空閒連接,如果有則直接使用空閒連接,如果沒有則新建立一個連接。在連接使用完畢後,不是將其物理連接關閉,而是將其放入池中等待其他操作複用。

同時連接池內部有機制判斷,如果當前的總的連接數少於miniIdle,則會建立新的空閒連接,以保證連接數得到miniIdle。如果當前連接池中某個連接在空閒了timeBetweenEvictionRunsMillis時間後任然沒有使用,則被物理性的關閉掉。有些數據庫連接的時候有超時限制(MySQL連接在8小時後斷開),或者由於網絡中斷等原因,連接池的連接會出現失效的情況,這時候可以設置一個testWhileIdle參數爲true,注意這裏的“while”這個單詞應該翻譯成“如果”,換句話說testWhileIdle寫爲testIfIdle更好理解些,其含義爲連接在獲取連接的時候,如果檢測到當前連接不活躍的時間超過了timeBetweenEvictionRunsMillis,則去手動檢測一下當前連接的有效性,在保證確實有效後才加以使用。在檢測活躍性時,如果當前的活躍時間大於minEvictableIdleTimeMillis,則認爲需要關閉當前連接。當然,爲了保證絕對的可用性,你也可以使用testOnBorrow爲true(即在每次獲取Connection對象時都檢測其可用性),不過這樣會影響性能。

最後說一下removeAbandoned參數,其實druid是不能檢測到當前使用的連接是否發生了連接泄露,所以在代碼內部就假定如果一個連接建立連接的時間很長,則將其認定爲泄露,繼而強制將其關閉掉。這個參數在druid中默認是不開啓的,github上給出的wiki中也對其沒有絲毫提及。其實在代碼中設置testWhileIdle就能在一定程序上消滅掉泄露的連接,因爲如果發生了泄露,那麼他的不活躍時間肯定會在某個時間點大於timeBetweenEvictionRunsMillis,繼而被回收掉。

2 代碼編寫

2.1 使用spring

首先給出spring配置文件

[html] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd  
  5.         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  6.         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
  7.     <!-- 給web使用的spring文件 -->  
  8.     <bean id="propertyConfigurer"  
  9.         class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
  10.         <property name="locations">  
  11.             <list>  
  12.                 <value>/WEB-INF/classes/dbconfig.properties</value>  
  13.             </list>  
  14.         </property>  
  15.     </bean>  
  16.     <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"  
  17.         destroy-method="close">  
  18.         <property name="url" value="${url}" />  
  19.         <property name="username" value="${username}" />  
  20.         <property name="password" value="${password}" />  
  21.         <property name="driverClassName" value="${driverClassName}" />  
  22.         <property name="filters" value="${filters}" />  
  23.   
  24.         <property name="maxActive" value="${maxActive}" />  
  25.         <property name="initialSize" value="${initialSize}" />  
  26.         <property name="maxWait" value="${maxWait}" />  
  27.         <property name="minIdle" value="${minIdle}" />  
  28.   
  29.         <property name="timeBetweenEvictionRunsMillis" value="${timeBetweenEvictionRunsMillis}" />  
  30.         <property name="minEvictableIdleTimeMillis" value="${minEvictableIdleTimeMillis}" />  
  31.   
  32.         <property name="validationQuery" value="${validationQuery}" />  
  33.         <property name="testWhileIdle" value="${testWhileIdle}" />  
  34.         <property name="testOnBorrow" value="${testOnBorrow}" />  
  35.         <property name="testOnReturn" value="${testOnReturn}" />  
  36.         <property name="maxOpenPreparedStatements"  
  37.             value="${maxOpenPreparedStatements}" />  
  38.         <property name="removeAbandoned" value="${removeAbandoned}" /> <!-- 打開removeAbandoned功能 -->  
  39.         <property name="removeAbandonedTimeout" value="${removeAbandonedTimeout}" /> <!-- 1800秒,也就是30分鐘 -->  
  40.         <property name="logAbandoned" value="${logAbandoned}" /> <!-- 關閉abanded連接時輸出錯誤日誌 -->  
  41.     </bean>  
  42.       
  43.     <bean id="dataSourceDbcp" class="org.apache.commons.dbcp.BasicDataSource"  
  44.         destroy-method="close">  
  45.   
  46.         <property name="driverClassName" value="${driverClassName}" />  
  47.         <property name="url" value="${url}" />  
  48.         <property name="username" value="${username}" />  
  49.         <property name="password" value="${password}" />  
  50.           
  51.         <property name="maxActive" value="${maxActive}" />  
  52.         <property name="minIdle" value="${minIdle}" />  
  53.         <property name="maxWait" value="${maxWait}" />  
  54.         <property name="defaultAutoCommit" value="true" />  
  55.           
  56.         <property name="timeBetweenEvictionRunsMillis" value="${timeBetweenEvictionRunsMillis}" />  
  57.         <property name="minEvictableIdleTimeMillis" value="${minEvictableIdleTimeMillis}" />  
  58.           
  59.         <property name="validationQuery" value="${validationQuery}" />  
  60.         <property name="testWhileIdle" value="${testWhileIdle}" />  
  61.         <property name="testOnBorrow" value="${testOnBorrow}" />  
  62.         <property name="testOnReturn" value="${testOnReturn}" />  
  63.         <property name="maxOpenPreparedStatements"  
  64.             value="${maxOpenPreparedStatements}" />  
  65.         <property name="removeAbandoned" value="${removeAbandoned}" />   
  66.         <property name="removeAbandonedTimeout" value="${removeAbandonedTimeout}" />  
  67.         <property name="logAbandoned" value="${logAbandoned}" />  
  68.     </bean>  
  69.   
  70.       
  71.     <!-- jdbcTemplate -->  
  72.     <bean id="jdbc" class="org.springframework.jdbc.core.JdbcTemplate">  
  73.         <property name="dataSource">  
  74.             <ref bean="dataSource" />  
  75.         </property>  
  76.     </bean>  
  77.   
  78.     <bean id="SpringTableOperatorBean" class="com.whyun.druid.model.TableOperator"  
  79.         scope="prototype">  
  80.         <property name="dataSource">  
  81.             <ref bean="dataSource" />  
  82.         </property>  
  83.     </bean>  
  84.       
  85. </beans>  


配置文件2.1

其中第一個bean中給出的配置文件/WEB-INF/classes/dbconfig.properties就是第1節中給出的配置文件。我這裏還特地給出dbcp的spring配置項,目的就是將兩者進行對比,方便大家進行遷移。這裏沒有使用JdbcTemplate,所以jdbc那個bean沒有使用到。下面給出com.whyun.druid.model.TableOperator類的代碼。

[java] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1. package com.whyun.druid.model;  
  2.   
  3. import java.sql.Connection;  
  4. import java.sql.PreparedStatement;  
  5. import java.sql.SQLException;  
  6. import java.sql.Statement;  
  7.   
  8. import javax.sql.DataSource;  
  9.   
  10. public class TableOperator {  
  11.     private DataSource dataSource;  
  12.     public void setDataSource(DataSource dataSource) {  
  13.         this.dataSource = dataSource;  
  14.     }  
  15.   
  16.     private static final int COUNT = 800;      
  17.   
  18.     public TableOperator() {  
  19.           
  20.     }  
  21.   
  22.     public void tearDown() throws Exception {  
  23.         try {  
  24.             dropTable();  
  25.         } catch (SQLException e) {  
  26.             e.printStackTrace();  
  27.         }         
  28.     }  
  29.   
  30.     public void insert() throws Exception {  
  31.           
  32.         StringBuffer ddl = new StringBuffer();  
  33.         ddl.append("INSERT INTO t_big (");  
  34.         for (int i = 0; i < COUNT; ++i) {  
  35.             if (i != 0) {  
  36.                 ddl.append(", ");  
  37.             }  
  38.             ddl.append("F" + i);  
  39.         }  
  40.         ddl.append(") VALUES (");  
  41.         for (int i = 0; i < COUNT; ++i) {  
  42.             if (i != 0) {  
  43.                 ddl.append(", ");  
  44.             }  
  45.             ddl.append("?");  
  46.         }  
  47.         ddl.append(")");  
  48.   
  49.         Connection conn = dataSource.getConnection();  
  50.   
  51. //        System.out.println(ddl.toString());  
  52.   
  53.         PreparedStatement stmt = conn.prepareStatement(ddl.toString());  
  54.   
  55.         for (int i = 0; i < COUNT; ++i) {  
  56.             stmt.setInt(i + 1, i);  
  57.         }  
  58.         stmt.execute();  
  59.         stmt.close();  
  60.   
  61.         conn.close();  
  62.     }  
  63.   
  64.     private void dropTable() throws SQLException {  
  65.   
  66.         Connection conn = dataSource.getConnection();  
  67.   
  68.         Statement stmt = conn.createStatement();  
  69.         stmt.execute("DROP TABLE t_big");  
  70.         stmt.close();  
  71.   
  72.         conn.close();  
  73.     }  
  74.   
  75.     public void createTable() throws SQLException {  
  76.         StringBuffer ddl = new StringBuffer();  
  77.         ddl.append("CREATE TABLE t_big (FID INT AUTO_INCREMENT PRIMARY KEY ");  
  78.         for (int i = 0; i < COUNT; ++i) {  
  79.             ddl.append(", ");  
  80.             ddl.append("F" + i);  
  81.             ddl.append(" BIGINT NULL");  
  82.         }  
  83.         ddl.append(")");  
  84.   
  85.         Connection conn = dataSource.getConnection();  
  86.   
  87.         Statement stmt = conn.createStatement();  
  88.         stmt.execute(ddl.toString());  
  89.         stmt.close();  
  90.   
  91.         conn.close();  
  92.     }  
  93. }  

代碼片段2.1

注意:在使用的時候,通過獲取完Connection對象,在使用完之後,要將其close掉,這樣其實是將用完的連接放入到連接池中,如果你不close的話,會造成連接泄露。

然後我們寫一個servlet來測試他.

[java] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1. package com.whyun.druid.servelt;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.PrintWriter;  
  5. import java.sql.SQLException;  
  6.   
  7. import javax.servlet.ServletContext;  
  8. import javax.servlet.ServletException;  
  9. import javax.servlet.http.HttpServlet;  
  10. import javax.servlet.http.HttpServletRequest;  
  11. import javax.servlet.http.HttpServletResponse;  
  12.   
  13. import org.springframework.web.context.WebApplicationContext;  
  14. import org.springframework.web.context.support.WebApplicationContextUtils;  
  15.   
  16. import com.whyun.druid.model.TableOperator;  
  17.   
  18. public class TestServlet extends HttpServlet {  
  19.     private TableOperator operator;  
  20.       
  21.   
  22.     @Override  
  23.     public void init() throws ServletException {  
  24.           
  25.         super.init();  
  26.          ServletContext servletContext = this.getServletContext();     
  27.            
  28.          WebApplicationContext ctx  
  29.             = WebApplicationContextUtils.getWebApplicationContext(servletContext);  
  30.          operator = (TableOperator)ctx.getBean("SpringTableOperatorBean");  
  31.     }  
  32.   
  33.     /** 
  34.      * The doGet method of the servlet. <br> 
  35.      * 
  36.      * This method is called when a form has its tag value method equals to get. 
  37.      *  
  38.      * @param request the request send by the client to the server 
  39.      * @param response the response send by the server to the client 
  40.      * @throws ServletException if an error occurred 
  41.      * @throws IOException if an error occurred 
  42.      */  
  43.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  44.             throws ServletException, IOException {  
  45.   
  46.         response.setContentType("text/html");  
  47.         PrintWriter out = response.getWriter();  
  48.   
  49.         boolean createResult = false;  
  50.         boolean insertResult = false;  
  51.         boolean dropResult = false;  
  52.           
  53.         try {  
  54.             operator.createTable();  
  55.             createResult = true;  
  56.         } catch (SQLException e) {  
  57.             e.printStackTrace();  
  58.         }  
  59.         if (createResult) {  
  60.             try {  
  61.                 operator.insert();  
  62.                 insertResult = true;  
  63.             } catch (Exception e) {  
  64.                 e.printStackTrace();  
  65.             }  
  66.             try {  
  67.                 operator.tearDown();  
  68.                 dropResult = true;  
  69.             } catch (Exception e) {  
  70.                 e.printStackTrace();  
  71.             }  
  72.         }  
  73.           
  74.           
  75.         out.println("{'createResult':"+createResult+",'insertResult':"  
  76.                 +insertResult+",'dropResult':"+dropResult+"}");  
  77.           
  78.         out.flush();  
  79.         out.close();  
  80.     }  
  81.   
  82. }  
代碼片段2.2

這裏沒有用到struts2或者springmvc,雖然大部分開發者用的是這兩種框架。

2.2 不使用spring

類似於dbcp,druid也提供了原生態的支持。這裏僅僅列出來瞭如何獲取一個DataSource對象,實際使用中要將獲取DataSource的過程封裝到一個單體模式類中。先看下面這段代碼:

[java] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1. package com.whyun.util.db;  
  2.   
  3. import javax.sql.DataSource;  
  4.   
  5. import org.apache.commons.dbcp.BasicDataSourceFactory;  
  6.   
  7. import com.alibaba.druid.pool.DruidDataSourceFactory;  
  8. import com.whyun.util.config.MySqlConfigProperty;  
  9. import com.whyun.util.config.MySqlConfigProperty2;  
  10. import com.whyun.util.db.source.AbstractDataSource;  
  11. import com.whyun.util.db.source.impl.DbcpSourceMysql;  
  12. import com.whyun.util.db.source.impl.DruidSourceMysql;  
  13. import com.whyun.util.db.source.impl.DruidSourceMysql2;  
  14.   
  15. // TODO: Auto-generated Javadoc  
  16. /** 
  17.  * The Class DataSourceUtil. 
  18.  */  
  19. public class DataSourceUtil {  
  20.       
  21.     /** 使用配置文件dbconfig.properties構建Druid數據源. */  
  22.     public static final int DRUID_MYSQL_SOURCE = 0;  
  23.       
  24.     /** The duird mysql source. */  
  25.     private static DataSource duirdMysqlSource;  
  26.       
  27.     /** 使用配置文件dbconfig2.properties構建Druid數據源. */  
  28.     public static final int DRUID_MYSQL_SOURCE2 = 1;  
  29.       
  30.     /** The druid mysql source2. */  
  31.     private static DataSource druidMysqlSource2;  
  32.       
  33.     /** 使用配置文件dbconfig.properties構建Dbcp數據源. */  
  34.     public static final int DBCP_SOURCE = 4;  
  35.       
  36.     /** The dbcp source. */  
  37.     private static  DataSource dbcpSource;  
  38.       
  39.     /** 
  40.      * 根據類型獲取數據源. 
  41.      * 
  42.      * @param sourceType 數據源類型 
  43.      * @return druid或者dbcp數據源 
  44.      * @throws Exception the exception 
  45.      * @NotThreadSafe 
  46.      */  
  47.     public static final DataSource getDataSource(int sourceType)  
  48.         throws Exception {  
  49.         DataSource dataSource = null;  
  50.         switch(sourceType) {  
  51.         case DRUID_MYSQL_SOURCE:              
  52.               
  53.             if (duirdMysqlSource == null) {  
  54.                 duirdMysqlSource = DruidDataSourceFactory.createDataSource(  
  55.                     MySqlConfigProperty.getInstance().getProperties());  
  56.             }  
  57.             dataSource = duirdMysqlSource;  
  58.             break;  
  59.         case DRUID_MYSQL_SOURCE2:  
  60.             if (druidMysqlSource2 == null) {  
  61.                 druidMysqlSource2 = DruidDataSourceFactory.createDataSource(  
  62.                     MySqlConfigProperty2.getInstance().getProperties());  
  63.             }  
  64.             dataSource = druidMysqlSource2;  
  65.             break;  
  66.         case DBCP_SOURCE:  
  67.             if (dbcpSource == null) {  
  68.                 dbcpSource = BasicDataSourceFactory.createDataSource(  
  69.                     MySqlConfigProperty.getInstance().getProperties());  
  70.             }  
  71.             dataSource = dbcpSource;  
  72.             break;  
  73.         }  
  74.         return dataSource;  
  75.     }  
  76.       
  77.     /** 
  78.      * 根據數據庫類型標示獲取DataSource對象,跟{@link com.whyun.util.db.DataSourceUtil#getDataSource(int)} 
  79.      * 不同的是,這裏DataSource獲取的時候使用了單體模式 
  80.      * 
  81.      * @param sourceType 數據源類型 
  82.      * @return 獲取到的DataSource對象 
  83.      * @throws Exception the exception 
  84.      */  
  85.     public static final DataSource getDataSource2(int sourceType) throws Exception {  
  86.   
  87.         AbstractDataSource abstractDataSource = null;  
  88.         switch(sourceType) {  
  89.         case DRUID_MYSQL_SOURCE:              
  90.             abstractDataSource = DruidSourceMysql.getInstance();  
  91.             break;  
  92.         case DRUID_MYSQL_SOURCE2:  
  93.             abstractDataSource = DruidSourceMysql2.getInstance();  
  94.             break;  
  95.         case DBCP_SOURCE:  
  96.             abstractDataSource = DbcpSourceMysql.getInstance();  
  97.             break;  
  98.         }  
  99.         return abstractDataSource == null ?  
  100.                 null :  
  101.                     abstractDataSource.getDataSource();  
  102.     }  
  103. }  

代碼片段2.3 手動讀取配置文件初始化連接池

第37行中調用了類com.alibaba.druid.pool.DruidDataSourceFactory中createDataSource方法來初始化一個連接池。對比dbcp的使用方法,兩者很相似。

下面給出一個多線程的測試程序。運行後可以比較druid和dbcp的性能差別。

[java] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1. package com.whyun.druid.test;  
  2.   
  3. import java.sql.SQLException;  
  4. import java.util.ArrayList;  
  5. import java.util.List;  
  6. import java.util.concurrent.Callable;  
  7. import java.util.concurrent.ExecutorService;  
  8. import java.util.concurrent.Executors;  
  9. import java.util.concurrent.Future;  
  10. import java.util.concurrent.TimeUnit;  
  11.   
  12. import com.whyun.druid.model.TableOperator;  
  13. import com.whyun.util.db.DataSourceUtil;  
  14.   
  15. public class MutilThreadTest {  
  16.     public static void test(int dbType, int times)  
  17.         throws Exception {   
  18.         int numOfThreads =Runtime.getRuntime().availableProcessors()*2;  
  19.         ExecutorService executor = Executors.newFixedThreadPool(numOfThreads);    
  20.         final TableOperator test = new TableOperator();  
  21. //        int dbType = DataSourceUtil.DRUID_MYSQL_SOURCE;  
  22. //        dbType = DataSourceUtil.DBCP_SOURCE;  
  23.         test.setDataSource(DataSourceUtil.getDataSource(dbType));  
  24.           
  25.         boolean createResult = false;  
  26.         try {  
  27.             test.createTable();  
  28.             createResult = true;  
  29.         } catch (SQLException e) {  
  30.             e.printStackTrace();  
  31.         }  
  32.         if (createResult) {  
  33.             List<Future<Long>> results = new ArrayList<Future<Long>>();     
  34.             for (int i = 0; i < times; i++) {    
  35.                 results.add(executor.submit(new Callable<Long>() {    
  36.                     @Override    
  37.                     public Long call() throws Exception {    
  38.                             long begin = System.currentTimeMillis();  
  39.                                 try {  
  40.                                     test.insert();  
  41.                                     //insertResult = true;  
  42.                                 } catch (Exception e) {  
  43.                                     e.printStackTrace();  
  44.                                 }                             
  45.                             long end = System.currentTimeMillis();    
  46.                         return end - begin;    
  47.                     }    
  48.                 }));    
  49.             }    
  50.             executor.shutdown();    
  51.             while(!executor.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS));    
  52.                 
  53.             long sum = 0;    
  54.             for (Future<Long> result : results) {    
  55.                 sum += result.get();    
  56.             }    
  57.                 
  58.                 
  59.             System.out.println("---------------db type "+dbType+"------------------");    
  60.             System.out.println("number of threads :" + numOfThreads + " times:" + times);    
  61.             System.out.println("running time: " + sum + "ms");    
  62.             System.out.println("TPS: " + (double)(100000 * 1000) / (double)(sum));    
  63.             System.out.println();    
  64.             try {  
  65.                 test.tearDown();  
  66.                 //dropResult = true;  
  67.             } catch (Exception e) {  
  68.                 e.printStackTrace();  
  69.             }  
  70.         } else {  
  71.             System.out.println("初始化數據庫失敗");  
  72.         }  
  73.           
  74.     }    
  75.       
  76.     public static void main (String argc[])  
  77.         throws Exception {  
  78.         test(DataSourceUtil.DBCP_SOURCE,50);  
  79.         test(DataSourceUtil.DRUID_MYSQL_SOURCE,50);  
  80.           
  81.     }  
  82. }  

代碼片段2.4 連接池多線程測試程序


3 監控

3.1 web監控

druid提供了sql語句查詢時間等信息的監控功能。爲了讓數據庫查詢一直運行,下面特地寫了一個ajax進行輪詢。同時,還要保證在web.xml中配置如下信息

[html] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1. <servlet>  
  2.         <servlet-name>DruidStatView</servlet-name>  
  3.         <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>  
  4.     </servlet>  
  5. <servlet-mapping>  
  6.         <servlet-name>DruidStatView</servlet-name>  
  7.         <url-pattern>/druid/*</url-pattern>  
  8.     </servlet-mapping>  
配置文件3.1 在web.xml中添加druid監控


同時將ajax代碼提供如下

[javascript] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1. function showTime() {  
  2.     var myDate = new Date();  
  3.     var timeStr = '';  
  4.     timeStr += myDate.getFullYear()+'-'//獲取完整的年份(4位,1970-????)  
  5.     timeStr += myDate.getMonth()+'-';      //獲取當前月份(0-11,0代表1月)  
  6.     timeStr += myDate.getDate() + ' ';      //獲取當前日(1-31)  
  7.     timeStr += myDate.getHours()+':';      //獲取當前小時數(0-23)  
  8.     timeStr += myDate.getMinutes()+':';    //獲取當前分鐘數(0-59)  
  9.     timeStr += myDate.getSeconds();    //獲取當前秒數(0-59)  
  10.     return timeStr  
  11. }  
  12. $(document).ready(function() {  
  13.     function loadDBTestMessage() {  
  14.         $.get('servlet/MysqlTestServlet',function(data) {  
  15.             if (typeof(data) != 'object') {  
  16.                 data = eval('(' + data + ')');  
  17.             }  
  18.             var html = '['+showTime()+']';  
  19.             html += '創建:' + data['createResult'];  
  20.             html +=  '插入:' + data['insertResult'];  
  21.             html += '銷燬:' + data['dropResult'];  
  22.             html +=   
  23.             $('#message').html(html);  
  24.         });  
  25.     }  
  26.       
  27.     setInterval(function() {  
  28.         loadDBTestMessage();  
  29.     }, 10000);  
  30. });  

代碼片段3.1 ajax輪詢

這時打開http://localhost/druid-web/druid/ 地址,會看到監控界面,點擊其中的sql標籤。

圖3.1 監控界面查看sql查詢時間

注意:在寫配置文件1.1時,要保證filter配置項中含有stat屬性,否則這個地方看不到sql語句的監控數據。

從0.2.23開始監控界面支持中英文語言,所以這裏就不翻譯表格中的英文字段了。


老版本的druid的jar包中不支持通過web界面進行遠程監控,從0.2.14開始可以通過配置jmx地址來獲取遠程運行druid的服務器的監控信息。具體配置方法如下:

[html] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1. <servlet>  
  2.         <servlet-name>DruidStatView</servlet-name>  
  3.         <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>  
  4.         <init-param>  
  5.             <param-name>jmxUrl</param-name>  
  6.             <param-value>service:jmx:rmi:///jndi/rmi://localhost:9004/jmxrmi</param-value>  
  7.         </init-param>  
  8.     </servlet>  
  9.     <servlet-mapping>  
  10.         <servlet-name>DruidStatView</servlet-name>  
  11.         <url-pattern>/druid/*</url-pattern>  
  12.     </servlet-mapping>  
配置文件3.2 遠程監控web

這裏連接的配置參數中多了一個jmxUrl,裏面配置一個jmx連接地址,如果配置了這個init-param後,那麼當前web監控界面監控的就不是本機的druid的使用情況,而是jmxUrl中指定的ip的遠程機器的druid使用情況。jmx連接中也可以指定用戶名、密碼,在上面的servlet中添加兩個init-param,其param-name分別爲jmxUsername和jmxPassword,分別對應連接jmx的用戶名和密碼。對於jmx在服務器端的配置,可以參考3.2節中的介紹。

3.2 jconsole監控

同時druid提供了jconsole監控的功能,因爲界面做的不是很好,所以官方中沒有對其的相關介紹。如果是純java程序的話,可以簡單的使用jconsole,也可以使用3.1中提到的通過配置init-param來訪問遠程druid。下面依然使用的是剛纔用的web項目來模擬druid所在的遠程機器。

現在假設有兩臺機器,一臺是運行druid的A機器,一臺是要查看druid運行信息的B機器。

首先在這臺遠程機器A的catalina.bat(或者catalina.sh)中加入java的啓動選項,放置於if "%OS%" == "Windows_NT" setlocal這句之後。

set JAVA_OPTS=%JAVA_OPTS% -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port="9004" -Dcom.sun.management.jmxremote.authenticate="false" -Dcom.sun.management.jmxremote.ssl="false"

保存完之後,啓動startup.bat(或者startup.sh)來運行tomcat(上面設置java啓動項的配置,按理來說在eclipse中也能適用,但是筆者在其下沒有試驗成功)。然後在要查看監控信息的某臺電腦B的命令行中運行如下命令

jconsole -pluginpath E:\kuaipan\workspace6\druid-web\WebRoot\WEB-INF\lib\druid-0.2.11.jar

這裏的最後一個參數就是你的druid的jar包的路徑。


圖3.2 jconsole連接界面

在遠程進程的輸入框裏面輸入ip:端口號,然後點擊連接(上面的配置中沒有指定用戶名、密碼,所以這裏不用填寫)。打開的界面如下:


圖3.3 jconsole 連接成功界面

可以看到和web監控界面類似的數據了。推薦直接使用web界面配置jmx地址方式來訪問遠程機器的druid使用情況,因爲這種方式查看到的數據信息更全面些。

參考


可以訪問http://git.oschina.net/yunnysunny/druid-demo 來獲取git版本庫中的最新代碼。

oschina 問答社區: http://www.oschina.net/p/druid
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章