Druid是一个JDBC组件,druid 是阿里开源在 github 上面的数据库连接池,它包括三部分:
* DruidDriver 代理Driver,能够提供基于Filter-Chain模式的插件体系。
* DruidDataSource 高效可管理的数据库连接池。
* SQLParser 专门解析 sql 语句
Druid 有什么优点?
1. 可以监控数据库访问性能,Druid内置提供了一个功能强大的StatFilter插件,能够详细统计SQL的执行性能,这对于线上分析数据库访问性能有帮助。
2. 替换DBCP和C3P0。Druid提供了一个高效、功能强大、可扩展性好的数据库连接池。
3. 数据库密码加密。直接把数据库密码写在配置文件中,这是不好的行为,容易导致安全问题。DruidDruiver和DruidDataSource都支持PasswordCallback。
4. SQL执行日志,Druid提供了不同的LogFilter,能够支持Common-Logging、Log4j和JdkLog,你可以按需要选择相应的LogFilter,监控你应用的数据库访问情况。
5. 扩展JDBC,如果你要对JDBC层有编程的需求,可以通过Druid提供的Filter-Chain机制,很方便编写JDBC层的扩展插件
通过命令:
java -cp D:\apache-maven-3.3.9\repository\com\alibaba\druid\1.0.20\druid-1.0.20.jar com.alibaba.d
ruid.filter.config.ConfigTools 123456
返回值如下:publickey代表公钥,privatekey是密码加密后的结果
privateKey:MIIBVgIBADANBgkqhkiG9w0BAQEFAASCAUAwggE8AgEAAkEA0TK4zQth0YhtXUle/bFqs2LXvBDzc1wvxPDHSF8a62CnzPadEgw+NTGb3njas
92hY9vKmVJYXu125aYWdPxElQIDAQABAkEAxeurE7NVFJxye/PSv0p/nMBDQ1b2PYpWV4lFwZ7ZJR5TIIJra7lRCFAXDeT+m+nwC8ZnHysEXQYI8wgnRBKx8
QIhAOzbG/Mbx3oUg/elftQQSP/u8CJjZUu2r7pWtH+aXIWbAiEA4htVZ3anV2b6cGxSYSNF1mWeEuhx6kGS2NgiSF+cmY8CIQCLLLB+qEsNK/LjWIZuu2b5o
//MZRVHaQBXAM2s0RoekwIhAMM6jKxwNB9wiC9IKH09IpDzXuC+mZWGFxBq1ncdLy8bAiAKOrgN543NZweSCHiWXm/eYvCUqaaERJrJy8jD8EMuCg==
publicKey:MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBANEyuM0LYdGIbV1JXv2xarNi17wQ83NcL8Twx0hfGutgp8z2nRIMPjUxm9542rPdoWPbyplSWF7tdu
WmFnT8RJUCAwEAAQ==
password:rqqQfXfY5N0x9BABjs7t7CY9IHm3aYNzuTk7frBDq1ZIliEK0UTUKclQ2+N5errzmB0/Wzk1cLRpIFn+FoVqRw==
通过加密时使用的命令我们不难看出druid对数据库密码加解密用的是configFilter这个类,所以在配置数据源链接时务必将该filter添加上,否则始终会抛出数据库连接异常,而druid是有重试机制的,默认重试30次,如果数据库做了限制频繁账号尝试连接的话,该账号有可能被锁定,导致线上数据库写入出现问题,所以缺了这样的配置实用加密连接还是蛮恐怖的,直接影响线上环境。
com.alibaba
druid
1.0.20
# 驱动配置信息
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url = jdbc:mysql://127.0.0.1:3306/myspringboot
spring.datasource.username = 用户名
spring.datasource.password = your encryt password
spring.datasource.publicKey=your publicKey
spring.datasource.driverClassName = com.mysql.jdbc.Driver
# 连接池的配置信息
# 初始化大小,最小,最大
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=config,stat,wall,log4j
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000;config.decrpt=true;
#config.decrypt.key=your public key
package com.rt.rest.config.druid;
import com.alibaba.druid.filter.config.ConfigTools;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
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;
import javax.sql.DataSource;
import java.sql.SQLException;
/**
* @Description:
* @author: Administrator
* @version: V1.0.0
* @data 2018/3/6
*/
//@Configuration
//@ConfigurationProperties(prefix="spring.datasource")
public class DruidDatsSourceConfig{
private Logger logger = LoggerFactory.getLogger(DruidDatsSourceConfig.class);
private String type;
private String url;
private String driverClassName;
private String username;
private String password;
private Integer initialSize;
private Integer minIdle;
private Integer maxActive;
private Integer maxWait;
private Integer timeBetweenEvictionRunsMillis;
private Integer minEvictableIdleTimeMillis;
private String validationQuery;
private Boolean testWhileIdle;
private Boolean testOnBorrow;
private Boolean testOnReturn;
private Boolean poolPreparedStatements;
private Integer maxPoolPreparedStatementPerConnectionSize;
private String filters;
private String connectionProperties;
private String publicKey;
public String getDriverClassName() {
return driverClassName;
}
public void setDriverClassName(String driverClassName) {
this.driverClassName = driverClassName;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getInitialSize() {
return initialSize;
}
public void setInitialSize(Integer initialSize) {
this.initialSize = initialSize;
}
public Integer getMinIdle() {
return minIdle;
}
public void setMinIdle(Integer minIdle) {
this.minIdle = minIdle;
}
public Integer getMaxActive() {
return maxActive;
}
public void setMaxActive(Integer maxActive) {
this.maxActive = maxActive;
}
public Integer getMaxWait() {
return maxWait;
}
public void setMaxWait(Integer maxWait) {
this.maxWait = maxWait;
}
public Integer getTimeBetweenEvictionRunsMillis() {
return timeBetweenEvictionRunsMillis;
}
public void setTimeBetweenEvictionRunsMillis(Integer timeBetweenEvictionRunsMillis) {
this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
}
public Integer getMinEvictableIdleTimeMillis() {
return minEvictableIdleTimeMillis;
}
public void setMinEvictableIdleTimeMillis(Integer minEvictableIdleTimeMillis) {
this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
}
public String getValidationQuery() {
return validationQuery;
}
public void setValidationQuery(String validationQuery) {
this.validationQuery = validationQuery;
}
public Boolean getTestWhileIdle() {
return testWhileIdle;
}
public void setTestWhileIdle(Boolean testWhileIdle) {
this.testWhileIdle = testWhileIdle;
}
public Boolean getTestOnBorrow() {
return testOnBorrow;
}
public void setTestOnBorrow(Boolean testOnBorrow) {
this.testOnBorrow = testOnBorrow;
}
public Boolean getTestOnReturn() {
return testOnReturn;
}
public void setTestOnReturn(Boolean testOnReturn) {
this.testOnReturn = testOnReturn;
}
public Boolean getPoolPreparedStatements() {
return poolPreparedStatements;
}
public void setPoolPreparedStatements(Boolean poolPreparedStatements) {
this.poolPreparedStatements = poolPreparedStatements;
}
public Integer getMaxPoolPreparedStatementPerConnectionSize() {
return maxPoolPreparedStatementPerConnectionSize;
}
public void setMaxPoolPreparedStatementPerConnectionSize(Integer maxPoolPreparedStatementPerConnectionSize) {
this.maxPoolPreparedStatementPerConnectionSize = maxPoolPreparedStatementPerConnectionSize;
}
public String getFilters() {
return filters;
}
public void setFilters(String filters) {
this.filters = filters;
}
public String getConnectionProperties() {
return connectionProperties;
}
public void setConnectionProperties(String connectionProperties) {
this.connectionProperties = connectionProperties;
}
public String getPublicKey() {
return publicKey;
}
public void setPublicKey(String publicKey) {
this.publicKey = publicKey;
}
@Bean
public ServletRegistrationBean druidServlet() {
ServletRegistrationBean reg = new ServletRegistrationBean();
reg.setServlet(new StatViewServlet());
reg.addUrlMappings("/druid/*");
reg.addInitParameter("loginUsername", username);
reg.addInitParameter("loginPassword", password);
return reg;
}
@Bean
public FilterRegistrationBean filterRegistrationBean() {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
filterRegistrationBean.setFilter(new WebStatFilter());
filterRegistrationBean.addUrlPatterns("/*");
filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
filterRegistrationBean.addInitParameter("profileEnable", "true");
return filterRegistrationBean;
}
@Bean
@Primary
public DataSource druidDataSource() throws Exception {
DruidDataSource datasource = new DruidDataSource();
datasource.setUrl(url);
datasource.setUsername(username);
datasource.setPassword(ConfigTools.decrypt(publicKey,password);
datasource.setDriverClassName(driverClassName);
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);
String paramArray[] = connectionProperties.split(";");
datasource.setConnectionProperties(connectionProperties);
try {
datasource.setFilters(filters);
} catch (SQLException e) {
logger.error("========druid configuration initialization filter========", e);
}
return datasource;
}
}
原文地址,本文略有改动
http://blog.csdn.net/ikownyou/article/details/79022560
查看更多戳这里
https://github.com/alibaba/druid/wiki/常见问题
开源中国
https://www.oschina.net/news/93304/druid-1-1-8-released