SpringBoot 项目中Druid的三种配置方式

   springboot 项目中使用yml(application.yml 或者 application.properties)文件、Java 代码配置 Bean 和注解三种方式配置 Alibaba Druid 用于监控或者查看 SQL 状况:

    1. 配置application .yml 或者 application.properties

    (1)pom.xml 添加相关依赖

        <!-- SPRINGBOOT WEB -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- SPRINGBOOT DRUID -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>
        
        <!-- SPRINGBOOT JDBC -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
<!-- MYSQL --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>${mysql-connector-java.version}</scope> </dependency> <!-- LOG4J --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.16</version> <scope>compile</scope> </dependency>

 (2)配置 application.yml 或者 application.properties 文件,本次以 application.yml配置为例

spring:
  # 数据源配置
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
   # MYSQL 5 驱动:com.mysql.jdbc.Driver,MYSQL 6+ 驱动:com.mysql.cj.jdbc.Driver driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://127.0.0.1:3306/bystest?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=CONVERT_TO_NULL&useSSL=false&serverTimezone=GMT%2B8 username: root password: 123456789 # 连接池配置 druid: # 初始化大小,最小,最大 initial-size: 5 min-idle: 5 max-active: 20 # 配置获取连接等待超时的时间 max-wait: 60000 # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位毫秒 time-between-eviction-runs-millis: 60000 # 配置一个连接在池中最小生存时间 min-evictable-idle-time-millis: 300000 validation-query: SELECT 1 FROM sys_user test-while-idle: true test-on-borrow: false test-on-return: false # 打开 PSCache,并且指定每个连接上 PSCache 的大小 pool-prepared-statements: true max-pool-prepared-statement-per-connection-size: 20 # 配置监控统计拦截的 Filter,去掉后监控界面 SQL 无法统计,wall 用于防火墙 filters: stat,wall,log4j # 通过 connection-properties 属性打开 mergeSql 功能;慢 SQL 记录 connection-properties: druid.stat.mergeSql\=true;druid.stat.slowSqlMillis\=5000 # 配置 DruidStatFilter web-stat-filter: enabled: true url-pattern: /* exclusions: .js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/* # 配置 DruidStatViewServlet stat-view-servlet: url-pattern: /druid/* # IP 白名单,没有配置或者为空,则允许所有访问 allow: 127.0.0.1 # IP 黑名单,若白名单也存在,则优先使用 deny: 192.168.31.253 # 禁用 HTML 中 Reset All 按钮 reset-enable: false # 登录用户名/密码 login-username: root login-password: 123

(3)启动 SpringBoot 项目访问地址 http://localhost:8080/druid/login.html 网址,若出现以下登录界面,则配置成功:

945474-20190427160558887-430451998.png

2. Java 代码中的 Bean 配置文件

  (1)pom.xml 依赖

<!-- 引入druid -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.10</version>
</dependency>

(2)在 application.yml 配置文件中添加 Druid 配置

spring:
    datasource:
        type: com.alibaba.druid.pool.DruidDataSource
        # 数据源的其他配置
        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,去掉后监控界面 sql 无法统计,'wall'用于防火墙
        filters: stat,wall,log4j
        maxPoolPreparedStatementPerConnectionSize: 20
        useGlobalDataSourceStat: true
        connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

(3)项目中添加 DruidConfig.java 配置文件

import javax.servlet.Filter;
import javax.servlet.Servlet;
import javax.sql.DataSource;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;

@Configuration
public class DruidConfig {

    @Bean
    // 将所有前缀为spring.datasource下的配置项都加载DataSource中
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource druidDataSource() {
        return new DruidDataSource();
    }

    @Bean
    public ServletRegistrationBean<Servlet> druidServlet() {
        // 进行 druid 监控的配置处理
        ServletRegistrationBean<Servlet> srb = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/**");
        // 白名单
        srb.addInitParameter("allow", "127.0.0.1");
        // 黑名单
        srb.addInitParameter("deny", "192.168.31.253");
        // 用户名
        srb.addInitParameter("loginUsername", "root");
        // 密码
        srb.addInitParameter("loginPassword", "root");
        // 是否可以重置数据源
        srb.addInitParameter("resetEnable", "false");
        return srb;
    }
    
    @Bean
    public FilterRegistrationBean<Filter> filterRegistrationBean() {
        FilterRegistrationBean<Filter> frb = new FilterRegistrationBean<>();
        frb.setFilter(new WebStatFilter());
        // 所有请求进行监控处理
        frb.addUrlPatterns("/*");
        // 排除名单
        frb.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.css,/druid/*");
        return frb;
    }

}

(4)启动 SpringBoot 项目访问地址 http://localhost:8080/druid/login.html 进行查看登录

3. 注解

(1)pom.xml 文件中添加 Druid 依赖(同方式二)

(2)配置文件添加信息(同方式二)

(3)配置 WebServlet

import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;

import com.alibaba.druid.support.http.StatViewServlet;
@WebServlet(urlPatterns = "/druid/*", 
    initParams={
            @WebInitParam(name="allow",value="192.168.16.110,127.0.0.1"),// IP白名单 (没有配置或者为空,则允许所有访问)
            @WebInitParam(name="deny",value="192.168.16.111"),// IP黑名单 (存在共同时,deny优先于allow)
            @WebInitParam(name="loginUsername",value="admin"),// 用户名
            @WebInitParam(name="loginPassword",value="123"),// 密码
            @WebInitParam(name="resetEnable",value="false")// 禁用HTML页面上的“Reset All”功能
    })
public class DruidServlet extends StatViewServlet {

    private static final long serialVersionUID = 1L;

}

(4)配置 WebFilter

import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;

import com.alibaba.druid.support.http.WebStatFilter;

@WebFilter(filterName="druidWebStatFilter",urlPatterns="/*",
initParams={
    @WebInitParam(name="exclusions",value="*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*")// 忽略资源
})
public class DruidFilter extends WebStatFilter {

}

(5)在启 SpringBootApplication 配置文件中, 添加 @ServletComponentScan 注解用于扫描我们配置的类

  

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;

@SpringBootApplication
@ServletComponentScan("com.test.servlet")
public class SpringBootApplication{

    public static void main(String[] args) {
        SpringApplication.run(SpringBootApplication.class, args); } }

(6)启动 SpringBoot 项目访问地址 http://localhost:8080/druid/login.html 进行查看登录

腾讯云推出云产品限时特惠抢购活动:2C2G云服务器7.9元/月起
本文链接:https://www.jhelp.net/p/uezEPkmaznWwbkCz (转载请保留)。
关注下面的标签,发现更多相似文章