spring boot,mybatis,druid连接池(慢SQL语句打印日志,SQL监控)
pom.xml
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.8</version> </dependency>
application.properties
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
spring.druid.url=jdbc:mysql://127.0.0.1:33062/test?useUnicode=true&amp;characterEncoding=UTF-8&amp;zeroDateTimeBehavior=convertToNull spring.druid.username=root spring.druid.password=766774 spring.druid.maxActive=30 spring.druid.minIdle=5 spring.druid.maxWait=10000 spring.druid.validationQuery=SELECT 'x' spring.druid.timeBetweenEvictionRunsMillis=60000 spring.druid.minEvictableIdleTimeMillis=300000
配置Bean
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import com.alibaba.druid.filter.Filter; import com.alibaba.druid.filter.logging.Log4jFilter; 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; @Configuration public class DruidDataSourceConfiguration { //自动读取application.properties前缀是spring.druid的配置 @Bean(initMethod="init",destroyMethod="close") @ConfigurationProperties(prefix = "spring.druid") public DataSource druidDataSource(Filter statFilter) { DruidDataSource druidDataSource = new DruidDataSource(); druidDataSource.setProxyFilters(Lists.newArrayList(statFilter())); return druidDataSource; } //慢日志 @Bean public StatFilter statFilter(){ StatFilter statFilter = new StatFilter(); statFilter.setMergeSql(true); //超过5000毫秒算是慢SQL statFilter.setSlowSqlMillis(5000); statFilter.setLogSlowSql(true); return statFilter; } //监控SQL配置,直接打开localhost:8080/druid 就可以看到 @Bean public ServletRegistrationBean druidStatViewServletBean(){ ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*"); return servletRegistrationBean; } }
使用
直接打开localhost:8080/druid 就可以监控SQL