spring boot配置durid數據源

  • pom文件
<!-- mysql驅動包 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.29</version>
    </dependency>
    
    <!-- alibaba druid數據源 -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.1.5</version>
    </dependency>
  • spring的property文件
spring.datasource.url=jdbc:mysql://localhost:3306/splatform
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
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
# 打開PSCache,而且指定每一個鏈接上PSCache的大小
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
# 配置監控統計攔截的filters,去掉後監控界面sql沒法統計,'wall'用於防火牆
spring.datasource.filters=stat,wall
# 經過connectProperties屬性來打開mergeSql功能;慢SQL記錄
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
  • 配置類
package com.zhangda.core.config;

import java.sql.SQLException;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import com.alibaba.druid.pool.DruidDataSource;

@Configuration
@Primary //在一樣的DataSource中,首先使用被標註的DataSource
public class DruidDataSourceConfig extends DataSourceProperties{

    private Logger logger = LoggerFactory.getLogger(DruidDataSourceConfig.class);

    @Value("${spring.datasource.url}")  
    private String dbUrl;  

    @Value("${spring.datasource.username}")  
    private String username;  

    @Value("${spring.datasource.password}")  
    private String password;  

    @Value("${spring.datasource.driver-class-name}")  
    private String driverClassName;  

    @Value("${spring.datasource.initialSize}")  
    private int initialSize;  

    @Value("${spring.datasource.minIdle}")  
    private int minIdle;  

    @Value("${spring.datasource.maxActive}")  
    private int maxActive;  

    @Value("${spring.datasource.maxWait}")  
    private int maxWait;  

    @Value("${spring.datasource.timeBetweenEvictionRunsMillis}")  
    private int timeBetweenEvictionRunsMillis;  

    @Value("${spring.datasource.minEvictableIdleTimeMillis}")  
    private int minEvictableIdleTimeMillis;  

    @Value("${spring.datasource.validationQuery}")  
    private String validationQuery;  

    @Value("${spring.datasource.testWhileIdle}")  
    private boolean testWhileIdle;  

    @Value("${spring.datasource.testOnBorrow}")  
    private boolean testOnBorrow;  

    @Value("${spring.datasource.testOnReturn}")  
    private boolean testOnReturn;  

    @Value("${spring.datasource.poolPreparedStatements}")  
    private boolean poolPreparedStatements;  

    @Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")  
    private int maxPoolPreparedStatementPerConnectionSize;  

    @Value("${spring.datasource.filters}")  
    private String filters;  

    @Value("{spring.datasource.connectionProperties}")  
    private String connectionProperties;  

    @Bean     //聲明其爲Bean實例  
    public DataSource dataSource(){  
        DruidDataSource datasource = new DruidDataSource();  

        datasource.setUrl(this.dbUrl);  
        datasource.setUsername(username);  
        datasource.setPassword(password);  
        datasource.setDriverClassName(driverClassName);  

        //configuration  
        datasource.setInitialSize(initialSize);  
        datasource.setMinIdle(minIdle);  
        datasource.setMaxActive(maxActive);  
        datasource.setMaxWait(maxWait);  
        datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);  
        datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);  
        datasource.setValidationQuery(validationQuery);  
        datasource.setTestWhileIdle(testWhileIdle);  
        datasource.setTestOnBorrow(testOnBorrow);  
        datasource.setTestOnReturn(testOnReturn);  
        datasource.setPoolPreparedStatements(poolPreparedStatements);  
        datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);  
        try {  
            datasource.setFilters(filters);  
        } catch (SQLException e) {  
            logger.error("druid configuration initialization filter", e);  
        }  
        datasource.setConnectionProperties(connectionProperties);  

        return datasource;  
    }
}
package com.zhangda.core.config;

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.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;


@Configuration
public class DruidMonitorConfig {

    /**
     * 註冊ServletRegistrationBean
     * @return
     */
    @Bean
    public ServletRegistrationBean registrationBean() {
        ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        /** 初始化參數配置,initParams**/
        //白名單
        bean.addInitParameter("allow", "127.0.0.1");//多個ip逗號隔開
        //IP黑名單 (存在共同時,deny優先於allow) : 若是知足deny的話提示:Sorry, you are not permitted to view this page.
        //bean.addInitParameter("deny", "192.168.1.73");
        //登陸查看信息的帳號密碼.
        bean.addInitParameter("loginUsername", "admin");
        bean.addInitParameter("loginPassword", "888888");
        //是否可以重置數據.
        bean.addInitParameter("resetEnable", "false");
        return bean;
    }

    /**
     * 註冊FilterRegistrationBean
     * @return
     */
    @Bean
    public FilterRegistrationBean druidStatFilter() {
        FilterRegistrationBean bean = new FilterRegistrationBean(new WebStatFilter());
        //添加過濾規則.
        bean.addUrlPatterns("/*");
        //添加不須要忽略的格式信息.
        bean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return bean;
    }

}
<dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>druid-spring-boot-starter</artifactId>
   <version>1.1.9</version>
</dependency>
# WebStatFilter配置,說明請參考Druid Wiki,配置_配置WebStatFilter
spring.datasource.druid.web-stat-filter.enabled= #是否啓用StatFilter默認值true
spring.datasource.druid.web-stat-filter.url-pattern=
spring.datasource.druid.web-stat-filter.exclusions=
spring.datasource.druid.web-stat-filter.session-stat-enable=
spring.datasource.druid.web-stat-filter.session-stat-max-count=
spring.datasource.druid.web-stat-filter.principal-session-name=
spring.datasource.druid.web-stat-filter.principal-cookie-name=
spring.datasource.druid.web-stat-filter.profile-enable=

# StatViewServlet配置,說明請參考Druid Wiki,配置_StatViewServlet配置
spring.datasource.druid.stat-view-servlet.enabled= #是否啓用StatViewServlet默認值true
spring.datasource.druid.stat-view-servlet.url-pattern=
spring.datasource.druid.stat-view-servlet.reset-enable=
spring.datasource.druid.stat-view-servlet.login-username=
spring.datasource.druid.stat-view-servlet.login-password=
spring.datasource.druid.stat-view-servlet.allow=
spring.datasource.druid.stat-view-servlet.deny=

# Spring監控配置,說明請參考Druid Github Wiki,配置_Druid和Spring關聯監控配置
spring.datasource.druid.aop-patterns= # Spring監控AOP切入點,如x.y.z.service.*,配置多個英文逗號分隔
相關文章
相關標籤/搜索