SpringBoot使用Druid数据源

41次阅读

共计 1896 个字符,预计需要花费 5 分钟才能阅读完成。

结构

导包

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

如果运行出错还需要导入

 <dependency>
     <groupId>log4j</groupId>
     <artifactId>log4j</artifactId>
     <version>1.2.17</version>
 </dependency>
 

application.yml

spring:
  datasource:
    username: blog
    password: 123456
    url: jdbc:mysql://localhost:3306/blog?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    #   数据源其他配置
    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
    
    

DruidConfig


@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<String,String> initParams = new HashMap<>();

        initParams.put("loginUsername","admin");// 账号
        initParams.put("loginPassword","12345");// 密码
        initParams.put("allow","");// 默认允许所有
        initParams.put("deny","192.168.123.22");

        bean.setInitParameters(initParams);
        return bean;
    }

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

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

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

        return bean;
    }
}

打开 http://localhost:8080/druid

输入账号密码,

成功

正文完
 0