-
Druid是阿里巴巴开源的一个数据源,主要用于java数据库连接池,相比spring推荐的DBCP和hibernate推荐的C3P0、Proxool数据库连接池,Druid在市场上占有绝对的优势,Druid数据源由于有强大的监控特性、可拓展性等特点。
-
使用
- 导入依赖
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>xxx</version> </dependency>
- 配置yml文件
spring: datasource: type: com.alibaba.druid.pool.DruidDataSource #引入druid数据源 #数据源基本信息,也可放在druid下 url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC username: root password: 123456 driver-class-name: com.mysql.cj.jdbc.Driver druid: #SpringBoot因为默认是hikari数据源所以对于其他数据源默认是不注入这些属性的,需要手动配置 #druid数据源专有配置 initialSize: 5 minIdle: 5 maxActive: 20 maxWait: 600000 # 主要配置以上几个即可 timeBetweenEvictionRunsMillis: 600000 minEvictableIdleTimeMillis: 300000 validationQuery: SELECT 1 FROM DUAL testWhileIdle: true testOnBorrow: false testOnReturn: false poolPreparedStatements: true #配置监控统计拦截的filters:stat:监控统计、self4j(使用log4j的记得导入log4j的依赖):日志记录、wall:防御sql注入 此处配置不能遗漏服务sql监控台不能监控sql filter: slf4j: enabled: true stat: enabled: true merge-sql: true slow-sql-millis: 5000 wall: enabled: true #配置stat-view-servlet stat-view-servlet: enabled: true login-username: admin login-password: 123456 reset-enable: false #配置web-stat-filter web-stat-filter: enabled: true
- 创建DruidConfig
@Configuration public class DruidConfig { @Bean @ConfigurationProperties(prefix = "spring.datasource") public DataSource getMyDruidDataSource(){ return new DruidDataSource(); } //配置Druid的监控 //1.配置一个管理后台的Servlet @Bean public ServletRegistrationBean statViewServlet(){ // 记得加上"/druid/*",否则在进行登录页面的重定向过多而无法访问的问题(记得在Google浏览器才会报这个错) ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(),"/druid/*"); Map<String,String> initParams = new HashMap<>(); initParams.put("loginUsername","admin"); initParams.put("loginPassword","123456"); //默认是允许所有访问 //initParams.put("allow",""); //initParams.put("deny","192.168.31.30"); bean.setInitParameters(initParams); return bean; } //2.配置一个web监控的filter @Bean public FilterRegistrationBean webStatFilter(){ FilterRegistrationBean bean = new FilterRegistrationBean(); bean.setFilter(new WebStatFilter()); Map<String,String> initParams = new HashMap<>(); //配置拦截时需要排除的请求 initParams.put("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"); bean.setInitParameters(initParams); bean.setUrlPatterns(Arrays.asList("/*")); return bean; } }