阿里巴巴druid数据库连接池的使用

      连接池作用,因为要频繁的连接数据库进行操作,如果每次操作数据库都先连接而后操作而后释放,频繁的进行数据库连接操作一定会占用更多的系统资源,系统响应变慢,太过浪费时间以及资源,所以引入资源池的概念,先批量创建一部分连接放在池子里,然后当有需要连接数据库时就从池子里取出一个连接,使用完再返回池子里。

现在常用的数据源插件有阿里巴巴的Druid  ,C3P0、DBCP、PROXOOL,

quartz默认使用的是c3p0的连接池,记得有篇文章测试过c3p0 ,Proxool ,Druid ,Tomcat Jdbc Pool这四种连接池的性能。
大致给出的测试数据为Druid >Tomcat Jdbc Pool >c3p0 >Proxool,以上仅供参考。

虽然Druid是数据源的后期之秀,但是它以优秀的性能以及自带的数据库监控页面迅速得到行业的认可,Druid提供了多种日志文件监控 commons-logging、log4jslf4j和logback等。

使用方式如下:1、pom文件中导入所需jar



   com.alibaba
   druid
   1.0.11

2、application.properites下增加druid连接数据库配置信息

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/tianjinb2b?useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=88888888
spring.datasource.driverClassName=com.mysql.jdbc.Driver        
# 数据库访问配置
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# 下面为连接池的补充设置,应用到上面所有数据源中
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
# 配置获取连接等待超时的时间
spring.datasource.maxWait=60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
spring.datasource.timeBetweenEvictionRunsMillis=60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
spring.datasource.filters=stat,wall,log4j
spring.datasource.logSlowSql=true

3、增加config文件用于读取配置文件中的相关信息

 
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * Created by arnold.zhu on 6/13/2017.
 */
@Configuration
public class DruidConfig {

    private Logger logger = LoggerFactory.getLogger(DruidConfig.class);

    @Value("${spring.datasource.url}")
    private String dbUrl;

    @Value("${spring.datasource.username}")
    private String username;

    @Value("${spring.datasource.password}")
    private String password;

    @Value("${spring.datasource.driver-class-name}")
    private String driverClassName;

    @Value("${spring.datasource.initialSize}")
    private int initialSize;

    @Value("${spring.datasource.minIdle}")
    private int minIdle;

    @Value("${spring.datasource.maxActive}")
    private int maxActive;

    @Value("${spring.datasource.maxWait}")
    private int maxWait;

    @Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
    private int timeBetweenEvictionRunsMillis;

    @Value("${spring.datasource.minEvictableIdleTimeMillis}")
    private int minEvictableIdleTimeMillis;

    @Value("${spring.datasource.validationQuery}")
    private String validationQuery;

    @Value("${spring.datasource.testWhileIdle}")
    private boolean testWhileIdle;

    @Value("${spring.datasource.testOnBorrow}")
    private boolean testOnBorrow;

    @Value("${spring.datasource.testOnReturn}")
    private boolean testOnReturn;

    @Value("${spring.datasource.filters}")
    private String filters;

    @Value("${spring.datasource.logSlowSql}")
    private String logSlowSql;

    @Bean
    public ServletRegistrationBean druidServlet() {
        ServletRegistrationBean reg = new ServletRegistrationBean();
        reg.setServlet(new StatViewServlet());
        reg.addUrlMappings("/druid/*");
        reg.addInitParameter("loginUsername", username);
        reg.addInitParameter("loginPassword", password);
        reg.addInitParameter("logSlowSql", logSlowSql);
        return reg;
    }

    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new WebStatFilter());
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        filterRegistrationBean.addInitParameter("profileEnable", "true");
        return filterRegistrationBean;
    }

    @Bean
    public DataSource druidDataSource() {
        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(dbUrl);
        datasource.setUsername(username);
        datasource.setPassword(password);
        datasource.setDriverClassName(driverClassName);
        datasource.setInitialSize(initialSize);
        datasource.setMinIdle(minIdle);
        datasource.setMaxActive(maxActive);
        datasource.setMaxWait(maxWait);
        datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
        datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
        datasource.setValidationQuery(validationQuery);
        datasource.setTestWhileIdle(testWhileIdle);
        datasource.setTestOnBorrow(testOnBorrow);
        datasource.setTestOnReturn(testOnReturn);
        try {
            datasource.setFilters(filters);
        } catch (SQLException e) {
            logger.error("druid configuration initialization filter", e);
        }
        return datasource;
    }

}

 

4、到这里,就可以使用http://localhost:8082/druid/login.html,用户名密码默认为数据库用户名密码,即可登录到监控页阿里巴巴druid数据库连接池的使用_第1张图片

 

监控页面

阿里巴巴druid数据库连接池的使用_第2张图片

 

这时虽然可以使用druid的监控功能,但是这里会涉及到一些私密信息,所以为了确保安全需要增加配置新的用户名和密码

 
增加如下代码,设置新的用户名密码即可
@Bean
public ServletRegistrationBean druidServlet() {
    ServletRegistrationBean reg = new ServletRegistrationBean();
    reg.setServlet(new StatViewServlet());
    reg.addUrlMappings("/druid/*");
    reg.addInitParameter("loginUsername", username);
    reg.addInitParameter("loginPassword", password);
    reg.addInitParameter("logSlowSql", logSlowSql);
    reg.setServlet(new StatViewServlet());
    Map initParameters = new HashMap<>();
    initParameters.put("resetEnable", "false"); //禁用HTML页面上的“Rest All”功能
    //initParameters.put("allow", "10.8.9.115");  //ip白名单(没有配置或者为空,则允许所有访问)
    initParameters.put("loginUsername", "admin");  //监控页面登录用户名
    initParameters.put("loginPassword", "admin");  //监控页面登录用户密码
    initParameters.put("deny", "127.0.0.1"); //ip黑名单
    initParameters.put("deny", "10.16.169.36"); //ip黑名单
    //如果某个ip同时存在,deny优先于allow
    reg.setInitParameters(initParameters);
    return reg;
}
 

 

 

你可能感兴趣的:(阿里巴巴druid数据库连接池的使用)