6.SpringBoot使用Druid数据源

1. 使用Druid数据源

1)、druid官方github地址

https://github.com/alibaba/druid

整合第三方技术的两种方式

  • 自定义
  • starter
2)、自定义方式
第一步:切换数据源DruidDataSource

https://mvnrepository.com/artifact/com.alibaba/druid


<dependency>
    <groupId>com.alibabagroupId>
    <artifactId>druidartifactId>
    <version>1.1.22version>
dependency>

以前在xml配置文件中,做如下配置:


<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
		destroy-method="close">
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
		<property name="maxActive" value="20" />
		<property name="initialSize" value="1" />
		<property name="maxWait" value="60000" />
		<property name="minIdle" value="1" />
		<property name="timeBetweenEvictionRunsMillis" value="60000" />
		<property name="minEvictableIdleTimeMillis" value="300000" />
		<property name="testWhileIdle" value="true" />
		<property name="testOnBorrow" value="false" />
		<property name="testOnReturn" value="false" />
		<property name="poolPreparedStatements" value="true" />
		<property name="maxOpenPreparedStatements" value="20" />
bean>

现在可以思考下,SpringBoot中如何配置DruidDataSource组件?

配置文件@Configuration + @Bean组合方式,配置DruidDataSource数据源

@Configuration
public class MyDruidDataSourceConfig {

    /**
     * 1.@Bean注解
     * DruidDataSource组件配置在IOC容器中
     *
     * 2.@ConfigurationProperties(prefix = "spring.datasource")
     * 配置绑定,application.yml文件中设置的数据源的相关配置可以直接使用
     */
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DruidDataSource druidDataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        return dataSource;
    }

}
第二步:StatViewServlet

StatViewServlet的用途包括:

  • 提供监控信息展示的html页面
  • 提供监控信息的JSON API

以前在web.xml配置文件中,做如下配置:

<servlet>
    <servlet-name>DruidStatViewservlet-name>
    <servlet-class>com.alibaba.druid.support.http.StatViewServletservlet-class>
servlet>
<servlet-mapping>
    <servlet-name>DruidStatViewservlet-name>
    <url-pattern>/druid/*url-pattern>
servlet-mapping>

现在可以思考下,SpringBoot中如何配置StatViewServlet组件?

配置文件@Configuration + @Bean组合方式,配置StatViewServlet数据源

@Configuration
public class MyDruidDataSourceConfig {

    /**
     * 1.@Bean注解
     * DruidDataSource组件配置在IOC容器中
     *
     * 2.@ConfigurationProperties(prefix = "spring.datasource")
     * 配置绑定,application.yml文件中设置的数据源的相关配置可以直接使用
     */
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DruidDataSource druidDataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        return dataSource;
    }

    //配置StatViewServlet  提供监控信息展示的html页面
    @Bean
    public ServletRegistrationBean<StatViewServlet> servletRegistrationBean(){
        StatViewServlet statViewServlet = new StatViewServlet();
        ServletRegistrationBean<StatViewServlet> bean =
                new ServletRegistrationBean<>(statViewServlet,"/druid/*");
        //配置上登录的用户名和密码
        bean.addInitParameter("loginUsername","admin");
        bean.addInitParameter("loginPassword","admin");
        //禁止清空统计数据
        bean.addInitParameter("resetEnable","false");
        return bean;
    }
}
第三步:StatFilter

用于统计监控信息;如SQL监控、URI监控


<property name="filters" value="stat,slf4j" />

系统中所有filter:

别名 Filter类名
default com.alibaba.druid.filter.stat.StatFilter
stat com.alibaba.druid.filter.stat.StatFilter
mergeStat com.alibaba.druid.filter.stat.MergeStatFilter
encoding com.alibaba.druid.filter.encoding.EncodingConvertFilter
log4j com.alibaba.druid.filter.logging.Log4jFilter
log4j2 com.alibaba.druid.filter.logging.Log4j2Filter
slf4j com.alibaba.druid.filter.logging.Slf4jLogFilter
commonlogging com.alibaba.druid.filter.logging.CommonsLogFilter
/**
     * 1.@Bean注解
     * DruidDataSource组件配置在IOC容器中
     *
     * 2.@ConfigurationProperties(prefix = "spring.datasource")
     * 配置绑定,application.yml文件中设置的数据源的相关配置可以直接使用
     */
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DruidDataSource druidDataSource() throws SQLException {
    DruidDataSource dataSource = new DruidDataSource();
    //开启SQL监控、防火墙监控、日志监控
    dataSource.setFilters("stat,wall,slf4j");
    return dataSource;
}
第四步:WebStatFilter

用于采集web-jdbc关联监控的数据。

配置文件@Configuration + @Bean组合方式,配置WebStatFilter数据源。

//WebStatFilter用于采集web-jdbc关联监控的数据。
@Bean
public FilterRegistrationBean<WebStatFilter> filterRegistrationBean(){
    WebStatFilter webStatFilter = new WebStatFilter();
    FilterRegistrationBean<WebStatFilter> bean = new FilterRegistrationBean<WebStatFilter>();
    bean.setFilter(webStatFilter);
    bean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
    bean.setUrlPatterns(Arrays.asList("/*"));
    return bean;
}

通过访问:http://localhost:8080/druid/datasource.html 查看druid对SQL监控情况

3)、使用官方starter方式

https://github.com/alibaba/druid/tree/master/druid-spring-boot-starter

第一步:引入druid-starter
<dependency>
    <groupId>com.alibabagroupId>
    <artifactId>druid-spring-boot-starterartifactId>
    <version>1.1.17version>
dependency>
第二步:分析自动配置

6.SpringBoot使用Druid数据源_第1张图片

  • DruidDataSourceAutoConfigure.class,扩展配置项 spring.datasource.druid
  • DruidSpringAopConfiguration.class, 监控SpringBean的;配置项:spring.datasource.druid.aop-patterns
  • DruidStatViewServletConfiguration.class, 监控页的配置:spring.datasource.druid.stat-view-servlet;默认开启
  • DruidWebStatFilterConfiguration.class, web监控配置;spring.datasource.druid.web-stat-filter;默认开启
  • DruidFilterConfiguration.class, 所有Druid自己filter的配置
private static final String FILTER_STAT_PREFIX = "spring.datasource.druid.filter.stat";

private static final String FILTER_CONFIG_PREFIX = "spring.datasource.druid.filter.config";

private static final String FILTER_ENCODING_PREFIX = "spring.datasource.druid.filter.encoding";

private static final String FILTER_SLF4J_PREFIX = "spring.datasource.druid.filter.slf4j";

private static final String FILTER_LOG4J_PREFIX = "spring.datasource.druid.filter.log4j";

private static final String FILTER_LOG4J2_PREFIX = "spring.datasource.druid.filter.log4j2";

private static final String FILTER_COMMONS_LOG_PREFIX = "spring.datasource.druid.filter.commons-log";

private static final String FILTER_WALL_PREFIX = "spring.datasource.druid.filter.wall";
第三步:配置示例
spring:
  # 配置数据源的基础信息
  datasource:
    #JDBC属性配置
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test?unicode=true&characterEncode=utf8&serverTimezone=GMT%2B8
    username: root
    password: root

    #针对于Druid数据源的配置
    druid:
      #监控SpringBean,开启Spring监控
      aop-patterns: com.igeek.springboot.*
      #开启SQL监控、防火墙监控、日志监控
      filters: stat,wall,slf4j

      #用于采集web-jdbc关联监控的数据
      web-stat-filter:
        enabled: true   #开启web监控
        url-pattern: /*
        exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"

      #提供监控信息展示的html页面
      stat-view-servlet:
        enabled: true  #开启html页面展示
        url-pattern: /druid/*
        login-username: admin
        login-password: 123
        reset-enable: false #禁止清空统计数据按钮

      #细节配置
      filter:
        #stat SQL监控,对上面filters里面的stat的详细配置
        stat:
          enabled: true   #开启SQL监控
          log-slow-sql: true  #开启慢日志监控
          slow-sql-millis: 1000 #单位为ms,SQL执行多久算慢,当前设置为sql执行>1s就算慢
        #wall 防火墙,对上面filters里面的wall的详细配置
        wall:
          enabled: true
          config:
            selelct-allow: false #禁止查询
            alter-table-allow: false #禁止修改表
            drop-table-allow: true #允许删除表

配置项列表https://github.com/alibaba/druid/wiki/DruidDataSource%E9%85%8D%E7%BD%AE%E5%B1%9E%E6%80%A7%E5%88%97%E8%A1%A8

你可能感兴趣的:(SpringBoot,spring,boot,spring,java)