springboot如何配置druid数据源

**1.首先在pom文件引入druid 依赖**
	
	
		com.alibaba
		druid
		1.1.8
	
**2.配置druid相关信息**
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://3306/mybatis2?serverTimezone=Asia/Shanghai&useUnicode=yes
    username: root
    password: root
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      query-timeout: 2400
      # 初始化大小
      initialSize: 5
      # 最小
      minIdle: 5
      # 最大
      maxActive: 20
      # 连接等待时间
      maxWait: 60000
      # 检测需要关闭的空白链接
      timeBetweenEvictionRunsMillis: 60000
      # 一个连接在池中最小生存时间
      minEvictableIdleTimeMillis: 300000
      #
      validationQuery: SELECT 1
      testWhileIdle: true
      testOnBorrow: false
      testOnReturn: false
      # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
      filters: stat,wall,slf4j
      # PSCache,并且指定每个连接上PSCache的大小
      poolPreparedStatements: true
      maxPoolPreparedStatementPerConnectionSize: 20
      # 合并多个DruidDataSource的监控数据
      useGlobalDataSourceStat: true
      #  通过connectProperties属性来打开mergeSql功能;慢SQL记录
      connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

3.引入配置进行监控
@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","192.168.15.21");

        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;
    }
}
成功效果:
![登陆后查看效果](https://img-blog.csdnimg.cn/20190912175418215.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NDM1NzY0Ng==,size_16,color_FFFFFF,t_70)

你可能感兴趣的:(springboot如何配置druid数据源)