记录SpringBoot 整合druid配置信息及过程

作为一个菜鸟新手。在学习springboot 整合druid时遇见各种坑。花了近一天时间,各种找资源找原因。终于在https://segmentfault.com/a/1190000009132815文章中得以解决。感谢该作者的分享。因此,总结下来作为作为后续参考。更多详细内容待后续研究。

第一步:添加pom依赖:(这里要添加两个依赖)

     <dependency>

         <groupId>org.springframework.boot</groupId>

         <artifactId>spring-boot-starter-data-jpa</artifactId>

    </dependency>

    <dependency>

         <groupId>com.alibaba</groupId>

         <artifactId>druid</artifactId>

        <version>1.0.20</version>

    </dependency>

 

第二步:配置application.properties文件 数据源相关信息

# mysql

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/sdfdcdb?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&useSSL=false

spring.datasource.driverClassName=com.mysql.jdbc.Driver

spring.datasource.username=root

spring.datasource.password=root

 

# DataSource

spring.datasource.initialSize=1  

spring.datasource.minIdle=1  

spring.datasource.maxActive=20  

spring.datasource.maxWait=60000  

spring.datasource.validationQuery=SELECT 1 FROM DUAL  

spring.datasource.testOnBorrow=false  

spring.datasource.testOnReturn=false  

spring.datasource.testWhileIdle=true  

spring.datasource.minEvictableIdleTimeMillis=25200000  

spring.datasource.timeBetweenEvictionRunsMillis=60000  

spring.datasource.removeAbandoned=true  

spring.datasource.removeAbandonedTimeout=1800  

spring.datasource.poolPreparedStatements=true  

spring.datasource.maxPoolPreparedStatementPerConnectionSize=20  

spring.datasource.logAbandoned=true  

spring.datasource.filters=stat,wall

 

注意:这里去掉了log4j,由于我的项目采用spring boot默认支持的日志插件,这里去掉了log4j 如果添加上,而没有配置log4j,以及添加对应依赖项目会报错

 

 

 

 

第三步:配置Druid的监控统计功能(由于我采用的是@Confing注解 配置,第二种方式基于注解的配置不做介绍)

 

package com.test.demo.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.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.context.annotation.Primary;

 

import javax.sql.DataSource;

import java.sql.SQLException;

 

import org.springframework.boot.web.servlet.FilterRegistrationBean;

import org.springframework.boot.web.servlet.ServletRegistrationBean;

@Configuration

public class DruidConfig {

 

    private static final Logger LOGGER = LoggerFactory.getLogger(DruidConfig.class);

 

    @Value("${spring.datasource.driverClassName}")

    private String driverClassName;

    @Value("${spring.datasource.url}")

    private String url;

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

    private String username;

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

    private String password;

    @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.validationQuery}")

    private String validationQuery;

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

    private boolean testOnBorrow;

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

    private boolean testOnReturn;

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

    private boolean testWhileIdle;

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

    private int timeBetweenEvictionRunsMillis;

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

    private int minEvictableIdleTimeMillis;

    @Value("${spring.datasource.removeAbandoned}")

    private boolean removeAbandoned;

    @Value("${spring.datasource.removeAbandonedTimeout}")

    private int removeAbandonedTimeout;

    @Value("${spring.datasource.logAbandoned}")

    private boolean logAbandoned;

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

    private String filters;

    @Value("${spring.datasource.poolPreparedStatements}")

    private boolean poolPreparedStatements;

    @Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")

    private int maxPoolPreparedStatementPerConnectionSize;

 

    @Bean

    @Primary

    public DataSource dataSource() {

        DruidDataSource datasource = new DruidDataSource();

 

        datasource.setDriverClassName(driverClassName);

        datasource.setUrl(url);

        datasource.setUsername(username);

        datasource.setPassword(password);

        //其它配置

        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);

        datasource.setPoolPreparedStatements(poolPreparedStatements);

        datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);

        try {

            datasource.setFilters(filters);

        } catch (SQLException e) {

            LOGGER.error("druid configuration initialization filter", e);

        }

        return datasource;

    }

 

    

    /**

     * 注册一个StatViewServlet

     * @return

     */

    @Bean

    public ServletRegistrationBean DruidStatViewServle2(){

        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");

 

        //添加初始化参数:initParams

        /** 白名单,如果不配置或value为空,则允许所有 */

        servletRegistrationBean.addInitParameter("allow","127.0.0.1,192.0.0.1");

        /** 黑名单,与白名单存在相同IP时,优先于白名单 */

        servletRegistrationBean.addInitParameter("deny","192.0.0.1");

        /** 用户名 */

        servletRegistrationBean.addInitParameter("loginUsername","admin");

        /** 密码 */

        servletRegistrationBean.addInitParameter("loginPassword","admin");

        /** 禁用页面上的“Reset All”功能 */

        servletRegistrationBean.addInitParameter("resetEnable","false");

        return servletRegistrationBean;

    }

 

    /**

     * 注册一个:WebStatFilter

     * @return

     */

    @Bean

    public FilterRegistrationBean druidStatFilter2(){

        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());

 

        /** 过滤规则 */

        filterRegistrationBean.addUrlPatterns("/*");

        /** 忽略资源 */

        filterRegistrationBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");

        return filterRegistrationBean;

    }

}

 

 

注意:该类被@Configuration标注,用作配置信息,且必须标注 DataSource对象被@Bean声明,为Spring容器所管理, @Primary表示这里定义的DataSource将覆盖其他来源的DataSource

 

等应用启动后,可以访问地址:http://localhost:8080/druid/,登录之后,即可查看数据源及SQL统计等

 

 

 

配置成功

注意:只要durid配置成功即可访问,访问地址与你配置的  ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");密切相关。


阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页