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都不會其作用。 |
|
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目錄下。
- url:jdbc:mysql://localhost:3306/dragoon_v25_masterdb
- driverClassName:com.mysql.jdbc.Driver
- username:root
- password:aaaaaaaa
- filters:stat
- maxActive:20
- initialSize:1
- maxWait:60000
- minIdle:10
- #maxIdle:15
- timeBetweenEvictionRunsMillis:60000
- minEvictableIdleTimeMillis:300000
- validationQuery:SELECT 'x'
- testWhileIdle:true
- testOnBorrow:false
- testOnReturn:false
- #poolPreparedStatements:true
- maxOpenPreparedStatements:20
- #對於建立連接過長的連接強制關閉
- removeAbandoned:true
- #如果連接建立時間超過了30分鍾,則強制將其關閉
- removeAbandonedTimeout:1800
- #將當前關閉動作記錄到日志
- logAbandoned:true
配置文件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配置文件
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
- http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
- <!-- 給web使用的spring文件 -->
- <bean id="propertyConfigurer"
- class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
- <property name="locations">
- <list>
- <value>/WEB-INF/classes/dbconfig.properties</value>
- </list>
- </property>
- </bean>
- <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
- destroy-method="close">
- <property name="url" value="${url}" />
- <property name="username" value="${username}" />
- <property name="password" value="${password}" />
- <property name="driverClassName" value="${driverClassName}" />
- <property name="filters" value="${filters}" />
- <property name="maxActive" value="${maxActive}" />
- <property name="initialSize" value="${initialSize}" />
- <property name="maxWait" value="${maxWait}" />
- <property name="minIdle" value="${minIdle}" />
- <property name="timeBetweenEvictionRunsMillis" value="${timeBetweenEvictionRunsMillis}" />
- <property name="minEvictableIdleTimeMillis" value="${minEvictableIdleTimeMillis}" />
- <property name="validationQuery" value="${validationQuery}" />
- <property name="testWhileIdle" value="${testWhileIdle}" />
- <property name="testOnBorrow" value="${testOnBorrow}" />
- <property name="testOnReturn" value="${testOnReturn}" />
- <property name="maxOpenPreparedStatements"
- value="${maxOpenPreparedStatements}" />
- <property name="removeAbandoned" value="${removeAbandoned}" /> <!-- 打開removeAbandoned功能 -->
- <property name="removeAbandonedTimeout" value="${removeAbandonedTimeout}" /> <!-- 1800秒,也就是30分鍾 -->
- <property name="logAbandoned" value="${logAbandoned}" /> <!-- 關閉abanded連接時輸出錯誤日志 -->
- </bean>
- <bean id="dataSourceDbcp" class="org.apache.commons.dbcp.BasicDataSource"
- destroy-method="close">
- <property name="driverClassName" value="${driverClassName}" />
- <property name="url" value="${url}" />
- <property name="username" value="${username}" />
- <property name="password" value="${password}" />
- <property name="maxActive" value="${maxActive}" />
- <property name="minIdle" value="${minIdle}" />
- <property name="maxWait" value="${maxWait}" />
- <property name="defaultAutoCommit" value="true" />
- <property name="timeBetweenEvictionRunsMillis" value="${timeBetweenEvictionRunsMillis}" />
- <property name="minEvictableIdleTimeMillis" value="${minEvictableIdleTimeMillis}" />
- <property name="validationQuery" value="${validationQuery}" />
- <property name="testWhileIdle" value="${testWhileIdle}" />
- <property name="testOnBorrow" value="${testOnBorrow}" />
- <property name="testOnReturn" value="${testOnReturn}" />
- <property name="maxOpenPreparedStatements"
- value="${maxOpenPreparedStatements}" />
- <property name="removeAbandoned" value="${removeAbandoned}" />
- <property name="removeAbandonedTimeout" value="${removeAbandonedTimeout}" />
- <property name="logAbandoned" value="${logAbandoned}" />
- </bean>
- <!-- jdbcTemplate -->
- <bean id="jdbc" class="org.springframework.jdbc.core.JdbcTemplate">
- <property name="dataSource">
- <ref bean="dataSource" />
- </property>
- </bean>
- <bean id="SpringTableOperatorBean" class="com.whyun.druid.model.TableOperator"
- scope="prototype">
- <property name="dataSource">
- <ref bean="dataSource" />
- </property>
- </bean>
- </beans>
配置文件2.1
其中第一個bean中給出的配置文件/WEB-INF/classes/dbconfig.properties就是第1節中給出的配置文件。我這里還特地給出dbcp的spring配置項,目的就是將兩者進行對比,方便大家進行遷移。這里沒有使用JdbcTemplate,所以jdbc那個bean沒有使用到。下面給出com.whyun.druid.model.TableOperator類的代碼。
- package com.whyun.druid.model;
- import java.sql.Connection;
- import java.sql.PreparedStatement;
- import java.sql.SQLException;
- import java.sql.Statement;
- import javax.sql.DataSource;
- public class TableOperator {
- private DataSource dataSource;
- public void setDataSource(DataSource dataSource) {
- this.dataSource = dataSource;
- }
- private static final int COUNT = 800;
- public TableOperator() {
- }
- public void tearDown() throws Exception {
- try {
- dropTable();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- public void insert() throws Exception {
- StringBuffer ddl = new StringBuffer();
- ddl.append("INSERT INTO t_big (");
- for (int i = 0; i < COUNT; ++i) {
- if (i != 0) {
- ddl.append(", ");
- }
- ddl.append("F" + i);
- }
- ddl.append(") VALUES (");
- for (int i = 0; i < COUNT; ++i) {
- if (i != 0) {
- ddl.append(", ");
- }
- ddl.append("?");
- }
- ddl.append(")");
- Connection conn = dataSource.getConnection();
- // System.out.println(ddl.toString());
- PreparedStatement stmt = conn.prepareStatement(ddl.toString());
- for (int i = 0; i < COUNT; ++i) {
- stmt.setInt(i + 1, i);
- }
- stmt.execute();
- stmt.close();
- conn.close();
- }
- private void dropTable() throws SQLException {
- Connection conn = dataSource.getConnection();
- Statement stmt = conn.createStatement();
- stmt.execute("DROP TABLE t_big");
- stmt.close();
- conn.close();
- }
- public void createTable() throws SQLException {
- StringBuffer ddl = new StringBuffer();
- ddl.append("CREATE TABLE t_big (FID INT AUTO_INCREMENT PRIMARY KEY ");
- for (int i = 0; i < COUNT; ++i) {
- ddl.append(", ");
- ddl.append("F" + i);
- ddl.append(" BIGINT NULL");
- }
- ddl.append(")");
- Connection conn = dataSource.getConnection();
- Statement stmt = conn.createStatement();
- stmt.execute(ddl.toString());
- stmt.close();
- conn.close();
- }
- }
代碼片段2.1
注意:在使用的時候,通過獲取完Connection對象,在使用完之后,要將其close掉,這樣其實是將用完的連接放入到連接池中,如果你不close的話,會造成連接泄露。
然后我們寫一個servlet來測試他.
- package com.whyun.druid.servelt;
- import java.io.IOException;
- import java.io.PrintWriter;
- import java.sql.SQLException;
- import javax.servlet.ServletContext;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import org.springframework.web.context.WebApplicationContext;
- import org.springframework.web.context.support.WebApplicationContextUtils;
- import com.whyun.druid.model.TableOperator;
- public class TestServlet extends HttpServlet {
- private TableOperator operator;
- @Override
- public void init() throws ServletException {
- super.init();
- ServletContext servletContext = this.getServletContext();
- WebApplicationContext ctx
- = WebApplicationContextUtils.getWebApplicationContext(servletContext);
- operator = (TableOperator)ctx.getBean("SpringTableOperatorBean");
- }
- /**
- * The doGet method of the servlet. <br>
- *
- * This method is called when a form has its tag value method equals to get.
- *
- * @param request the request send by the client to the server
- * @param response the response send by the server to the client
- * @throws ServletException if an error occurred
- * @throws IOException if an error occurred
- */
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- response.setContentType("text/html");
- PrintWriter out = response.getWriter();
- boolean createResult = false;
- boolean insertResult = false;
- boolean dropResult = false;
- try {
- operator.createTable();
- createResult = true;
- } catch (SQLException e) {
- e.printStackTrace();
- }
- if (createResult) {
- try {
- operator.insert();
- insertResult = true;
- } catch (Exception e) {
- e.printStackTrace();
- }
- try {
- operator.tearDown();
- dropResult = true;
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- out.println("{'createResult':"+createResult+",'insertResult':"
- +insertResult+",'dropResult':"+dropResult+"}");
- out.flush();
- out.close();
- }
- }
這里沒有用到struts2或者springmvc,雖然大部分開發者用的是這兩種框架。
2.2 不使用spring
類似於dbcp,druid也提供了原生態的支持。這里僅僅列出來了如何獲取一個DataSource對象,實際使用中要將獲取DataSource的過程封裝到一個單體模式類中。先看下面這段代碼:
- package com.whyun.util.db;
- import javax.sql.DataSource;
- import org.apache.commons.dbcp.BasicDataSourceFactory;
- import com.alibaba.druid.pool.DruidDataSourceFactory;
- import com.whyun.util.config.MySqlConfigProperty;
- import com.whyun.util.config.MySqlConfigProperty2;
- import com.whyun.util.db.source.AbstractDataSource;
- import com.whyun.util.db.source.impl.DbcpSourceMysql;
- import com.whyun.util.db.source.impl.DruidSourceMysql;
- import com.whyun.util.db.source.impl.DruidSourceMysql2;
- // TODO: Auto-generated Javadoc
- /**
- * The Class DataSourceUtil.
- */
- public class DataSourceUtil {
- /** 使用配置文件dbconfig.properties構建Druid數據源. */
- public static final int DRUID_MYSQL_SOURCE = 0;
- /** The duird mysql source. */
- private static DataSource duirdMysqlSource;
- /** 使用配置文件dbconfig2.properties構建Druid數據源. */
- public static final int DRUID_MYSQL_SOURCE2 = 1;
- /** The druid mysql source2. */
- private static DataSource druidMysqlSource2;
- /** 使用配置文件dbconfig.properties構建Dbcp數據源. */
- public static final int DBCP_SOURCE = 4;
- /** The dbcp source. */
- private static DataSource dbcpSource;
- /**
- * 根據類型獲取數據源.
- *
- * @param sourceType 數據源類型
- * @return druid或者dbcp數據源
- * @throws Exception the exception
- * @NotThreadSafe
- */
- public static final DataSource getDataSource(int sourceType)
- throws Exception {
- DataSource dataSource = null;
- switch(sourceType) {
- case DRUID_MYSQL_SOURCE:
- if (duirdMysqlSource == null) {
- duirdMysqlSource = DruidDataSourceFactory.createDataSource(
- MySqlConfigProperty.getInstance().getProperties());
- }
- dataSource = duirdMysqlSource;
- break;
- case DRUID_MYSQL_SOURCE2:
- if (druidMysqlSource2 == null) {
- druidMysqlSource2 = DruidDataSourceFactory.createDataSource(
- MySqlConfigProperty2.getInstance().getProperties());
- }
- dataSource = druidMysqlSource2;
- break;
- case DBCP_SOURCE:
- if (dbcpSource == null) {
- dbcpSource = BasicDataSourceFactory.createDataSource(
- MySqlConfigProperty.getInstance().getProperties());
- }
- dataSource = dbcpSource;
- break;
- }
- return dataSource;
- }
- /**
- * 根據數據庫類型標示獲取DataSource對象,跟{@link com.whyun.util.db.DataSourceUtil#getDataSource(int)}
- * 不同的是,這里DataSource獲取的時候使用了單體模式
- *
- * @param sourceType 數據源類型
- * @return 獲取到的DataSource對象
- * @throws Exception the exception
- */
- public static final DataSource getDataSource2(int sourceType) throws Exception {
- AbstractDataSource abstractDataSource = null;
- switch(sourceType) {
- case DRUID_MYSQL_SOURCE:
- abstractDataSource = DruidSourceMysql.getInstance();
- break;
- case DRUID_MYSQL_SOURCE2:
- abstractDataSource = DruidSourceMysql2.getInstance();
- break;
- case DBCP_SOURCE:
- abstractDataSource = DbcpSourceMysql.getInstance();
- break;
- }
- return abstractDataSource == null ?
- null :
- abstractDataSource.getDataSource();
- }
- }
代碼片段2.3 手動讀取配置文件初始化連接池
第37行中調用了類com.alibaba.druid.pool.DruidDataSourceFactory中createDataSource方法來初始化一個連接池。對比dbcp的使用方法,兩者很相似。
下面給出一個多線程的測試程序。運行后可以比較druid和dbcp的性能差別。
- package com.whyun.druid.test;
- import java.sql.SQLException;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.concurrent.Callable;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import java.util.concurrent.Future;
- import java.util.concurrent.TimeUnit;
- import com.whyun.druid.model.TableOperator;
- import com.whyun.util.db.DataSourceUtil;
- public class MutilThreadTest {
- public static void test(int dbType, int times)
- throws Exception {
- int numOfThreads =Runtime.getRuntime().availableProcessors()*2;
- ExecutorService executor = Executors.newFixedThreadPool(numOfThreads);
- final TableOperator test = new TableOperator();
- // int dbType = DataSourceUtil.DRUID_MYSQL_SOURCE;
- // dbType = DataSourceUtil.DBCP_SOURCE;
- test.setDataSource(DataSourceUtil.getDataSource(dbType));
- boolean createResult = false;
- try {
- test.createTable();
- createResult = true;
- } catch (SQLException e) {
- e.printStackTrace();
- }
- if (createResult) {
- List<Future<Long>> results = new ArrayList<Future<Long>>();
- for (int i = 0; i < times; i++) {
- results.add(executor.submit(new Callable<Long>() {
- @Override
- public Long call() throws Exception {
- long begin = System.currentTimeMillis();
- try {
- test.insert();
- //insertResult = true;
- } catch (Exception e) {
- e.printStackTrace();
- }
- long end = System.currentTimeMillis();
- return end - begin;
- }
- }));
- }
- executor.shutdown();
- while(!executor.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS));
- long sum = 0;
- for (Future<Long> result : results) {
- sum += result.get();
- }
- System.out.println("---------------db type "+dbType+"------------------");
- System.out.println("number of threads :" + numOfThreads + " times:" + times);
- System.out.println("running time: " + sum + "ms");
- System.out.println("TPS: " + (double)(100000 * 1000) / (double)(sum));
- System.out.println();
- try {
- test.tearDown();
- //dropResult = true;
- } catch (Exception e) {
- e.printStackTrace();
- }
- } else {
- System.out.println("初始化數據庫失敗");
- }
- }
- public static void main (String argc[])
- throws Exception {
- test(DataSourceUtil.DBCP_SOURCE,50);
- test(DataSourceUtil.DRUID_MYSQL_SOURCE,50);
- }
- }
代碼片段2.4 連接池多線程測試程序
3 監控
3.1 web監控
druid提供了sql語句查詢時間等信息的監控功能。為了讓數據庫查詢一直運行,下面特地寫了一個ajax進行輪詢。同時,還要保證在web.xml中配置如下信息
- <servlet>
- <servlet-name>DruidStatView</servlet-name>
- <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>DruidStatView</servlet-name>
- <url-pattern>/druid/*</url-pattern>
- </servlet-mapping>
同時將ajax代碼提供如下
- function showTime() {
- var myDate = new Date();
- var timeStr = '';
- timeStr += myDate.getFullYear()+'-'; //獲取完整的年份(4位,1970-????)
- timeStr += myDate.getMonth()+'-'; //獲取當前月份(0-11,0代表1月)
- timeStr += myDate.getDate() + ' '; //獲取當前日(1-31)
- timeStr += myDate.getHours()+':'; //獲取當前小時數(0-23)
- timeStr += myDate.getMinutes()+':'; //獲取當前分鍾數(0-59)
- timeStr += myDate.getSeconds(); //獲取當前秒數(0-59)
- return timeStr
- }
- $(document).ready(function() {
- function loadDBTestMessage() {
- $.get('servlet/MysqlTestServlet',function(data) {
- if (typeof(data) != 'object') {
- data = eval('(' + data + ')');
- }
- var html = '['+showTime()+']';
- html += '創建:' + data['createResult'];
- html += '插入:' + data['insertResult'];
- html += '銷毀:' + data['dropResult'];
- html +=
- $('#message').html(html);
- });
- }
- setInterval(function() {
- loadDBTestMessage();
- }, 10000);
- });
代碼片段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的服務器的監控信息。具體配置方法如下:
- <servlet>
- <servlet-name>DruidStatView</servlet-name>
- <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>
- <init-param>
- <param-name>jmxUrl</param-name>
- <param-value>service:jmx:rmi:///jndi/rmi://localhost:9004/jmxrmi</param-value>
- </init-param>
- </servlet>
- <servlet-mapping>
- <servlet-name>DruidStatView</servlet-name>
- <url-pattern>/druid/*</url-pattern>
- </servlet-mapping>
這里連接的配置參數中多了一個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使用情況,因為這種方式查看到的數據信息更全面些。