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,通过监控界面发现PSCache有缓存命中率记录,
该应该是支持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    
connectionInitSqls   物理连接初始化的时候执行的sql
exceptionSorter 根据dbType自动识别 当数据库抛出一些不可恢复的异常时,抛弃连接
filters   属性类型是字符串,通过别名的方式配置扩展插件,
常用的插件有:
监控统计用的filter:stat 
日志用的filter:log4j
 防御sql注入的filter:wall
proxyFilters   类型是List<com.alibaba.druid.filter.Filter>,
如果同时配置了filters和proxyFilters,
是组合关系,并非替换关系

表1.1 配置属性

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

  1. url:jdbc:mysql://localhost:3306/dragoon_v25_masterdb
  2. driverClassName:com.mysql.jdbc.Driver
  3. username:root
  4. password:aaaaaaaa
  5. filters:stat
  6. maxActive:20
  7. initialSize:1
  8. maxWait:60000
  9. minIdle:10
  10. #maxIdle:15
  11. timeBetweenEvictionRunsMillis:60000
  12. minEvictableIdleTimeMillis:300000
  13. validationQuery:SELECT 'x'
  14. testWhileIdle:true
  15. testOnBorrow:false
  16. testOnReturn:false
  17. #poolPreparedStatements:true
  18. maxOpenPreparedStatements:20
  19. #对于长时间不使用的连接强制关闭
  20. removeAbandoned:true
  21. #超过30分钟开始关闭空闲连接
  22. removeAbandonedTimeout:1800
  23. #将当前关闭动作记录到日志
  24. logAbandoned:true

配置文件1.1 

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

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

2 代码编写

2.1 使用spring

首先给出spring配置文件

  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. <property name="maxActive" value="${maxActive}" />
  24. <property name="initialSize" value="${initialSize}" />
  25. <property name="maxWait" value="${maxWait}" />
  26. <property name="minIdle" value="${minIdle}" />
  27. <property name="timeBetweenEvictionRunsMillis" value="${timeBetweenEvictionRunsMillis}" />
  28. <property name="minEvictableIdleTimeMillis" value="${minEvictableIdleTimeMillis}" />
  29. <property name="validationQuery" value="${validationQuery}" />
  30. <property name="testWhileIdle" value="${testWhileIdle}" />
  31. <property name="testOnBorrow" value="${testOnBorrow}" />
  32. <property name="testOnReturn" value="${testOnReturn}" />
  33. <property name="maxOpenPreparedStatements"
  34. value="${maxOpenPreparedStatements}" />
  35. <property name="removeAbandoned" value="${removeAbandoned}" /> <!-- 打开removeAbandoned功能 -->
  36. <property name="removeAbandonedTimeout" value="${removeAbandonedTimeout}" /> <!-- 1800秒,也就是30分钟 -->
  37. <property name="logAbandoned" value="${logAbandoned}" /> <!-- 关闭abanded连接时输出错误日志 -->
  38. </bean>
  39. <bean id="dataSourceDbcp" class="org.apache.commons.dbcp.BasicDataSource"
  40. destroy-method="close">
  41. <property name="driverClassName" value="${driverClassName}" />
  42. <property name="url" value="${url}" />
  43. <property name="username" value="${username}" />
  44. <property name="password" value="${password}" />
  45. <property name="maxActive" value="${maxActive}" />
  46. <property name="minIdle" value="${minIdle}" />
  47. <property name="maxWait" value="${maxWait}" />
  48. <property name="defaultAutoCommit" value="true" />
  49. <property name="timeBetweenEvictionRunsMillis" value="${timeBetweenEvictionRunsMillis}" />
  50. <property name="minEvictableIdleTimeMillis" value="${minEvictableIdleTimeMillis}" />
  51. <property name="validationQuery" value="${validationQuery}" />
  52. <property name="testWhileIdle" value="${testWhileIdle}" />
  53. <property name="testOnBorrow" value="${testOnBorrow}" />
  54. <property name="testOnReturn" value="${testOnReturn}" />
  55. <property name="maxOpenPreparedStatements"
  56. value="${maxOpenPreparedStatements}" />
  57. <property name="removeAbandoned" value="${removeAbandoned}" />
  58. <property name="removeAbandonedTimeout" value="${removeAbandonedTimeout}" />
  59. <property name="logAbandoned" value="${logAbandoned}" />
  60. </bean>
  61. <!-- jdbcTemplate -->
  62. <bean id="jdbc" class="org.springframework.jdbc.core.JdbcTemplate">
  63. <property name="dataSource">
  64. <ref bean="dataSource" />
  65. </property>
  66. </bean>
  67. <bean id="SpringTableOperatorBean" class="com.whyun.druid.model.TableOperator"
  68. scope="prototype">
  69. <property name="dataSource">
  70. <ref bean="dataSource" />
  71. </property>
  72. </bean>
  73. </beans>

配置文件2.1

其中第一个bean中给出的配置文件/WEB-INF/classes/dbconfig.properties就是第1节中给出的配置文件。我这里还特地给出dbcp的spring配置项,目的就是将两者进行对比,方便大家进行迁移。这里没有使用JdbcTemplate,所以jdbc那个bean没有使用到。下面给出com.whyun.druid.model.TableOperator类的代码。

  1. package com.whyun.druid.model;
  2. import java.sql.Connection;
  3. import java.sql.PreparedStatement;
  4. import java.sql.SQLException;
  5. import java.sql.Statement;
  6. import javax.sql.DataSource;
  7. public class TableOperator {
  8. private DataSource dataSource;
  9. public void setDataSource(DataSource dataSource) {
  10. this.dataSource = dataSource;
  11. }
  12. private static final int COUNT = 800;
  13. public TableOperator() {
  14. }
  15. public void tearDown() throws Exception {
  16. try {
  17. dropTable();
  18. } catch (SQLException e) {
  19. e.printStackTrace();
  20. }
  21. }
  22. public void insert() throws Exception {
  23. StringBuffer ddl = new StringBuffer();
  24. ddl.append("INSERT INTO t_big (");
  25. for (int i = 0; i < COUNT; ++i) {
  26. if (i != 0) {
  27. ddl.append(", ");
  28. }
  29. ddl.append("F" + i);
  30. }
  31. ddl.append(") VALUES (");
  32. for (int i = 0; i < COUNT; ++i) {
  33. if (i != 0) {
  34. ddl.append(", ");
  35. }
  36. ddl.append("?");
  37. }
  38. ddl.append(")");
  39. Connection conn = dataSource.getConnection();
  40. //        System.out.println(ddl.toString());
  41. PreparedStatement stmt = conn.prepareStatement(ddl.toString());
  42. for (int i = 0; i < COUNT; ++i) {
  43. stmt.setInt(i + 1, i);
  44. }
  45. stmt.execute();
  46. stmt.close();
  47. conn.close();
  48. }
  49. private void dropTable() throws SQLException {
  50. Connection conn = dataSource.getConnection();
  51. Statement stmt = conn.createStatement();
  52. stmt.execute("DROP TABLE t_big");
  53. stmt.close();
  54. conn.close();
  55. }
  56. public void createTable() throws SQLException {
  57. StringBuffer ddl = new StringBuffer();
  58. ddl.append("CREATE TABLE t_big (FID INT AUTO_INCREMENT PRIMARY KEY ");
  59. for (int i = 0; i < COUNT; ++i) {
  60. ddl.append(", ");
  61. ddl.append("F" + i);
  62. ddl.append(" BIGINT NULL");
  63. }
  64. ddl.append(")");
  65. Connection conn = dataSource.getConnection();
  66. Statement stmt = conn.createStatement();
  67. stmt.execute(ddl.toString());
  68. stmt.close();
  69. conn.close();
  70. }
  71. }

代码片段2.1

注意:在使用的时候,通过获取完Connection对象,在使用完之后,要将其close掉,这样其实是将用完的连接放入到连接池中,如果你不close的话,会造成连接泄露。

然后我们写一个servlet来测试他.

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

代码片段2.2

这里没有用到struts2或者springmvc,虽然大部分开发者用的是这两种框架。

2.2 不使用spring

类似于dbcp,druid也提供了原生态的支持。这里仅仅列出来了如何获取一个DataSource对象,实际使用中要将获取DataSource的过程封装到一个单体模式类中。先看下面这段代码:

  1. package com.whyun.util.db;
  2. import javax.sql.DataSource;
  3. import org.apache.commons.dbcp.BasicDataSourceFactory;
  4. import com.alibaba.druid.pool.DruidDataSourceFactory;
  5. import com.whyun.util.config.MySqlConfigProperty;
  6. import com.whyun.util.config.MySqlConfigProperty2;
  7. import com.whyun.util.db.source.AbstractDataSource;
  8. import com.whyun.util.db.source.impl.DbcpSourceMysql;
  9. import com.whyun.util.db.source.impl.DruidSourceMysql;
  10. import com.whyun.util.db.source.impl.DruidSourceMysql2;
  11. // TODO: Auto-generated Javadoc
  12. /**
  13. * The Class DataSourceUtil.
  14. */
  15. public class DataSourceUtil {
  16. /** 使用配置文件dbconfig.properties构建Druid数据源. */
  17. public static final int DRUID_MYSQL_SOURCE = 0;
  18. /** The duird mysql source. */
  19. private static DataSource duirdMysqlSource;
  20. /** 使用配置文件dbconfig2.properties构建Druid数据源. */
  21. public static final int DRUID_MYSQL_SOURCE2 = 1;
  22. /** The druid mysql source2. */
  23. private static DataSource druidMysqlSource2;
  24. /** 使用配置文件dbconfig.properties构建Dbcp数据源. */
  25. public static final int DBCP_SOURCE = 4;
  26. /** The dbcp source. */
  27. private static  DataSource dbcpSource;
  28. /**
  29. * 根据类型获取数据源.
  30. *
  31. * @param sourceType 数据源类型
  32. * @return druid或者dbcp数据源
  33. * @throws Exception the exception
  34. * @NotThreadSafe
  35. */
  36. public static final DataSource getDataSource(int sourceType)
  37. throws Exception {
  38. DataSource dataSource = null;
  39. switch(sourceType) {
  40. case DRUID_MYSQL_SOURCE:
  41. if (duirdMysqlSource == null) {
  42. duirdMysqlSource = DruidDataSourceFactory.createDataSource(
  43. MySqlConfigProperty.getInstance().getProperties());
  44. }
  45. dataSource = duirdMysqlSource;
  46. break;
  47. case DRUID_MYSQL_SOURCE2:
  48. if (druidMysqlSource2 == null) {
  49. druidMysqlSource2 = DruidDataSourceFactory.createDataSource(
  50. MySqlConfigProperty2.getInstance().getProperties());
  51. }
  52. dataSource = druidMysqlSource2;
  53. break;
  54. case DBCP_SOURCE:
  55. if (dbcpSource == null) {
  56. dbcpSource = BasicDataSourceFactory.createDataSource(
  57. MySqlConfigProperty.getInstance().getProperties());
  58. }
  59. dataSource = dbcpSource;
  60. break;
  61. }
  62. return dataSource;
  63. }
  64. /**
  65. * 根据数据库类型标示获取DataSource对象,跟{@link com.whyun.util.db.DataSourceUtil#getDataSource(int)}
  66. * 不同的是,这里DataSource获取的时候使用了单体模式
  67. *
  68. * @param sourceType 数据源类型
  69. * @return 获取到的DataSource对象
  70. * @throws Exception the exception
  71. */
  72. public static final DataSource getDataSource2(int sourceType) throws Exception {
  73. AbstractDataSource abstractDataSource = null;
  74. switch(sourceType) {
  75. case DRUID_MYSQL_SOURCE:
  76. abstractDataSource = DruidSourceMysql.getInstance();
  77. break;
  78. case DRUID_MYSQL_SOURCE2:
  79. abstractDataSource = DruidSourceMysql2.getInstance();
  80. break;
  81. case DBCP_SOURCE:
  82. abstractDataSource = DbcpSourceMysql.getInstance();
  83. break;
  84. }
  85. return abstractDataSource == null ?
  86. null :
  87. abstractDataSource.getDataSource();
  88. }
  89. }

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

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

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

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

代码片段2.4 连接池多线程测试程序

 

3 监控

3.1 web监控

druid提供了sql语句查询时间等信息的监控功能。为了让数据库查询一直运行,下面特地写了一个ajax进行轮询。同时,还要保证在web.xml中配置如下信息

  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代码提供如下

  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. setInterval(function() {
  27. loadDBTestMessage();
  28. }, 10000);
  29. });

代码片段3.1 ajax轮询

这时打开http://localhost/druid-web/druid/ 地址,会看到监控界面,点击其中的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,>1000,5个时间分布区域,单位为ms

ExecRsHisto

当前sql做execute操作和resultSet

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

同上

FetchRowHisto

当前sql查询时间分布数组

同上

UpdateHisto

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

同上

表3.1 监控字段含义

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

  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使用情况,因为这种方式查看到的数据信息更全面些。

druid配置(转)的更多相关文章

  1. druid配置数据库连接使用密文密码

    spring使用druid配置dataSource片段代码 dataSource配置 <!-- 基于Druid数据库链接池的数据源配置 --> <bean id="data ...

  2. JNDI学习总结(三)——Tomcat下使用Druid配置JNDI数据源

    com.alibaba.druid.pool.DruidDataSourceFactory实现了javax.naming.spi.ObjectFactory,可以作为JNDI数据源来配置. 一.下载D ...

  3. Tomcat下使用Druid配置JNDI数据源

    com.alibaba.druid.pool.DruidDataSourceFactory实现了javax.naming.spi.ObjectFactory,可以作为JNDI数据源来配置. 一.下载D ...

  4. Druid 配置及内置监控,Web页面查看监控内容 【我改】

    转: Druid 配置及内置监控,Web页面查看监控内容 1.配置Druid的内置监控 首先在Maven项目的pom.xml中引入包 1 2 3 4 5 <dependency>      ...

  5. SpringBoot入门之基于Druid配置Mybatis多数据源

    上一篇了解了Druid进行配置连接池的监控和慢sql处理,这篇了解下使用基于基于Druid配置Mybatis多数据源.SpringBoot默认配置数据库连接信息时只需设置url等属性信息就可以了,Sp ...

  6. 数据库连接池----Druid配置详解

    什么是连接池? 数据库连接池出现的原因在数据库连接资源的低效管理,使用数据库连接池是基于设计模式中的资源池的概念,从而解决资源频繁是分配.释放所造成的问题. 数据库连接池的基本思想就是为数据库连接建立 ...

  7. SpringBoot17 FastJson配置、Druid配置

    1 FastJson配置 1.1 FastJson基础知识 点击前往 1.2 SpringBoot整合FastJson 点击前往 1.2.1 导入FastJson依赖 <!--fastjson- ...

  8. JNDI学习总结(4)——Tomcat下使用Druid配置JNDI数据源

    com.alibaba.druid.pool.DruidDataSourceFactory实现了javax.naming.spi.ObjectFactory,可以作为JNDI数据源来配置. 一.下载D ...

  9. SpringBoot系列之集成Druid配置数据源监控

    SpringBoot系列之集成Druid配置数据源监控 继上一篇博客SpringBoot系列之JDBC数据访问之后,本博客再介绍数据库连接池框架Druid的使用 实验环境准备: Maven Intel ...

  10. Spring Boot整合Druid配置多数据源

    Druid是阿里开发的数据库连接池,功能强大,号称Java语言中最好的数据库连接池.本文主要介绍Srping Boot下用Druid配置多个数据源,demo环境为:Spring Boot 2.1.4. ...

随机推荐

  1. java Reference(摘录)

    Java中的Reference对象和GC是紧密联系在一起的,Reference的实现也是和GC相关的. 强引用 强引用是Java中使用最普遍的引用,我们经常使用的Object o = new Obje ...

  2. cocos2dx 文件处理

    问题1:fopen 在vs下使用fopen进行文件处理,跑通了,但是移植到android源码下时就出现了一大推问题,首先需要理解的是在vs下开发资源是存放在执行文件的相同目录下的,而移植到androi ...

  3. WPF – 使用触发器

    WPF – 使用触发器 WPF提供了很重要的一个东西就是绑定Binding, 它帮助我们做了很多事情,这个我们在WPF学习之绑定这篇里边有讲过.对于Binding我们可以设置其绑定对象,关系,并通过某 ...

  4. 使用SBT构建Scala项目

    既然决定要在Scala上下功夫,那就要下的彻底.我们入乡随俗,学一下SBT.sbt使用ivy作为库管理工具.ivy默认把library repository建在user home下面. 安装SBT 在 ...

  5. mysql 1067 进程意外终止 无法启动

    查看日志 data/XXX.err 发现如下错误 [ERROR] InnoDB: Attempted to open a previously opened tablespace. Previous ...

  6. asp.net中WebForm.aspx与类文件分离使用

    第一步:新建一个web项目和类库,新建一个页面和映射类文件: 第二步:在页面中,删除默认映射类,添加服务器控件. 1.更改映射类命名空间: 原: <%@ Page Language=" ...

  7. 【转】发布iOS应用程序到苹果APP STORE完整流程

    原文: http://www.cnblogs.com/JuneWang/p/3850859.html 可以为每个app上传5张截图,虽然至少需要上传一张,可能很少有人会只上传一张图片.另外,你还需要分 ...

  8. Zend Studio 11.0.2 破解和汉化

    本方法适用于Zend Studio 11.0.2,亲测,其他版本未知. 破解方法:覆盖安装目录 plugins 里同名文件,启动任意输入即可注册. Windows版下载地址:http://downlo ...

  9. js学习--DOM操作详解大全 前奏(认识DOM)

    一 . 节点属性 DOM 是树型结构,相应的,可以通过一些节点属性来遍历节点树: 方法 说明 nodeName 节点名称,相当于tagName.属性节点返回属性名,文本节点返回#text.nodeNa ...

  10. TensorFlow和最近发布的slim

    笔者将和大家分享一个结合了TensorFlow和最近发布的slim库的小应用,来实现图像分类.图像标注以及图像分割的任务,围绕着slim展开,包括其理论知识和应用场景. 之前自己尝试过许多其它的库,比 ...