1、引入Druid数据源依赖

  1. <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
  2. <dependency>
  3. <groupId>com.alibaba</groupId>
  4. <artifactId>druid</artifactId>
  5. <version>1.1.21</version>
  6. </dependency>

2、修改SpringBoot配置文件

  1. spring:
  2. datasource:
  3. username: root
  4. password: root
  5. url: jdbc:mysql://127.0.0.1:3306/test
  6. driver-class-name: com.mysql.cj.jdbc.Driver
  7. type: com.alibaba.druid.pool.DruidDataSource ## 引入Druid数据源
  8. ## 数据源其他配置
  9. initialSize: 5
  10. minIdle: 5
  11. maxActive: 20
  12. maxWait: 60000
  13. timeBetweenEvictionRunsMillis: 60000
  14. minEvictableIdleTimeMillis: 300000
  15. validationQuery: SELECT 1 FROM DUAL
  16. testWhileIdle: true
  17. testOnBorrow: false
  18. testOnReturn: false
  19. poolPreparedStatements: true
  20. ## 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
  21. filters: stat,wall
  22. maxPoolPreparedStatementPerConnectionSize: 20
  23. useGlobalDataSourceStat: true
  24. connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

3、编写数据源配置类

/**
* Druid数据配置类
**/
@Configuration
public class MyDruidConfiguration {

    /**
     * 配置自定义数据源
     * @return
     */
    @Bean
    // 导入配置文件的配置
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource myDruidDataSource(){
        return new DruidDataSource();
    }

    /**
     * 配置Druid的监控管理后台
     * @return
     */
    @Bean
    public ServletRegistrationBean druidServletRegistrationBean(){
        ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");

        Map<String, String> initParams = new HashMap<>();
        initParams.put("loginUsername", "admin");
        initParams.put("loginPassword", "admin");
        initParams.put("allow", ""); // 默认允许所有访问
        initParams.put("deny", "");

        bean.setInitParameters(initParams);
        return bean;
    }

    /**
     * 配置一个web监控的filter
     * @return
     */
    @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;
    }
}

4、测试

访问:http://localhost:8080/druid/,输入配置的用户名和密码即可登录Druid数据源管理后台。
image.png