springboot整合Druid(德鲁伊)数据库连接池

方式一、直接整合

引入数据源

<!--druid -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.12</version>
</dependency>
<!-- mybatis  排除HikariCP数据源-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.1</version>
    <exclusions>
        <exclusion>
            <artifactId>HikariCP</artifactId>
            <groupId>com.zaxxer</groupId>
        </exclusion>
    </exclusions>
</dependency>

配置文件

##数据源配置
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/taotao?useUnicode=true&characterEncoding=UTF-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
#初始连接数
spring.datasource.initialSize=5
#最小连接数
spring.datasource.minIdle=5
#最大连接数
spring.datasource.maxActive=20
#配置获取连接等待超时的时间
spring.datasource.maxWait=60000
#配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
spring.datasource.timeBetweenEvictionRunsMillis=60000
#配置一个连接在池中最小生存的时间,单位是毫秒
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
spring.datasource.poolPreparedStatements=true
#配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入
#如果允许时报错  java.lang.ClassNotFoundException: org.apache.log4j.Priority
#则导入 log4j 依赖即可,Maven 地址: https://mvnrepository.com/artifact/log4j/log4j
spring.datasource.filters=stat,wall
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
spring.datasource.connectionProperties=druid.stat.mergeSql\=true;druid.stat.slowSqlMillis\=5000

配置类

现在需要程序员自己为 com.alibaba.druid.pool.DruidDataSource 绑定全局配置文件中的参数,再添加到容器中,而不再使用 Spring Boot 的自动生成了;我们需要 自己添加 DruidDataSource 组件到容器中,并绑定属性;

@Configuration
public class DruidConfig {
    /*
       将自定义的 Druid数据源添加到容器中,不再让 Spring Boot 自动创建
       绑定全局配置文件中的 druid 数据源属性到 com.alibaba.druid.pool.DruidDataSource从而让它们生效
       @ConfigurationProperties(prefix = "spring.datasource"):作用就是将全局配置文件中
       前缀为 spring.datasource的属性值注入到 com.alibaba.druid.pool.DruidDataSource 的同名参数中
     */
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druidDataSource() {
        return new DruidDataSource();
    }
}

去测试类中测试一下;看是否成功!

public class SpringbootDemoDataApplicationTests {
    //注入数据源
    @Autowired
    DataSource dataSource;
    @Test
    public void contextLoads() throws SQLException {
        //看一下默认数据源
        System.out.println(dataSource.getClass());
        //获得连接
        Connection connection =   dataSource.getConnection();
        System.out.println(connection);
        DruidDataSource druidDataSource = (DruidDataSource) dataSource;
        System.out.println("druidDataSource 数据源最大连接数:" + druidDataSource.getMaxActive());
        System.out.println("druidDataSource 数据源初始化连接数:" + druidDataSource.getInitialSize());
        //关闭连接
        connection.close();
    }
}

输出结果 :可见配置参数已经生效
在这里插入图片描述
配置 Druid 数据源监控
Druid 数据源具有监控的功能,并提供了一个 web 界面方便用户查看,类似安装路由器时,人家也提供了一个默认的web页面。
所以第一步需要设置Druid的后台管理页面,比如 登录账号、密码 等;配置后台管理;

//配置 Druid 监控管理后台的Servlet;
//内置 Servler 容器时没有web.xml文件,所以使用 Spring Boot 的注册 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", "123456"); //后台管理界面的登录密码

    //后台允许谁可以访问
    //initParams.put("allow", "localhost"):表示只有本机可以访问
    //initParams.put("allow", ""):为空或者为null时,表示允许所有访问
    initParams.put("allow", "");
    //deny:Druid 后台拒绝谁访问
    //initParams.put("kuangshen", "192.168.1.20");表示禁止此ip访问

    //设置初始化参数
    bean.setInitParameters(initParams);
    return bean;
    //这些参数可以在 com.alibaba.druid.support.http.StatViewServlet 的父类 com.alibaba.druid.support.http.ResourceServlet 中找到
}

配置完毕后,我们可以选择访问 : http://localhost:8080/druid/login.html
在这里插入图片描述
在这里插入图片描述
配置 Druid web 监控 filter
这个过滤器的作用就是统计 web 应用请求中所有的数据库信息,比如:发出的sql语句,sql执行的时间、请求次数、请求的url地址、以及seesion监控、数据库表的访问次数 等等。

//配置 Druid 监控 之  web 监控的 filter
//WebStatFilter:用于配置Web和Druid数据源之间的管理关联监控统计
 @Bean
 public FilterRegistrationBean webStatFilter() {
     FilterRegistrationBean bean = new FilterRegistrationBean();
     bean.setFilter(new WebStatFilter());

     //exclusions:设置哪些请求进行过滤排除掉,从而不进行统计
     Map<String, String> initParams = new HashMap<>();
     initParams.put("exclusions", "*.js,*.css,/druid/*");
     bean.setInitParameters(initParams);

     //"/*" 表示过滤所有请求
     bean.setUrlPatterns(Arrays.asList("/*"));
     return bean;
 }

配置完毕后,我们可以启动来进行测试!

我们发送一条sql语句,然后来看一下后台的消息;
在这里插入图片描述
参考:https://www.cnblogs.com/hellokuangshen/p/11331338.html

方式二、通过SpringbootStarter整合

上面配置使用配置类,配置Druid 数据源监控和监控 filter,也可以不使用配置类,直接在配置文件中进行配置:

        <!--druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.4</version>
        </dependency>

        <!--aop-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
spring:
  datasource:
    username: ${POSTGRES_USERNAME:xxx}
    password: ${POSTGRES_PASSWORD:123456}
    driver-class-name: org.postgresql.Driver
    url: jdbc:postgresql://${POSTGRES_HOST:39.xx.xxx.xx}:${POSTGRES_PORT:xxxx}/${POSTGRES_DATABASE:xxx}?sslmode=disable&currentSchema=${POSTGRES_CURRENTSCHEMA:xxxx}
    #数据源类型
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      # 初始化连接池大小
      initial-size: 10
      max-active: 150
      ## 开启基础监控
      stat-view-servlet:
        enabled: true
        # 账号密码
        login-username: admin
        login-password: 123456
        # 访问路径:ip:port/druid/login.html
        url-pattern: /druid/*
        # ip白名单(没有配置为空,则允许所有访问)。deny是设置黑名单
        allow: null
      filter:
        # 开启sql监控
        stat:
          enabled: true
          db-type: postgresql
          # 慢sql监控,sql监控,最慢会显示红色
          log-slow-sql: true
          slow-sql-millis: 200
        # 开启SQL防火墙监控  
        wall:
          enabled: true
          db-type: postgresql
          config:
             # 是否允许删除
             delete-allow: false
             # 是否允许删除表
             drop-table-allow: false
         # 开启日志打印 https://www.cnblogs.com/sloveling/p/druid_log.html
        slf4j:
          enabled: true
          statement-prepare-after-log-enabled: false
          statement-close-after-log-enabled: false
      # 开启web应用和URI监控
      web-stat-filter:
        enabled: true
        # 排除的
        exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*,/swagger-resources*,/webjars*,/v2*,/doc.html"
        # profileEnable能够监控单个url调用的sql列表
        profileEnable: true
        # sessionStatEnable 开启session监控
      # 开启Spring监控(需要加入aop的依赖)
      aop-patterns: com.xxx.cloud.xxxx.service.*,com.xxx.cloud.xxxx.dao.*

界面信息简单说明

WEB监控:
在这里插入图片描述
如果出现大于1000秒的次数,说明这接口不咋的

Session监控:可以知道当前有多少个用户进行访问
在这里插入图片描述
SQL防火墙:
在这里插入图片描述
更多sql防火墙相关的配置:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
Spring监控:
在这里插入图片描述

  • 5
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值