Druid是Java中最好的数据库连接池,并且能够提供强大的监控和扩展功能。业界把Druid和HikariCP做对比后,虽说HikarCP的性能比Druid高,但是因为Druid包括很多维度的统计和分析功能,所以也是大家学则使用的主要原因。
Druid是阿里巴巴开源平台上的一个项目,整个项目由数据库连接池、插件框架和SQL解析器组成。该项目主要是为了扩展JDBC的一些限制,可以让程序员实现一些特殊的需求,比如向密钥服务请求凭证、统计SQL信息、SQL性能收集、SQL注入检查、SQL翻译等,程序员可以通过定制来实现自己需要的功能。
更多关于Druid的介绍可以看http://www.iteye.com/magazines/90,是对主要负责人的采访。
现在来说一下如何配置实用这么牛叉的druid。
在pom.xml配置文件中添加如下依赖,实际工程中用的还是1.0.18的版本
com.alibaba
druid
1.0.25
spring-boot目前支持的连接池有dbcp,dbcp2,hikari,tomcat的jdbc(这也是默认使用的),并不支持druid,这么牛叉的东西,系统spring-boot团队早日增加对druid的支持。
### druid setting ###
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url=jdbc:mysql://ip:3306/jikefriend?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=
### 不支持的补充配置 ###
spring.datasource.driverClassName=com.mysql.jdbc.Driver
# 初始化大小,最小,最大
spring.datasource.initialSize=1
spring.datasource.minIdle=1
spring.datasource.maxActive=20
# 配置获取连接等待超时的时间
spring.datasource.maxWait=60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
spring.datasource.testWhileIdle=true
spring.datasource.minEvictableIdleTimeMillis=25200000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
spring.datasource.timeBetweenEvictionRunsMillis=60000
spring.datasource.removeAbandoned=true
spring.datasource.removeAbandonedTimeout=1800
# 打开PSCache,并且指定每个连接上PSCache的大小
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
spring.datasource.logAbandoned=true
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
spring.datasource.filters=stat,wall,log4j
由于很多属性并不支持,所以需要进行配置信息的定制
package com.db;
import com.alibaba.druid.pool.DruidDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.sql.DataSource;
import java.sql.SQLException;
@Configuration
public class DruidConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(DruidConfig.class);
@Value("${spring.datasource.driverClassName}")
private String driverClassName;
@Value("${spring.datasource.url}")
private String url;
@Value("${spring.datasource.username}")
private String username;
@Value("${spring.datasource.password}")
private String password;
@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.validationQuery}")
private String validationQuery;
@Value("${spring.datasource.testOnBorrow}")
private boolean testOnBorrow;
@Value("${spring.datasource.testOnReturn}")
private boolean testOnReturn;
@Value("${spring.datasource.testWhileIdle}")
private boolean testWhileIdle;
@Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
private int timeBetweenEvictionRunsMillis;
@Value("${spring.datasource.minEvictableIdleTimeMillis}")
private int minEvictableIdleTimeMillis;
@Value("${spring.datasource.removeAbandoned}")
private boolean removeAbandoned;
@Value("${spring.datasource.removeAbandonedTimeout}")
private int removeAbandonedTimeout;
@Value("${spring.datasource.logAbandoned}")
private boolean logAbandoned;
@Value("${spring.datasource.filters}")
private String filters;
@Value("${spring.datasource.poolPreparedStatements}")
private boolean poolPreparedStatements;
@Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")
private int maxPoolPreparedStatementPerConnectionSize;
@Bean
@Primary
public DataSource dataSource() {
DruidDataSource datasource = new DruidDataSource();
datasource.setDriverClassName(driverClassName);
datasource.setUrl(url);
datasource.setUsername(username);
datasource.setPassword(password);
//其它配置
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);
}
return datasource;
}
}
其中,
DruidDBConfig类被@Configuration标注,用作配置信息; DataSource对象被@Bean声明,为Spring容器所管理, @Primary表示这里定义的DataSource将覆盖其他来源的DataSource。
配置servlet
package com.db;
import com.alibaba.druid.support.http.StatViewServlet;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
@SuppressWarnings("serial")
@WebServlet(urlPatterns="/druid/*",
initParams={
/** 白名单,如果不配置或value为空,则允许所有 */
@WebInitParam(name="allow",value="127.0.0.1,192.0.0.1"),
/** 黑名单,与白名单存在相同IP时,优先于白名单 */
@WebInitParam(name="deny",value="192.0.0.1"),
/** 用户名 */
@WebInitParam(name="loginUsername",value="jikefriend"),
/** 密码 */
@WebInitParam(name="loginPassword",value="jikefriend"),
/** 禁用HTML页面上的“Reset All”功能 */
@WebInitParam(name="resetEnable",value="false")
})
public class DruidStatViewServlet extends StatViewServlet {
}
配置filter
package com.db;
import com.alibaba.druid.support.http.WebStatFilter;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
@WebFilter(
filterName="druidWebStatFilter",urlPatterns="/*",
initParams={
/** 忽略资源 */
@WebInitParam(name="exclusions", value="*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*")
}
)
public class DruidStatFilter extends WebStatFilter {
}
这里需要注意的,此时如果直接启动项目,在浏览器中输入http://127.0.0.1:8080/druid/index.html会报404,需要在启动类上加上@ServletComponentScan注解,才能够在启动的时候扫描到自己编写的servlet和filter。
/**
* 注册一个StatViewServlet
* @return
*/
@Bean
public ServletRegistrationBean DruidStatViewServle2(){
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),"/druid2/*");
//添加初始化参数:initParams
/** 白名单,如果不配置或value为空,则允许所有 */
servletRegistrationBean.addInitParameter("allow","127.0.0.1,192.0.0.1");
/** 黑名单,与白名单存在相同IP时,优先于白名单 */
servletRegistrationBean.addInitParameter("deny","192.0.0.1");
/** 用户名 */
servletRegistrationBean.addInitParameter("loginUsername","jikefriend");
/** 密码 */
servletRegistrationBean.addInitParameter("loginPassword","jikefriend");
/** 禁用页面上的“Reset All”功能 */
servletRegistrationBean.addInitParameter("resetEnable","false");
return servletRegistrationBean;
}
/**
* 注册一个:WebStatFilter
* @return
*/
@Bean
public FilterRegistrationBean druidStatFilter2(){
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
/** 过滤规则 */
filterRegistrationBean.addUrlPatterns("/*");
/** 忽略资源 */
filterRegistrationBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid2/*");
return filterRegistrationBean;
}
需要注意的是,这里引用的jar包为
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;