1. 程式人生 > 其它 >9. SpringBoot整合Druid

9. SpringBoot整合Druid

SpringBoot整合Druid

  1. 依賴

    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid-spring-boot-starter</artifactId>
        <version>1.2.2</version>
    </dependency>
    
  2. 配置檔案 & 屬性類 & 配置類

# 資料來源
spring:
  datasource:
    # 名稱
    name: druidDataSource
    # 資料來源型別
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
     # 驅動
     driver-class-name: com.mysql.cj.jdbc.Driver
     # 路徑
     url: jdbc:mysql://localhost:3306/demo?useSSL=false&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
     # 使用者名稱
     username: root
     # 密碼
     password: mysql
     filters: stat,wall
     #      filters: stat,wall,log4j,config
     #連線池配置
     max-active: 100
     initial-size: 1
     max-wait: 60000
     min-idle: 1
     time-between-eviction-runs-millis: 60000
     min-evictable-idle-time-millis: 300000
     validation-query: select 'x'
     test-while-idle: true
     test-on-borrow: false
     test-on-return: false
     pool-prepared-statements: true
     max-open-prepared-statements: 50
     max-pool-prepared-statement-per-connection-size: 20
import org.springframework.boot.context.properties.ConfigurationProperties;

/**
 * 資料來源屬性
 */
@ConfigurationProperties(prefix = "spring.datasource.druid")
public class DruidDataSourceProperties {

   // jdbc
   private String driverClassName;
   private String url;
   private String username;
   private String password;
   // jdbc connection pool
   private int initialSize;
   private int minIdle;
   private int maxActive = 100;
   private long maxWait;
   private long timeBetweenEvictionRunsMillis;
   private long minEvictableIdleTimeMillis;
   private String validationQuery;
   private boolean testWhileIdle;
   private boolean testOnBorrow;
   private boolean testOnReturn;
   private boolean poolPreparedStatements;
   private int maxPoolPreparedStatementPerConnectionSize;
   // filter
   private String filters;

   public int getInitialSize() {
      return initialSize;
   }

   public void setInitialSize(int initialSize) {
      this.initialSize = initialSize;
   }

   public int getMinIdle() {
      return minIdle;
   }

   public void setMinIdle(int minIdle) {
      this.minIdle = minIdle;
   }

   public int getMaxActive() {
      return maxActive;
   }

   public void setMaxActive(int maxActive) {
      this.maxActive = maxActive;
   }

   public long getMaxWait() {
      return maxWait;
   }

   public void setMaxWait(long maxWait) {
      this.maxWait = maxWait;
   }

   public long getTimeBetweenEvictionRunsMillis() {
      return timeBetweenEvictionRunsMillis;
   }

   public void setTimeBetweenEvictionRunsMillis(long timeBetweenEvictionRunsMillis) {
      this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
   }

   public long getMinEvictableIdleTimeMillis() {
      return minEvictableIdleTimeMillis;
   }

   public void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis) {
      this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
   }

   public String getValidationQuery() {
      return validationQuery;
   }

   public void setValidationQuery(String validationQuery) {
      this.validationQuery = validationQuery;
   }

   public boolean isTestWhileIdle() {
      return testWhileIdle;
   }

   public void setTestWhileIdle(boolean testWhileIdle) {
      this.testWhileIdle = testWhileIdle;
   }

   public boolean isTestOnBorrow() {
      return testOnBorrow;
   }

   public void setTestOnBorrow(boolean testOnBorrow) {
      this.testOnBorrow = testOnBorrow;
   }

   public boolean isTestOnReturn() {
      return testOnReturn;
   }

   public void setTestOnReturn(boolean testOnReturn) {
      this.testOnReturn = testOnReturn;
   }

   public boolean isPoolPreparedStatements() {
      return poolPreparedStatements;
   }

   public void setPoolPreparedStatements(boolean poolPreparedStatements) {
      this.poolPreparedStatements = poolPreparedStatements;
   }

   public int getMaxPoolPreparedStatementPerConnectionSize() {
      return maxPoolPreparedStatementPerConnectionSize;
   }

   public void setMaxPoolPreparedStatementPerConnectionSize(int maxPoolPreparedStatementPerConnectionSize) {
      this.maxPoolPreparedStatementPerConnectionSize = maxPoolPreparedStatementPerConnectionSize;
   }

   public String getFilters() {
      return filters;
   }

   public void setFilters(String filters) {
      this.filters = filters;
   }

   public String getDriverClassName() {
      return driverClassName;
   }

   public void setDriverClassName(String driverClassName) {
      this.driverClassName = driverClassName;
   }

   public String getUrl() {
      return url;
   }

   public void setUrl(String url) {
      this.url = url;
   }

   public String getUsername() {
      return username;
   }

   public void setUsername(String username) {
      this.username = username;
   }

   public String getPassword() {
      return password;
   }

   public void setPassword(String password) {
      this.password = password;
   }

}
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
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 javax.servlet.Filter;
import javax.servlet.Servlet;
import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * Druid資料來源配置
 */
@Configuration
@EnableConfigurationProperties({DruidDataSourceProperties.class})
public class DruidConfig {
    @Autowired
    private DruidDataSourceProperties properties;

    @Bean
    @ConditionalOnMissingBean
    public DataSource druidDataSource() {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(properties.getDriverClassName());
        druidDataSource.setUrl(properties.getUrl());
        druidDataSource.setUsername(properties.getUsername());
        druidDataSource.setPassword(properties.getPassword());
        druidDataSource.setInitialSize(properties.getInitialSize());
        druidDataSource.setMinIdle(properties.getMinIdle());
        druidDataSource.setMaxActive(properties.getMaxActive());
        druidDataSource.setMaxWait(properties.getMaxWait());
        druidDataSource.setTimeBetweenEvictionRunsMillis(properties.getTimeBetweenEvictionRunsMillis());
        druidDataSource.setMinEvictableIdleTimeMillis(properties.getMinEvictableIdleTimeMillis());
        druidDataSource.setValidationQuery(properties.getValidationQuery());
        druidDataSource.setTestWhileIdle(properties.isTestWhileIdle());
        druidDataSource.setTestOnBorrow(properties.isTestOnBorrow());
        druidDataSource.setTestOnReturn(properties.isTestOnReturn());
        druidDataSource.setPoolPreparedStatements(properties.isPoolPreparedStatements());
        druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(properties.getMaxPoolPreparedStatementPerConnectionSize());

        try {
            druidDataSource.setFilters(properties.getFilters());
            druidDataSource.init();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return druidDataSource;
    }

    /**
     * 註冊Servlet資訊, 配置監控檢視
     *
     * @return
     */
    @Bean
    @ConditionalOnMissingBean
    public ServletRegistrationBean<Servlet> druidServlet() {
        ServletRegistrationBean<Servlet> servletRegistrationBean = new ServletRegistrationBean<Servlet>(new StatViewServlet(), "/druid/*");

        //白名單:
//        servletRegistrationBean.addInitParameter("allow","127.0.0.1,139.196.87.48");
        //IP黑名單 (存在共同時,deny優先於allow) : 如果滿足deny的話提示:Sorry, you are not permitted to view this page.
        servletRegistrationBean.addInitParameter("deny","192.168.1.119");
        //登入檢視資訊的賬號密碼, 用於登入Druid監控後臺
        servletRegistrationBean.addInitParameter("loginUsername", "admin");
        servletRegistrationBean.addInitParameter("loginPassword", "admin");
        //是否能夠重置資料.
        servletRegistrationBean.addInitParameter("resetEnable", "true");
        return servletRegistrationBean;

    }

    /**
     * 註冊Filter資訊, 監控攔截器
     *
     * @return
     */
    @Bean
    @ConditionalOnMissingBean
    public FilterRegistrationBean<Filter> filterRegistrationBean() {
        FilterRegistrationBean<Filter> filterRegistrationBean = new FilterRegistrationBean<Filter>();
        filterRegistrationBean.setFilter(new WebStatFilter());
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }
}
  1. Druid監控

    http://localhost:8080/druid/login.html