【轉載學習】SpringBoot配置Druid數據源

出處:http://www.javashuo.com/article/p-fensxgmn-nv.htmlcss

<dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>druid-spring-boot-starter</artifactId>
   <version>1.1.10</version>
</dependency>

配置YML文件html

spring:
  datasource:
#   數據源基本配置
    username: root
    password: root
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/duid
    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
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true  
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

雖然咱們配置了druid鏈接池的其它屬性,可是不會生效。由於默認是使用的java.sql.Datasource的類來獲取屬性的,有些屬性datasource沒有。若是咱們想讓配置生效,須要手動建立Druid的配置文件。java

@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DruidDataSource druidDataSource(){
      return new DruidDataSource();
}

Druid的最強大之處在於它有着強大的監控,能夠監控咱們發送到數據庫的全部sql語句。方便咱們後期排插錯誤。mysql

咱們接着在DruidDataSource裏面配置監控中心:spring

/**
     * 配置監控服務器
     * @return 返回監控註冊的servlet對象
     * @author SimpleWu
     */
    @Bean
    public ServletRegistrationBean statViewServlet() {
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        // 添加IP白名單
        servletRegistrationBean.addInitParameter("allow", "127.0.0.1");
        // 添加IP黑名單,當白名單和黑名單重複時,黑名單優先級更高
        servletRegistrationBean.addInitParameter("deny", "127.0.0.1");
        // 添加控制檯管理用戶
        servletRegistrationBean.addInitParameter("loginUsername", "SimpleWu");
        servletRegistrationBean.addInitParameter("loginPassword", "123456");
        // 是否可以重置數據
        servletRegistrationBean.addInitParameter("resetEnable", "false");
        return servletRegistrationBean;
    }

    /**
     * 配置服務過濾器
     *
     * @return 返回過濾器配置對象
     */
    @Bean
    public FilterRegistrationBean statFilter() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
        // 添加過濾規則
        filterRegistrationBean.addUrlPatterns("/*");
        // 忽略過濾格式
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*,");
        return filterRegistrationBean;
    }

配置完後咱們啓動SpringBoot程序訪問:sql

http://localhost:8080/druid/ 就能夠來到咱們的登陸頁面面就是咱們上面添加的控制檯管理用戶數據庫

相關文章
相關標籤/搜索