spring boot 整合Druid数据库连接池

 spring Boot 自带的数据源连接有org.apache.tomcat.jdbc.pool.DataSource、HikariDataSource、BasicDataSource,但大部分项目中都是采用阿里druid,它包含一系列的监控组件,比较成熟,性能也不差。讲一下整合步骤

第一步:配置application.yml 

spring:
  datasource:
#   数据源基本配置
    username: root
    password: root
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/mytest
    type: com.alibaba.druid.pool.DruidDataSource
    schema:
      - classpath:sql/department.sql
      - classpath:sql/employee.sql
#   数据源其他配置
    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
#   配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
    

在数据源其他配置以上中的配置信息都在DataSourceProperties类中一一对应,而以下的配置字段都是DruidDataSource类中的。因此我们需要写自己的druidDataSourceAutoConfig自动配置类来引用这些属性;

第二步:编写DruidDataSourceAutoConfig类

@Configuration
public class DruidConfig {

    @ConfigurationProperties(prefix = "spring.datasource")//从全局配置类中获取属性
    @Bean
    public DataSource druid(){
        return  new DruidDataSource();
    }

    //配置Druid的监控
    //1、配置一个管理后台的Servlet
    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        Map initParams = new HashMap<>();

        initParams.put("loginUsername","admin");
        initParams.put("loginPassword","123456");
        initParams.put("allow","");//默认就是允许所有访问
        initParams.put("deny","1.1.1.1");

        bean.setInitParameters(initParams);
        return bean;
    }


    //2、配置一个web监控的filter,过滤器
    @Bean
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());

        Map initParams = new HashMap<>();
        initParams.put("exclusions","*.js,*.css,/druid/*");

        bean.setInitParameters(initParams);

        bean.setUrlPatterns(Arrays.asList("/*"));

        return  bean;
    }
}

后台登录url: http://localhost:8080/druid/login.html

spring boot 整合Druid数据库连接池_第1张图片

 

 

 

 

 

你可能感兴趣的:(java,springboot)