Druid是什么?
Druid是Java语言中最好的数据库连接池。Druid能够提供强大的监控和扩展功能。
优点:
- 可以监控数据库访问性能,Druid内置提供了一个功能强大的StatFilter插件,能够详细统计SQL的执行性能,这对于线上分析数据库访问性能有帮助。
- 替换DBCP和C3P0。Druid提供了一个高效、功能强大、可扩展性好的数据库连接池。
- 数据库密码加密。直接把数据库密码写在配置文件中,这是不好的行为,容易导致安全问题。DruidDruiver和DruidDataSource都支持PasswordCallback。
- SQL执行日志,Druid提供了不同的LogFilter,能够支持Common-Logging、Log4j和JdkLog,你可以按需要选择相应的LogFilter,监控你应用的数据库访问情况。
- 扩展JDBC,如果你要对JDBC层有编程的需求,可以通过Druid提供的Filter-Chain机制,很方便编写JDBC层的扩展插件
SpringBoot集成Druid
1. 引入maven依赖
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.20</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency>
2.在 application.yml 文件中加入数据库的配置(属性名的值和冒号中间必须有空格!):
spring: datasource: #mysql 配置 dbType: mysql driverClassName: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false username: root password: 123456 # 驱动配置信息 type: com.alibaba.druid.pool.DruidDataSource # 连接池的配置信息:初始化大小,最小,最大 initialSize: 1 minIdle: 1 maxActive: 3 # 配置获取连接等待超时的时间 maxWait: 60000 # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 timeBetweenEvictionRunsMillis: 60000 # 配置一个连接在池中最小生存的时间,单位是毫秒 minEvictableIdleTimeMillis: 30000 #验证库是否正常sql validationQuery: select 'x' #空闲时验证,防止连接断开 testWhileIdle: true testOnBorrow: false testOnReturn: false # 打开PSCache,并且指定每个连接上PSCache的大小 poolPreparedStatements: true maxPoolPreparedStatementPerConnectionSize: 20 # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙 filters: stat,wall,slf4j # 通过connectProperties属性来打开mergeSql功能;慢SQL记录 connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
3.加入Druid配置类:
由于目前Spring Boot中默认支持的连接池只有 dbcp、dbcp2、 tomcat、hikari 连接池,Druid 暂时不在Spring Boot 中的直接支持,故需要进行配置信息的定制:
新建druid包,加入DruidDBConfig 实现类,类中的属性值一定要和 application.yal文件中对应属性保持一致:
import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.support.http.StatViewServlet; import com.alibaba.druid.support.http.WebStatFilter; import lombok.Data; import org.slf4j.Logger; import org.slf4j.LoggerFactory; 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; @Configuration public class DruidDBConfig { private Logger logger = LoggerFactory.getLogger(DruidDBConfig.class); @Bean public ServletRegistrationBean druidServlet() { logger.info("init Druid Servlet Configuration "); ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*"); // IP白名单 servletRegistrationBean.addInitParameter("allow", ""); // IP黑名单(共同存在时,deny优先于allow) servletRegistrationBean.addInitParameter("deny", ""); //控制台管理用户 servletRegistrationBean.addInitParameter("loginUsername", ""); servletRegistrationBean.addInitParameter("loginPassword", ""); //是否能够重置数据 禁用HTML页面上的“Reset All”功能 servletRegistrationBean.addInitParameter("resetEnable", "false"); return servletRegistrationBean; } @Bean public FilterRegistrationBean filterRegistrationBean() { FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter()); filterRegistrationBean.addUrlPatterns("/*"); filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"); return filterRegistrationBean; } // 解决 spring.datasource.filters=stat,wall,log4j 无法正常注册进去 //使用@ConfigurationProperties替代@Value("${spring.datasource.url}")注解 @ConfigurationProperties(prefix = "spring.datasource") @Data //lombok注解,可以省略setter、getter方法 class DataSourceProperties{
private String dbType; private String url; private String username; private String password; private String driverClassName; private int initialSize; private int minIdle; private int maxActive; private int maxWait; private int timeBetweenEvictionRunsMillis; private int minEvictableIdleTimeMillis; private String validationQuery; private boolean testWhileIdle; private boolean testOnBorrow; private boolean testOnReturn; private boolean poolPreparedStatements; private int maxPoolPreparedStatementPerConnectionSize; private String filters; private String connectionProperties; @Bean //声明其为Bean实例 @Primary //表示这里定义的DataSource将覆盖其他来源的DataSource。 public DataSource dataSource() { DruidDataSource datasource = new DruidDataSource(); datasource.setDbType(dbType); datasource.setUrl(url); datasource.setUsername(username); datasource.setPassword(password); datasource.setDriverClassName(driverClassName); //configuration 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); } datasource.setConnectionProperties(connectionProperties); return datasource; } } }
4.运行项目
启动springboot项目,访问 http://localhost:8080/druid/index.html 直接登录访问 Druid 的后台。
5.问题小结
### Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection: dbType not support : null, url null] with root cause
org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection: dbType not support : null, url null
at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:84)
at org.mybatis.spring.transaction.SpringManagedTransaction.openConnection(SpringManagedTransaction.java:82)
解决方法:application.yml文件缺少dbType属性,url配置文件和类中的名称不一致,导致值没有注入。
spring:
datasource:
#mysql 配置
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false
username: root
password: 123456
# 驱动配置信息
type: com.alibaba.druid.pool.DruidDataSource
dbType: mysql
# 连接池的配置信息:初始化大小,最小,最大
initialSize: 1
minIdle: 1
maxActive: 3
# 配置获取连接等待超时的时间
maxWait: 60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
timeBetweenEvictionRunsMillis: 60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
minEvictableIdleTimeMillis: 30000
#验证库是否正常sql
validationQuery: select 'x'
#空闲时验证,防止连接断开
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
# 打开PSCache,并且指定每个连接上PSCache的大小
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall,slf4j
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000