JSP(非框架)+Druid简单的数据库连接池入门

Druid是什么?有什么作用?

Druid首先是一个数据库连接池,但它不仅仅是一个数据库连接池,它还包含一个ProxyDriver,一系列内置的JDBC组件库,一个SQLParser。 Druid的项目背景?目前的项目团队情况?开源目的?
2010年开始,阿里某大佬负责设计一个叫做Dragoon的监控系统,需要一些监控组件,监控应用程序的运行情况,包括WebURI、Spring、JDBC等。

其他的废话不多说了,本文仅仅提供一种可以使用的 、基于JSP-Servlet 的最简单使用方式!

1.首先下载开发所需的Jar包,并引入到工程里。(我的版本是druid-1.1.9.jar)**

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

http://repo1.maven.org/maven2/com/alibaba/druid/

2.使用DruidDataSource(新建一个类)**

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

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

实现Druid DAO的方式之一(这里面有个坑–配置文件的路径,具体可以自己逐行DEBUG尝试

package com.jdbc;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.Properties;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.pool.DruidPooledConnection;

/*
加载,链接druid,初始化数据库连接池
 */
public class DbPoolConnection {
    private static DbPoolConnection databasePool = null;
    private static DruidDataSource dds = null;
    static {
        Properties properties = loadPropertyFile("db_server.properties");
        try {
            dds = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private DbPoolConnection() {}
    public static synchronized DbPoolConnection getInstance() {
        if (null == databasePool) {
            databasePool = new DbPoolConnection();
        }
        return databasePool;
    }
    public DruidPooledConnection getConnection() throws SQLException {
        return dds.getConnection();
    }
    public static Properties loadPropertyFile(String fullFile) {

        if (null == fullFile || fullFile.equals("")) throw new IllegalArgumentException("Properties file path can not be null : " + fullFile);
        File webRootPath= new File(DbPoolConnection.class.getResource("").getPath());
        InputStream inputStream = null;
        Properties p = null;
        try {
            inputStream = new FileInputStream(new File(webRootPath
                    + File.separator + fullFile));
            p = new Properties();
            p.load(inputStream);
        } catch (FileNotFoundException e) {
            throw new IllegalArgumentException("Properties file not found: " + fullFile);
        } catch (IOException e) {
            throw new IllegalArgumentException("Properties file can not be loading: " + fullFile);
        } finally {
            try {
                if (inputStream != null)
                    inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return p;
    }
}

3.创建配置文件** - 在 DbPoolConnection 类中的 Properties loadPropertyFile(String fullFile) 是借鉴 JFinal 里中的方法实现的,配置文件放在当前类同级目录下,db_server.properties 配置文件的配置如下:

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/XXX
username=root
password=****(填自己的)
filters=stat
initialSize=2
maxActive=300
maxWait=60000
timeBetweenEvictionRunsMillis=60000
minEvictableIdleTimeMillis=300000
validationQuery=SELECT 1
testWhileIdle=true
testOnBorrow=false
testOnReturn=false
poolPreparedStatements=false
maxPoolPreparedStatementPerConnectionSize=200
这个配置可以根据个人项目的特点进行适当修改。在使用之前,建议使用最新的 jdbc-mysql 驱动,我使用的是:mysql-connector-java-5.1.22-bin.jar

4.测试数据库连接池(新建一个类)** -

package com.test;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.alibaba.druid.pool.GetConnectionTimeoutException;
import com.jdbc.DbPoolConnection;

import java.sql.PreparedStatement;
import java.sql.SQLException;


public class druid_test {
    private static void executeUpdateBySQL(String sql) throws SQLException {
        DbPoolConnection dbp = DbPoolConnection.getInstance();
        DruidPooledConnection con = dbp.getConnection();
        PreparedStatement ps = con.prepareStatement(sql);
        try{
            con=dbp.getConnection();
            ps=con.prepareStatement(sql);
            ps.executeUpdate();
        }catch (GetConnectionTimeoutException e){
            throw new IllegalArgumentException("数据库连接异常");
        }
        finally {
            if(ps!=null)
                try {
                ps.close();
                System.out.println("ps is close");
                }catch (SQLException e1){
                System.out.println("ps close is error");
                }
              if(con!=null)
                  try {
                con.close();
                System.out.println("con is close");
                  }catch (SQLException e){
                System.out.println("con close is error");
                  }
        }

    }
    public static void main(String []args) throws SQLException {
        String sql="insert into hh values('2','2')";
        executeUpdateBySQL(sql);
    }
}
OK,到这里,已经完成了druid的基本入门内容了,其实很简单,和JDBC差不多,都是先加载配置文件,然后初始化一个数据库连接池,然后连接和操作SQL语句** ————————————————————————————

进阶版

和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 配置属性

加入 druid-1.0.9.jar

ApplicationContext.xml

< bean name = "transactionManager" class ="org.springframework.jdbc.datasource.DataSourceTransactionManager" >   
    < property name = "dataSource" ref = "dataSource" ></ property >
     </ bean >
    < bean id = "propertyConfigurer" class ="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" >  
       < property name = "locations" >  
           < list >  
                 < value > /WEB-INF/classes/dbconfig.properties </ value >  
            </ list >  
        </ property >  
    </ bean >
ApplicationContext.xml配置druid

  <!-- 阿里 druid 数据库连接池 -->
    < 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}" />
         <!-- 打开 removeAbandoned 功能 -->
         < property name = "removeAbandoned" value = "${removeAbandoned}" />
         <!-- 1800 秒,也就是 30 分钟 -->
         < property name = "removeAbandonedTimeout" value ="${removeAbandonedTimeout}" />
         <!-- 关闭 abanded 连接时输出错误日志 -->   
         < property name = "logAbandoned" value = "${logAbandoned}" />
    </ bean >

dbconfig.properties

url: jdbc:mysql:// localhost :3306/ newm
driverClassName: com.mysql.jdbc.Driver
username: root
password: root
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
maxOpenPreparedStatements: 20
removeAbandoned: true
removeAbandonedTimeout: 1800
logAbandoned: true

web.xml

  <!-- 连接池 启用 Web 监控统计功能    start-->
    < filter >
       < filter-name > DruidWebStatFilter </ filter-name >
       < filter-class > com.alibaba.druid.support.http.WebStatFilter </ filter-class >
       < init-param >
           < param-name > exclusions </ param-name >
           < param-value > *. js ,*. gif ,*. jpg ,*. png ,*. css ,*. ico ,/ druid /* </ param-value >
       </ init-param >
    </ filter >
    < filter-mapping >
       < filter-name > DruidWebStatFilter </ filter-name >
       < url-pattern > /* </ url-pattern >
    </ filter-mapping >
    < 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 >
    <!-- 连接池 启用 Web 监控统计功能    end-->

访问监控页面: http://ip:port/projectName/druid/index.html
参考博文: https://blog.csdn.net/hj7jay/article/details/51686418
http://www.codeweblog.com/%E6%9C%80%E7%AE%80%E5%8D%95%E7%9A%84druid%E4%BD%BF%E7%94%A8%E6%96%B9%E5%BC%8F

猜你喜欢

转载自blog.csdn.net/mikeoperfect/article/details/80043969