What
Druid是一个JDBC组件,它包括三部分:
• DruidDriver 代理Driver,能够提供基于Filter-Chain模式的插件体系。
• DruidDataSource 高效可管理的数据库连接池。
• SQLParser
Why
• 可以监控数据库访问性能,Druid内置提供了一个功能强大的StatFilter插件,能够详细统计SQL的执行性能,这对于线上分析数据库访问性能有帮助。
• 替换DBCP和C3P0。Druid提供了一个高效、功能强大、可扩展性好的数据库连接池。
• 数据库密码加密。直接把数据库密码写在配置文件中,这是不好的行为,容易导致安全问题。DruidDruiver和DruidDataSource都支持PasswordCallback。
• SQL执行日志,Druid提供了不同的LogFilter,能够支持Common-Logging、Log4j和JdkLog,你可以按需要选择相应的LogFilter,监控你应用的数据库访问情况。
• 扩展JDBC,如果你要对JDBC层有编程的需求,可以通过Druid提供的Filter-Chain机制,很方便编写JDBC层的扩展插件。
USE
- 依赖
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.21</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency>
- 配置
spring: datasource: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8 username: root password: root # 数据源选择 type: com.alibaba.druid.pool.DruidDataSource # Spring Boot 默认是不注入这些属性值的,需要自己绑定 # 数据源专有配置 initialSize: 5 minIdle: 5 maxActive: 20 maxWait: 60000 timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 300000 validationQuery: SELECT 1 FROM DUAL testWhileIdle: true testOnBorrow: false testOnReturn: false poolPreparedStatements: true #配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入 #如果允许时报错 java.lang.ClassNotFoundException: org.apache.log4j.Priority #则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j filters: stat,wall,log4j maxPoolPreparedStatementPerConnectionSize: 20 useGlobalDataSourceStat: true connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
- 利用druid性能监控
@Configuration public class DruidConfig { @Bean @ConfigurationProperties(prefix = "spring.datasource") public DataSource druidDataSource() { return new DruidDataSource(); } @Bean public ServletRegistrationBean druidServlet() { //后台监控 ServletRegistrationBean<StatViewServlet> statViewServletRegistration = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*"); HashMap<String, String> initParameters = new HashMap<>(8); //druid web登录验证 initParameters.put("loginUsername", "admin"); initParameters.put("loginPassword", "123"); //允许访问 initParameters.put("allow", ""); //禁止访问 //initParameters.put("guest", "127.0.0.1"); statViewServletRegistration.setInitParameters(initParameters); return statViewServletRegistration; } @Bean public FilterRegistrationBean filterRegistrationBean() { //filter拦截 FilterRegistrationBean<WebStatFilter> webStatFilterRegistrationBean = new FilterRegistrationBean<>(new WebStatFilter()); webStatFilterRegistrationBean.addUrlPatterns("/*"); webStatFilterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*,*.html"); return webStatFilterRegistrationBean; } }
启动报错:
Failed to bind properties under ‘spring.datasource’ to javax.sql.DataSource
2021-07-09 10:46:47.780 WARN 15072 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.boot.context.properties.ConfigurationPropertiesBindException: Error creating bean with name 'druidDataSource': Could not bind properties to 'DataSource' : prefix=spring.datasource, ignoreInvalidFields=false, ignoreUnknownFields=true; nested exception is org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'spring.datasource' to javax.sql.DataSource 2021-07-09 10:46:47.781 INFO 15072 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
原因是: filters: stat,wall,log4j 配置了log4j,去掉filters的log4j或在依赖里加入log4j即可解决。
- druid Web监控
http://localhost:8080/druid/login.html 登录后可查询监控信息。