DRUID是阿裡巴巴開源平台上一個資料庫連接配接池實作,它結合了C3P0、DBCP、PROXOOL等DB池的優點,同時加入了日志監控,可以很好的監控DB池連接配接和SQL的執行情況,可以說是針對監控而生的DB連接配接池。
SpringBoot整合Druid
1.添加Maven依賴
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.8</version>
</dependency>
2.添加配置
application.yml
spring:
datasource:
username: root
password:
url: jdbc:mysql://:/jdbc
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
initialSize:
minIdle:
maxActive:
maxWait:
# 配置間隔多久才進行一次檢測,檢測需要關閉的空閑連接配接,機關是毫秒
timeBetweenEvictionRunsMillis:
# 配置一個連接配接在池中最小生存的時間,機關是毫秒
minEvictableIdleTimeMillis:
validationQuery: SELECT FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
# 打開PSCache,并且指定每個連接配接上PSCache的大小
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize:
# 配置監控統計攔截的filters,去掉後監控界面sql無法統計,'wall'用于防火牆
filters: stat,wall,log4j
# 合并多個DruidDataSource的監控資料
useGlobalDataSourceStat: true
# 通過connectProperties屬性來打開mergeSql功能;慢SQL記錄
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
3.開啟Druid監控功能
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix="spring.datasource")
@Bean
public DataSource durid(){
return new DruidDataSource();
}
//配置Druid的監控
//1.配置一個管理背景的sevlet
@Bean
public ServletRegistrationBean<StatViewServlet> statViewServlet(){
ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<StatViewServlet>(new StatViewServlet(),"/druid/*");
Map<String,String> initParams = new HashMap<String,String>();
initParams.put("loginUsername", "admin");
initParams.put("loginPassword", "123456");
//設定ip白名單
initParams.put("allow", "");
//設定ip黑名單。deny優先級高于allow
initParams.put("deny", "192.168.10.125");
bean.setInitParameters(initParams);
return bean;
}
//2.配置一個web監控的filter
@Bean
public FilterRegistrationBean<WebStatFilter> webStatFilter(){
FilterRegistrationBean<WebStatFilter> bean = new FilterRegistrationBean<WebStatFilter>();
bean.setFilter(new WebStatFilter());
Map<String,String> initParams = new HashMap<String,String>();
//忽略過濾的形式
initParams.put("exclusions", "*.js,*.css,/druid/*");
bean.setInitParameters(initParams);
//設定過濾器過濾路徑
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
}
}
4.檢驗配置是否生效
- 通路http://localhost:8080/druid/login.html
- 以上述配置的賬号密碼登入(admin,123456)
5.可能出現錯誤
錯誤描述:
Failed to bind properties under 'spring.datasource' to javax.sql.DataSource:
Property: spring.datasource.filters
Value: stat,wall,log4j
Origin: class path resource [application.yml]::
Reason: Unable to set value for property filters
解決辦法:
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
<scope>compile</scope>
</dependency>