最简单的Druid使用方式


Druid一个JDBC组件, 首先是一个数据库连接池,属于阿里巴巴众多开源项目的一个。如果想看具体的介绍请看这里:

官网介绍:http://code.alibabatech.com/wiki/display/Druid/Home

OSC介绍:http://www.oschina.net/p/druid

其他的废话不多说了,本文仅仅提供一种 未经证实但可以使用的 、基于JSP-Servlet 的最简单使用方式,以供初学者快速上手,如果有不对之处敬请指出,我及时改正!

1.首先下载开发所需的Jar包,并引入到工程里。

大家可以通过这里下载最新的版本:

http://code.alibabatech.com/wiki/display/Druid/Get+Druid

2.使用DruidDataSource 

在使用时请大家要有一个概念,那就是DruidDataSouuce其实是对javax.sql.DataSource的封装,只是功能上更强大。所以使用DruidDataSouuce javax.sql.DataSource 没有太大的区别。

既然二者在使用上区别不大,那就可以使用我们大学老师交给我们的那套知识来实现,这就是通过 单例模式 实现DAO层。

实现Druid DAO的方式之一

01 import java.io.File;
02 import java.io.FileInputStream;
03 import java.io.FileNotFoundException;
04 import java.io.IOException;
05 import java.io.InputStream;
06 import java.sql.SQLException;
07 import java.util.Properties;
08  
09 import com.alibaba.druid.pool.DruidDataSource;
10 import com.alibaba.druid.pool.DruidDataSourceFactory;
11 import com.alibaba.druid.pool.DruidPooledConnection;
12  
13 public class DbPoolConnection {
14     private static DbPoolConnection databasePool = null;
15     private static DruidDataSource dds = null;
16     static {
17         Properties properties = loadPropertyFile("db_server.properties");
18         try {
19             dds = (DruidDataSource) DruidDataSourceFactory
20                     .createDataSource(properties);
21         catch (Exception e) {
22             e.printStackTrace();
23         }
24     }
25     private DbPoolConnection() {}
26     public static synchronized DbPoolConnection getInstance() {
27         if (null == databasePool) {
28             databasePool = new DbPoolConnection();
29         }
30         return databasePool;
31     }
32     public DruidPooledConnection getConnection() throws SQLException {
33         return dds.getConnection();
34     }
35     public static Properties loadPropertyFile(String fullFile) {
36         String webRootPath = null;
37         if (null == fullFile || fullFile.equals(""))
38             throw new IllegalArgumentException(
39                     "Properties file path can not be null : " + fullFile);
40         webRootPath = DbPoolConnection.class.getClassLoader().getResource("")
41                 .getPath();
42         webRootPath = new File(webRootPath).getParent();
43         InputStream inputStream = null;
44         Properties p = null;
45         try {
46             inputStream = new FileInputStream(new File(webRootPath
47                     + File.separator + fullFile));
48             p = new Properties();
49             p.load(inputStream);
50         catch (FileNotFoundException e) {
51             throw new IllegalArgumentException("Properties file not found: "
52                     + fullFile);
53         catch (IOException e) {
54             throw new IllegalArgumentException(
55                     "Properties file can not be loading: " + fullFile);
56         finally {
57             try {
58                 if (inputStream != null)
59                     inputStream.close();
60             catch (IOException e) {
61                 e.printStackTrace();
62             }
63         }
64         return p;
65     }
66 }

    通过上面的代码可以看出Druid DAO实用了DruidDataSource的工厂模式DruidDataSourceFactory,此工厂模式极大的简化了我们实用Druid的开发过程,只需通过DruidDataSourceFactory的创建方法就可以获得DataSource实例:

1 public static DataSource createDataSource(Properties properties) throws Exception
2   {
3     return createDataSource(properties);
4   }

    在 DbPoolConnection 类中的 Properties loadPropertyFile(String fullFile) 是借鉴 JFinal 里中的方法实现的,配置文件要求放在WEB-INF目录下,db_server.properties 配置文件的配置如下:

01 driverClassName=com.mysql.jdbc.Driver
02 url=jdbc:mysql://127.0.0.1:3306/DBName
03 username=root
04 password=root
05 filters=stat
06 initialSize=2
07 maxActive=300
08 maxWait=60000
09 timeBetweenEvictionRunsMillis=60000
10 minEvictableIdleTimeMillis=300000
11 validationQuery=SELECT 1
12 testWhileIdle=true
13 testOnBorrow=false
14 testOnReturn=false
15 poolPreparedStatements=false
16 maxPoolPreparedStatementPerConnectionSize=200
    这个配置可以根据个人项目的特点进行适当修改。在使用之前,建议使用最新的 jdbc-mysql 驱动,我使用的是:mysql-connector-java-5.1.22-bin.jar  

    使用示例:

1 private void executeUpdateBySQL(String sql) throws SQLException {
2         DbPoolConnection dbp = DbPoolConnection.getInstance();
3         DruidPooledConnection con = dbp.getConnection();
4         PreparedStatement ps = con.prepareStatement(sql);
5         ps.executeUpdate();
6         ps.close();
7         con.close();
8         dbp = null;
9     }
    到此,关于Druid的简单实用说明已经OK了,这仅仅是基于最简单的 JDBC-Servlet 使用方式,基于Spring框架的我并没有涉猎,敬请有使用过的前辈进行详细说明。  

 druid数据监控

3 监控

3.1 web监控

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

[html]   view plain copy
  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
  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语句的监控数据。

表格中各项含义如下

名称

解释

备注

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 plain copy
  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://download.csdn.net/detail/yunnysunny/5144480
另外也可以访问 http://git.oschina.net/yunnysunny/druid-demo 来获取git版本库中的最新代码。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值