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的方式之一
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; |
09 | import com.alibaba.druid.pool.DruidDataSource; |
10 | import com.alibaba.druid.pool.DruidDataSourceFactory; |
11 | import com.alibaba.druid.pool.DruidPooledConnection; |
13 | public class DbPoolConnection
{ |
14 | private static DbPoolConnection
databasePool = null ; |
15 | private static DruidDataSource
dds = null ; |
17 | Properties
properties = loadPropertyFile( "db_server.properties" ); |
19 | dds
= (DruidDataSource) DruidDataSourceFactory |
20 | .createDataSource(properties); |
25 | private DbPoolConnection()
{} |
26 | public static synchronized DbPoolConnection
getInstance() { |
27 | if ( null ==
databasePool) { |
28 | databasePool
= new DbPoolConnection(); |
32 | public DruidPooledConnection
getConnection() throws SQLException
{ |
33 | return dds.getConnection(); |
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( "" ) |
42 | webRootPath
= new File(webRootPath).getParent(); |
43 | InputStream
inputStream = null ; |
46 | inputStream
= new FileInputStream( new File(webRootPath |
47 | +
File.separator + fullFile)); |
50 | } catch (FileNotFoundException
e) { |
51 | throw new IllegalArgumentException( "Properties
file not found: " |
53 | } catch (IOException
e) { |
54 | throw new IllegalArgumentException( |
55 | "Properties
file can not be loading: " +
fullFile); |
58 | if (inputStream
!= null ) |
60 | } catch (IOException
e) { |
通过上面的代码可以看出Druid DAO实用了DruidDataSource的工厂模式DruidDataSourceFactory,此工厂模式极大的简化了我们实用Druid的开发过程,只需通过DruidDataSourceFactory的创建方法就可以获得DataSource实例:
1 | public static DataSource
createDataSource(Properties properties) throws Exception |
3 | return createDataSource(properties); |
在 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 |
09 | timeBetweenEvictionRunsMillis= 60000 |
10 | minEvictableIdleTimeMillis= 300000 |
11 | validationQuery=SELECT 1 |
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); |
到此,关于Druid的简单实用说明已经OK了,这仅仅是基于最简单的 JDBC-Servlet 使用方式,基于Spring框架的我并没有涉猎,敬请有使用过的前辈进行详细说明。
druid数据监控
[b]3 监控[/b]
[title3]
3.1 web监控[/title3]
druid提供了sql语句查询时间等信息的监控功能。为了让数据库查询一直运行,下面特地写了一个ajax进行轮询。同时,还要保证在web.xml中配置如下信息
[html] view
plain
copy<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>
配置文件3.1 在web.xml中添加druid监控同时将ajax代码提供如下
[javascript] view
plain
copyfunction 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语句的监控数据。表格中各项含义如下
名称
| 解释
| 备注
|
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的服务器的监控信息。具体配置方法如下:
[html] view
plain
copy<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>
配置文件3.2 远程监控web
这里连接的配置参数中多了一个jmxUrl,里面配置一个jmx连接地址,如果配置了这个init-param后,那么当前web监控界面监控的就不是本机的druid的使用情况,而是jmxUrl中指定的ip的远程机器的druid使用情况。jmx连接中也可以指定用户名、密码,在上面的servlet中添加两个init-param,其param-name分别为jmxUsername和jmxPassword,分别对应连接jmx的用户名和密码。对于jmx在服务器端的配置,可以参考3.2节中的介绍。
[title3]
3.2 jconsole监控[/title3]
同时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版本库中的最新代码。