victory的博客

长安一片月,万户捣衣声

0%

SpringBoot集成Druid

SpringBoot集成Druid

Java程序很大一部分要操作数据库,为了提高性能操作数据库的时候,又不得不使用数据库连接池。
Druid 是阿里巴巴开源平台上一个数据库连接池实现,结合了 C3P0、DBCP 等 DB 池的优点,同时加入了日志监控。
Druid 可以很好的监控 DB 池连接和 SQL 的执行情况,天生就是针对监控而生的 DB 连接池。
Druid已经在阿里巴巴部署了超过600个应用,经过一年多生产环境大规模部署的严苛考验。
Spring Boot 2.0 以上默认使用 Hikari 数据源,可以说 Hikari 与 Driud 都是当前 Java Web 上最优秀的数据源,我们来重点介绍 Spring Boot 如何集成 Druid 数据源,如何实现数据库监控。

Github地址

  • 项目目录
  • 添加Druid数据源依赖
    1
    2
    3
    4
    5
    <dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.2.11</version>
    </dependency>
  • 切换数据源并配置数据源;之前已经说过 Spring Boot 2.0 以上默认使用 com.zaxxer.hikari.HikariDataSource 数据源,但可以 通过 spring.datasource.type 指定数据源
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    spring:
    datasource:
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    #SpringBoot默认是不注入这些的,需要自己绑定
    #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.Properity
    #则导入log4j 依赖就行
    filters: stat,wall # ,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionoProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
  • 现在需要程序员自己为 DruidDataSource 绑定全局配置文件中的参数,再添加到容器中,而不再使用 Spring Boot 的自动生成了;我们需要 自己添加 DruidDataSource 组件到容器中,并绑定属性;
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11

    @Configuration
    public class DruidConfig {
    //绑定全局配置文件中的参数
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druidDataSource() {
    return new DruidDataSource();
    }

    }
  • 测试Druid数据源是否配置成功
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    package com.example;

    import org.junit.jupiter.api.Test;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;

    import javax.sql.DataSource;
    import java.sql.Connection;
    import java.sql.SQLException;

    @SpringBootTest
    class SpringDataApplicationTests {

    @Autowired
    DataSource dataSource;

    @Test
    void contextLoads() throws SQLException {
    //查看默认的数据源
    System.out.println(dataSource.getClass());

    //获得数据库链接
    Connection connection = dataSource.getConnection();
    System.out.println(connection);

    //关闭
    connection.close();
    }
    }

  • 配置Druid数据源监控
    Druid 数据源具有监控的功能,并提供了一个 web 界面方便用户查看,类似安装 路由器 时,人家也提供了一个默认的 web 页面。
    所以第一步需要设置 Druid 的后台管理页面,比如 登录账号、密码 等;配置后台管理;
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    // 后台监控:相当于web.xml,配置ServletRegistrationBean
    //因为SprintBoot内置了servlet容器,所以没有web.xml,替代方法ServletRegistrationBean
    @Bean
    public ServletRegistrationBean statViewServlet() {
    ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");

    // 后台登录进行账号密码配置
    HashMap<String, String> initParameters = new HashMap<>();

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

    // 允许谁可以访问,如果后面的参数为空代表谁都可以访问,指定参数只能指定的参数进行访问
    initParameters.put("allow", "");

    // 禁止谁可以访问
    // initParameters.put("koko","192.168.43.21");

    bean.setInitParameters(initParameters); // 设置初始化参数
    return bean;
    }
  • 配置完成后,就可以通过http://localhost:8080/druid/login.html访问监控页面
  • 登录成功后显示的监控页面
  • 配置 Druid web 监控 filter 过滤器
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    //filter
    @Bean
    public FilterRegistrationBean webStatFileter(){
    FilterRegistrationBean bean = new FilterRegistrationBean();

    bean.setFilter(new WebStatFilter());

    //可以过滤那些请求呢?

    Map<String, String> initParameters = new HashMap<>();

    //这些东西不进行统计
    initParameters.put("exclusions", "*.js,*.css,/druid/*");

    return bean;
    }