Druid数据库连接池

spring:
  datasource:
    username: root
    password: 19990802
    url: jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
#   type可以指定数据源类型
    #Spring Boot 默认是不注入这些属性值的,需要自己绑定
    #druid 数据源专有配置

    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,stat:监控统计、log4j:日志记录、wall:防御sql注入
    #如果允许时报错  java.lang.ClassNotFoundException: org.apache.log4j.Priority
    #则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500



package com.cheng.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.HashMap;

@Configuration
public class DruidConfig {

    @Bean
    @ConfigurationProperties(prefix ="spring.datasource")//和配置文件绑定
    public DataSource druidDataSource(){
        return new DruidDataSource();
    }
    //获取后台监控
    @Bean
    //由于 SpringBoot 默认是以 jar 包的方式启动嵌入式的 Servlet 容器来启动 SpringBoot 的 web 应用,没有 web.xml 文件。所以想用使用 Servlet 功能,就必须要借用 Spring Boot 提供的 ServletRegistrationBean 接口。
    public ServletRegistrationBean servletRegistration(){
        ServletRegistrationBean bean = new ServletRegistrationBean<>(new StatViewServlet(),"/druid/*")   //StatViewServlet用于展示Druid的统计信息
            
        //设置后台登录的账户和密码
        HashMap initParameters = new HashMap<>();

        //增加配置 登录的key是固定的
        initParameters.put("loginUsername","admin");
        initParameters.put("loginPassword","123456");

        //设置谁可以访问
        initParameters.put("allow","");//任何人都可以访问

        //设置初始化参数
        bean.setInitParameters(initParameters);

        return bean;
    }
}

 启动SpringBoot测试,访问http://localhost:8080/druid

Druid数据库连接池_第1张图片

@Bean
public FilterRegistrationBean webStartFilter(){
    FilterRegistrationBean bean = new FilterRegistrationBean();
    bean.setFilter(new WebStatFilter());

    //可以过滤的请求
    HashMap initParameters = new HashMap<>();

    //排除一些不必要的url
    initParameters.put("exclusions","*.js,*.css,/druid/*");
    
    bean.setInitParameters(initParameters);//设置初始化参数
    return bean;
}

 

你可能感兴趣的:(java)