在springboot 项目中添加阿里巴巴的druid 数据连接池

在springboot 项目中添加阿里巴巴的druid 数据连接池

1.  获取 maven依赖   https://mvnrepository.com/artifact/com.alibaba/druid

<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.12</version>
</dependency>

2.在yml配置文件里添加一个spring.datasource.type= com.alibaba.druid.pool.DruidDataSource

spring:
  datasource:
    username: root
    password: root
    #mysql8版本以上的驱动包,需要指定以下时区
    url: jdbc:mysql://127.0.0.1:3306/jdbc?serverTimezone=GMT%2B8
    #mysql8版本以上指定新的驱动类
    driver-class-name: com.mysql.cj.jdbc.Driver
    #引入Druid数据源
    type: com.alibaba.druid.pool.DruidDataSource

    #   数据源其他配置, DataSourceProperties中没有相关属性,默认无法绑定
    initialSize: 8
    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,logback
    maxPoolPreparedStatementPerConnectionSize: 25
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

3.重新注入一个bean 

@Configuration
public class DruidConfig {

    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
//    这个方法名不能使用druidConfig()
    public DataSource druid() {
//        DataSource dataSource = new DruidDataSource();
//        ((DruidDataSource) dataSource).setAsyncInit(true);
//        ((DruidDataSource) dataSource).setInitialSize(5);
        return new DruidDataSource();
    }
}

4.写一个servlet

//1.配置druid的后台的servlet
    @Bean
    public ServletRegistrationBean statViewServlet() {
        ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
        Map map = new HashMap();
        map.put(StatViewServlet.PARAM_NAME_USERNAME,"root");
        map.put(StatViewServlet.PARAM_NAME_PASSWORD,"root");
        map.put(StatViewServlet.PARAM_NAME_ALLOW,"");
        map.put(StatViewServlet.PARAM_NAME_DENY,"192.168.1.9");
        bean.setInitParameters(map);

        return bean;
    }

 5.写一个拦截器

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

        bean.setFilter(new WebStatFilter());

        Map<String, String> initMap = new HashMap<>();
        //  不拦截
        initMap.put(WebStatFilter.PARAM_NAME_EXCLUSIONS, "*.css,*.js,/druid/*");
        bean.setInitParameters(initMap);
        //        拦截那些请求
        bean.setUrlPatterns(Arrays.asList("/*"));
        return bean;
    }

6.浏览器打开地址

 
发布了81 篇原创文章 · 获赞 50 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/l23456789o/article/details/100658871