springboot集成druid连接池
使用druid连接池主要有几步:
1、添加jar和依赖
<groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>6.0.4</version> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>18.0</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.20</version> <scope>provided</scope> </dependency> <!-- https://mvnrepository.com/artifact/com.alibaba/druid --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.9</version> </dependency>
2、配置文件:
server: port: 1111 spring: application: name: springboothouse druid: druidClassName: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/houseselling?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC username: root password: ***** #最大连接数 maxActive: 30 #最小连接数 minIdle: 5 #获取连接的最大等待时间 maxWait: 10000 #解决mysql8小时的问题 validationgQuery: SELECT 'X' #空闲连接的检查时间间隔 timeBetweenEvictionRunsMillis: 60000 #空闲连接最小空闲时间 minEvictableIdleTimeMillis: 300000
3、配置连接池的监控和慢sql处理
连接池的监控连接:
http://ip:port/ 项目名/druid/或
http://ip:port/ 项目名/druid/index.html即可访问
package com.house.sell.config; import com.alibaba.druid.filter.Filter; import com.alibaba.druid.filter.stat.StatFilter; import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.support.http.StatViewServlet; import com.google.common.collect.Lists; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.sql.DataSource; /** *druid连接池的配置,配置如何处理慢sql, */ @Configuration public class DruidConfig { //这个注解读取配置文件前缀为prefix的配置,将外部的配置文件与这里绑定 @ConfigurationProperties(prefix = "spring.druid") //容器的开启与关闭 @Bean(initMethod = "init",destroyMethod = "close") public DruidDataSource dataSource(){ DruidDataSource dataSource=new DruidDataSource(); dataSource.setProxyFilters(Lists.newArrayList(statFilter())); return dataSource; } //bean注解,成为spring的bean,利用filter将慢sql的日志打印出来 @Bean public Filter statFilter(){ StatFilter statFilter=new StatFilter(); //多长时间定义为慢sql,这里定义为5s statFilter.setSlowSqlMillis(5000); //是否打印出慢日志 statFilter.setLogSlowSql(true); //是否将日志合并起来 statFilter.setMergeSql(true); return statFilter; } //这是配置druid的监控 @Bean public ServletRegistrationBean servletRegistrationBean(){ return new ServletRegistrationBean(new StatViewServlet(),"/druid/*"); } }