Druid是Java語言中最好的數據庫鏈接池,而且可以提供強大的監控和擴展功能。css
業界把 Druid 和 HikariCP 作對比後,雖然說 HikariCP 的性能比 Druid 高,可是由於 Druid 包括不少維度的統計和分析功能,因此這也是你們都選擇使用它的緣由。html
下面來講明如何在 spring Boot 中配置使用Druidjava
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.18</version> </dependency>
# 數據庫訪問配置 # 主數據源,默認的 spring.datasource.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/test spring.datasource.username=root spring.datasource.password=123456 # 下面爲鏈接池的補充設置,應用到上面全部數據源中 # 初始化大小,最小,最大 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,log4j # 經過connectProperties屬性來打開mergeSql功能;慢SQL記錄 spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 # 合併多個DruidDataSource的監控數據 #spring.datasource.useGlobalDataSourceStat=true
以下是在SpringBoot項目中基於註解的配置,若是是web.xml配置,按規則配置便可。mysql
@Configuration public class DruidConfig { @Bean @ConfigurationProperties(prefix="spring.datasource") public DataSource druidDataSource() { return new DruidDataSource(); } @Bean public ServletRegistrationBean druidServlet() { ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*"); //白名單: servletRegistrationBean.addInitParameter("allow","127.0.0.1"); //IP黑名單 (存在共同時,deny優先於allow) : 若是知足deny的話提示:Sorry, you are not permitted to view this page. servletRegistrationBean.addInitParameter("deny","192.168.1.73"); //登陸查看信息的帳號密碼. servletRegistrationBean.addInitParameter("loginUsername","admin2"); servletRegistrationBean.addInitParameter("loginPassword","123456"); //是否可以重置數據. servletRegistrationBean.addInitParameter("resetEnable","false"); return servletRegistrationBean; } @Bean public FilterRegistrationBean filterRegistrationBean() { FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); filterRegistrationBean.setFilter(new WebStatFilter()); filterRegistrationBean.addUrlPatterns("/*"); filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"); return filterRegistrationBean; } }
而後啓動項目後訪問 http://yourdomain/druid/index.html 便可查看數據源及SQL統計等。
截圖以下: web