引入依賴
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.19</version>
</dependency>
複製代碼
在spring配置文件application.yml中新增以下配置
spring:
datasource:
url: jdbc:mysql://localhost:3306/***?useUnicode=true&characterEncoding=utf8
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
# 最小鏈接池數量
minIdle: 3
# 最大鏈接池數量
maxActive: 20
# 獲取鏈接時最大等待時間,單位毫秒
maxWait: 60000
# 初始化時創建物理鏈接的個數
initialSize: 2
# 配置間隔多久才進行一次檢測,檢測須要關閉的空閒鏈接,單位是毫秒
timeBetweenEvictionRunsMillis: 60000
# 配置一個鏈接在池中最小生存的時間,單位是毫秒
minEvictableIdleTimeMillis: 30000
# 檢測鏈接是否有效
validationQuery: select 'x'
# 申請鏈接的時候檢測,建議配置爲true,不影響性能,而且保證安全性
testWhileIdle: true
# 獲取鏈接時執行檢測,影響性能,建議關閉
testOnBorrow: false
# 歸還鏈接時執行檢測,影響性能,建議關閉
testOnReturn: false
# 打開PSCache,而且指定每一個鏈接上PSCache的大小,PSCache對支持遊標的數據庫性能提高巨大,oracle建議開啓,mysql建議關閉
poolPreparedStatements: false
maxPoolPreparedStatementPerConnectionSize: 20
# 配置插件 stat:監控統計 wall:防護sql注入 log4j:日誌
filters: stat,wall,log4j
# 經過connectProperties屬性來打開mergeSql功能;慢SQL記錄
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
複製代碼
新建druid配置文件,代碼以下
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
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 org.springframework.context.annotation.Primary;
@Configuration
public class DruidConfig {
@Primary
@Bean(destroyMethod = "close")
@ConfigurationProperties(prefix = "spring.datasource")
public DruidDataSource dataSource(){
return new DruidDataSource();
}
@Bean
public FilterRegistrationBean statFilter(){
FilterRegistrationBean filter = new FilterRegistrationBean(new WebStatFilter());
filter.addUrlPatterns("/*");
filter.addInitParameter("exclusions", "*.js,*.gif,*.png,*.jpg,*.css,*.ico,/druid/*");
return filter;
}
@Bean
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean servlet = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
servlet.addInitParameter("allow", "127.0.0.1");
servlet.addInitParameter("deny","192.168.1.4");
servlet.addInitParameter("loginUsername","root");
servlet.addInitParameter("loginPassword","root");
servlet.addInitParameter("resetEnable","true");
return servlet;
}
}
複製代碼