Chinaunix首页 | 论坛 | 博客
  • 博客访问: 132471
  • 博文数量: 48
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 200
  • 用 户 组: 普通用户
  • 注册时间: 2013-05-21 14:51
个人简介

天不设牢,二人自在心中舍牢。顺天而行者,心中无牢。

文章分类

全部博文(48)

文章存档

2013年(48)

我的朋友

分类: Java

2013-05-27 12:52:59

原文:http://blog.csdn.net/yunnysunny/article/details/8657095
java程序很大一部分要操作数据库,为了提高性能操作数据库的时候,有不得不使用数据库连接池。数据库连接池有很多选择,c3p、dhcp、proxool等,druid作为一名后起之秀,凭借其出色的性能,也逐渐印入了大家的眼帘。接下来本教程就说一下druid的简单使用。

 首先从 下载最新的jar包。如果想使用最新的源码编译,可以从 下载源码,然后使用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。详细看这里:
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。
在mysql下建议关闭。
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    
connectionInitSqls   物理连接初始化的时候执行的sql
exceptionSorter 根据dbType自动识别 当数据库抛出一些不可恢复的异常时,抛弃连接
filters   属性类型是字符串,通过别名的方式配置扩展插件,
常用的插件有:
监控统计用的filter:stat 
日志用的filter:log4j
 防御sql注入的filter:wall
proxyFilters   类型是List
如果同时配置了filters和proxyFilters,
是组合关系,并非替换关系
表1.1 配置属性


根据常用的配置属性,首先给出一个如下的配置文件,放置于src目录下。


[plain] view plaincopy
  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  
  23.   
  24. #对于长时间不使用的连接强制关闭  
  25. removeAbandoned:true  
  26. #超过30分钟开始关闭空闲连接  
  27. removeAbandonedTimeout:1800  
  28. #将当前关闭动作记录到日志  
  29. logAbandoned:true  


配置文件1.1 

配置项中指定了各个参数后,在连接池内部是这么使用这些参数的。数据库连接池在初始化的时候会创建initialSize个连接,当有数据库操作时,会从池中取出一个连接。如果当前池中正在使用的连接数等于maxActive,则会等待一段时间,等待其他操作释放掉某一个连接,如果这个等待时间超过了maxWait,则会报错;如果当前正在使用的连接数没有达到maxActive,则判断当前是否空闲连接,如果有则直接使用空闲连接,如果没有则新建立一个连接。在连接使用完毕后,不是将其物理连接关闭,而是将其放入池中等待其他操作复用。

同时连接池内部有机制判断,如果当前的总的连接数少于miniIdle,则会建立新的空闲连接,以保证连接数得到miniIdle。如果当前连接池中某个连接在空闲了timeBetweenEvictionRunsMillis时间后任然没有使用,则被物理性的关闭掉。有些数据库连接的时候有超时限制(mysql连接在8小时后断开),或者由于网络中断等原因,连接池的连接会出现失效的情况,这时候设置一个testWhileIdle参数为true,可以保证连接池内部定时检测连接的可用性,不可用的连接会被抛弃或者重建,最大情况的保证从连接池中得到的Connection对象是可用的。当然,为了保证绝对的可用性,你也可以使用testOnBorrow为true(即在获取Connection对象时检测其可用性),不过这样会影响性能。

2 代码编写

2.1 使用spring

首先给出spring配置文件

[html] view plaincopy
  1. xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns=""  
  3.     xmlns:xsi=""  
  4.     xsi:schemaLocation="
  5.          /spring-beans-3.0.xsd  
  6.         ">  
  7.       
  8.     <bean id="propertyConfigurer"  
  9.         class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
  10.         <property name="locations">  
  11.             <list>  
  12.                 <value>/WEB-INF/classes/dbconfig.propertiesvalue>  
  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}" />   
  39.         <property name="removeAbandonedTimeout" value="${removeAbandonedTimeout}" />   
  40.         <property name="logAbandoned" value="${logAbandoned}" />   
  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.       
  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 plaincopy
  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 plaincopy
  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. 
     
  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也提供了原生态的支持。先看下面这段代码:


[java] view plaincopy
  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.   
  11. /** 
  12.  * The Class DataSourceUtil. 
  13.  */  
  14. public class DataSourceUtil {  
  15.       
  16.     /** 使用配置文件dbconfig.properties构建Druid数据源. */  
  17.     public static final int DRUID_MYSQL_SOURCE = 0;  
  18.       
  19.     /** 使用配置文件dbconfig2.properties构建Druid数据源. */  
  20.     public static final int DRUID_MYSQL_SOURCE2 = 1;  
  21.       
  22.     /** 使用配置文件dbconfig.properties构建Dbcp数据源. */  
  23.     public static final int DBCP_SOURCE = 4;  
  24.       
  25.     /** 
  26.      * 根据类型获取数据源 
  27.      * 
  28.      * @param sourceType 数据源类型 
  29.      * @return druid或者dbcp数据源 
  30.      * @throws Exception the exception 
  31.      */  
  32.     public static final DataSource getDataSource(int sourceType)  
  33.         throws Exception {  
  34.         DataSource dataSource = null;  
  35.         switch(sourceType) {  
  36.         case DRUID_MYSQL_SOURCE:              
  37.             dataSource = DruidDataSourceFactory.createDataSource(  
  38.                     MySqlConfigProperty.getInstance().getProperties());               
  39.             break;  
  40.         case DRUID_MYSQL_SOURCE2:  
  41.             dataSource = DruidDataSourceFactory.createDataSource(  
  42.                     MySqlConfigProperty2.getInstance().getProperties());  
  43.             break;  
  44.         case DBCP_SOURCE:  
  45.             dataSource = BasicDataSourceFactory.createDataSource(  
  46.                     MySqlConfigProperty.getInstance().getProperties());  
  47.             break;  
  48.         }  
  49.         return dataSource;  
  50.     }  
  51. }  


代码片段2.3 手动读取配置文件初始化连接池


第37行中调用了类com.alibaba.druid.pool.DruidDataSourceFactory中createDataSource方法来初始化一个连接池。对比dbcp的使用方法,两者很相似。

下面给出一个多线程的测试程序。运行后可以比较druid和dbcp的性能差别。


[java] view plaincopy
  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> results = new ArrayList>();     
  34.             for (int i = 0; i < times; i++) {    
  35.                 results.add(executor.submit(new Callable() {    
  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 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 plaincopy
  1. <servlet>  
  2.         <servlet-name>DruidStatViewservlet-name>  
  3.         <servlet-class>com.alibaba.druid.support.http.StatViewServletservlet-class>  
  4.     servlet>  
  5. <servlet-mapping>  
  6.         <servlet-name>DruidStatViewservlet-name>  
  7.         <url-pattern>/druid/*url-pattern>  
  8.     servlet-mapping>  
配置文件3.1 在web.xml中添加druid监控



同时将ajax代码提供如下


[javascript] view plaincopy
  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轮询


这时打开 地址,会看到监控界面,点击其中的sql标签。

图3.1 监控界面查看sql查询时间

注意:在写配置文件1.1时,要保证filter配置项中含有stat属性,否则这个地方看不到sql语句的监控数据。

表格中各项含义如下

名称

解释

备注

ExecuteCount

当前sql已执行次数


ExecTime

当前sql已执行时间


ExecMax

当前sql最大执行时间


Txn

当前运行的事务数量


Error

当前sql执行出错的数目


Update

当前sql更新或者删除操作中已经影响的行数


FetchRow

当前sql操作中已经读取的行数


Running

当前sql正在运行的数目


Concurrent

当前sql最大并发执行数 


ExecHisto 

当前sql做execute操作的时间分布数组

分为0-1,1-10,10-100,100-1000>10005个时间分布区域,单位为ms

ExecRsHisto 

当前sql做execute操作和resultSet

打开至关闭的时间总和分布数组

同上

FetchRowHisto

当前sql查询时间分布数组

同上

UpdateHisto 

当前sql更新、删除时间分布数组

同上

表3.1 监控字段含义


老版本的druid的jar包中不支持通过web界面进行远程监控,从0.2.14开始可以通过配置jmx地址来获取远程运行druid的服务器的监控信息。具体配置方法如下:


[html] view plaincopy
  1. <servlet>  
  2.         <servlet-name>DruidStatViewservlet-name>  
  3.         <servlet-class>com.alibaba.druid.support.http.StatViewServletservlet-class>  
  4.         <init-param>  
  5.             <param-name>jmxUrlparam-name>  
  6.             <param-value>service:jmx:rmi:///jndi/rmi://localhost:9004/jmxrmiparam-value>  
  7.         init-param>  
  8.     servlet>  
  9.     <servlet-mapping>  
  10.         <servlet-name>DruidStatViewservlet-name>  
  11.         <url-pattern>/druid/*url-pattern>  
  12.     servlet-mapping>  
配置文件3.2 远程监控web


这里连接的配置参数中多了一个jmxUrl,里面配置一个jmx连接地址。jmx连接中也可以指定用户名、密码,在上面的servlet中添加两个init-param,其param-name分别为jmxUsername和jmxPassword,分别对应连接jmx的用户名和密码。对于jmx在服务器端的配置,可以参考3.2节中的介绍。

3.2 jconsole监控


同时druid提供了jconsole监控的功能,因为界面做的不是很好,所以官方中没有对其的相关介绍。如果是纯java程序的话,上面提到的web监控就无法使用了,jconsole的作用就体现出来了。不过我在下面做教程的时候,依然使用的是刚才用的web项目。

首先在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中也能适用,但是笔者在其下没有试验成功)。然后在远程的某台电脑的命令行中运行如下命令

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监控界面类似的数据了。

参考

本文章中的代码已上传:
oschina 问答社区:
阅读(2291) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~