Druid是Java语言中最好的数据库连接池,并且能够提供强大的监控和扩展功能。
Spring Boot默认的数据源是:org.apache.tomcat.jdbc.pool.DataSource


如何在 spring Boot 中配置使用Druid,整体步骤:
(1)    ——   Druid简单介绍,具体看官网;
(2)     —— 在pom.xml配置druid依赖包;
(3)    ——  配置application.properties加入数据库源类型等参数;
(4)     —— 编写druid servlet和filter提供监控页面访问;
(5)     —— 输入地址进行测试; 

具体:

(1)添加Maven依赖 (或jar包)

<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>druid</artifactId>
	<version>1.0.18</version>
</dependency>

(2)、配置数据源相关信息(application.properties)

# 数据库访问配置
# 主数据源,默认的
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456

# 下面为连接池的补充设置,应用到上面所有数据源中
# 初始化大小,最小,最大
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
# 打开PSCache,并且指定每个连接上PSCache的大小
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
spring.datasource.filters=stat,wall,log4j
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# 合并多个DruidDataSource的监控数据
#spring.datasource.useGlobalDataSourceStat=true  

(3) 配置监控统计功能,使用代码注册Servlet

/**
     * 注册一个StatViewServlet
     * @return
     */
    @Bean
    public ServletRegistrationBean druidStatViewServle(){
        //org.springframework.boot.context.embedded.ServletRegistrationBean提供类的进行注册.
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
        //添加初始化参数:initParams
        //白名单:
        servletRegistrationBean.addInitParameter("allow","127.0.0.1");
        //IP黑名单 (存在共同时,deny优先于allow) : 如果满足deny的话提示:Sorry, you are not permitted to view this page.
        servletRegistrationBean.addInitParameter("deny","192.168.1.11");
        //登录查看信息的账号密码.
        servletRegistrationBean.addInitParameter("loginUsername","admin");
        servletRegistrationBean.addInitParameter("loginPassword","123456");
        //是否能够重置数据.
        servletRegistrationBean.addInitParameter("resetEnable","false");
        return servletRegistrationBean;
    }

    /**
     * 注册一个:filterRegistrationBean
     * @return
     */
    @Bean
    public FilterRegistrationBean druidStatFilter(){
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
        //添加过滤规则.
        filterRegistrationBean.addUrlPatterns("/*");
        //添加不需要忽略的格式信息.
        filterRegistrationBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }


/**
     * 加载druid数据库连接池
     * @return 返回DruidDataSource对象
     */
    private DruidDataSource cfgDataSource(){
        DruidDataSource druidDs = new DruidDataSource();
        String initialSize = cfgService().get(DBConstants.DURIDINITIALSIZE);
        String minIdle = cfgService().get(DBConstants.DURIDMINIDLE);
        String maxActive = cfgService().get(DBConstants.DURIDMAXACTIVE);
        String maxWait = cfgService().get(DBConstants.DURIDMAXWAIT);
        String timeBetweenEvictionRunsMillis = cfgService().get(DBConstants.DURIDTIMEBETWEENEVICTIONRUNSMILLIS);
        String minEvictableIdleTimeMillis = cfgService().get(DBConstants.DURIDMINEVICTABLEIDLETIMEMILLIS);
        String validationQuery = cfgService().get(DBConstants.DURIDVALIDATIONQUERY);
        String testwhileIdle = cfgService().get(DBConstants.DURIDTESTWHILEIDLE);
        String testOnBorrow = cfgService().get(DBConstants.DURIDTESTONBORROW);
        String testOnReturn = cfgService().get(DBConstants.DURIDTESTONRETURN);
        String poolPreparedStatements = cfgService().get(DBConstants.DURIDPOOLPREPAREDSTATEMENTS);
        String maxPoolPreparedStatementPerConnectionSize = cfgService().get(DBConstants.DURIDMAXPOOLPREPAREDSTATEMENTPERCONNECTIONSIZE);
        String removeAbandoned = cfgService().get(DBConstants.REMOVEABANDONED);
        String removeAbandonedTimeout = cfgService().get(DBConstants.REMOVEABANDONEDTIMEOUT);
        String logAbandoned = cfgService().get(DBConstants.LOGABANDONED);
        try {
            //<!-- 配置初始化大小、最小、最大 -->
            druidDs.setInitialSize(Integer.parseInt(StringUtils.isEmpty(initialSize)?"1":initialSize));
            druidDs.setMinIdle(Integer.parseInt(StringUtils.isEmpty(minIdle)?"1":minIdle));
            druidDs.setMaxActive(Integer.parseInt(StringUtils.isEmpty(maxActive)?"20":maxActive));
            //<!-- 配置获取连接等待超时的时间 -->
            druidDs.setMaxWait(Long.parseLong(StringUtils.isEmpty(maxWait)?"60000":maxWait));
            //<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
            druidDs.setTimeBetweenEvictionRunsMillis(Long.parseLong(StringUtils.isEmpty(timeBetweenEvictionRunsMillis)?"60000":timeBetweenEvictionRunsMillis));
            //<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
            druidDs.setMinEvictableIdleTimeMillis(Long.parseLong(StringUtils.isEmpty(minEvictableIdleTimeMillis)?"300000":minEvictableIdleTimeMillis));
            druidDs.setValidationQuery(StringUtils.isEmpty(validationQuery)?"select 'x'":validationQuery);
            druidDs.setTestWhileIdle(Boolean.parseBoolean(StringUtils.isEmpty(testwhileIdle)?"true":testwhileIdle));
            druidDs.setTestOnBorrow(Boolean.parseBoolean(StringUtils.isEmpty(testOnBorrow)?"false":testOnBorrow));
            druidDs.setTestOnReturn(Boolean.parseBoolean(StringUtils.isEmpty(testOnReturn)?"false":testOnReturn));
            //<!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
            druidDs.setPoolPreparedStatements(Boolean.parseBoolean(StringUtils.isEmpty(poolPreparedStatements)?"true":poolPreparedStatements));
            druidDs.setMaxPoolPreparedStatementPerConnectionSize(Integer.parseInt(StringUtils.isEmpty(maxPoolPreparedStatementPerConnectionSize)?"20":maxPoolPreparedStatementPerConnectionSize));
            //
            druidDs.setRemoveAbandoned(Boolean.parseBoolean(StringUtils.isEmpty(removeAbandoned)?"true":removeAbandoned));
            druidDs.setRemoveAbandonedTimeout(Integer.parseInt(StringUtils.isEmpty(removeAbandonedTimeout)?"180":removeAbandonedTimeout));
            druidDs.setLogAbandoned(Boolean.parseBoolean(StringUtils.isEmpty(logAbandoned)?"true":logAbandoned));
            //<!-- 配置监控统计拦截的filters,去掉后监控界面sql无法统计 -->
            druidDs.setFilters("stat,log4j");
        } catch (SQLException e) {
            LogUtils.warn("加载 druid数据源监控服务异常:" + e.getMessage(), e);
        }
        return druidDs;
    }

(4) 访问验证

启动应用就可以访问:http://127.0.0.1:8080/druid

输入账号和密码:admin/123456 就可以访问了,如下图示:




GitHub 加速计划 / druid / druid
27.83 K
8.56 K
下载
阿里云计算平台DataWorks(https://help.aliyun.com/document_detail/137663.html) 团队出品,为监控而生的数据库连接池
最近提交(Master分支:3 个月前 )
f060c270 - 12 天前
1613a765 * Improve gaussdb ddl parser * fix temp table 14 天前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐