springboot——数据层访问搭建 集成Duid连接池
springboot中默认是使用的tomcat的连接池,如果我们想要第三方的连接池,我们这么配置呢?
首先在application.yml文件中注释掉之前数据库的配置,重新用druid的方式配置:
#spring:
#datasource:
# driver-class-name: com.mysql.jdbc.Driver
# url: jdbc:mysql://127.0.0.1:3306/house
#username: root
#password: root
mybatis.config-location = classpath:/mybatis/mybatis-config.xml
spring.druid.url = jdbc:mysql://127.0.0.1:3306/house
spring.druid.username = root
spring.druid.password = root
spring.druid.driverClassName = com.mysql.jdbc.Driver
spring.druid.initialSize=5
spring.druid.minIdle=5
spring.druid.maxActive=20
spring.druid.maxWait=10000
spring.druid.timeBetweenEvictionRunsMillis=60000
spring.druid.minEvictableIdleTimeMillis=300000
spring.druid.validationQuery=SELECT 1 FROM DUAL
spring.druid.testWhileIdle=true
在pom文件中配置依赖库:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.8</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version> <!--特别注意这个地方版本也不能乱 -->
</dependency>
新建DruidConfig配置文件:
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix="spring.druid") //将配置文件中spring.druid.*配置到DruidDataSource中
@Bean(initMethod="init",destroyMethod="close")
public DruidDataSource dataSource(Filter statFilter) throws SQLException{
DruidDataSource dataSource = new DruidDataSource();
dataSource.setProxyFilters(Lists.newArrayList(statFilter()));
return dataSource;
}
//配置慢连接过滤
@Bean
public Filter statFilter(){
StatFilter filter = new StatFilter();
filter.setSlowSqlMillis(5000);
filter.setLogSlowSql(true);
filter.setMergeSql(true);
return filter;
}
//添加监控,可以帮助我们分析慢sql和每个sql的执行时间
@Bean
public ServletRegistrationBean servletRegistrationBean(){
return new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
}
}
然后启动项目,在浏览器中输入地址http://127.0.0.1:8080/user对数据库中的user表进行查询后,再访问http://127.0.0.1:8080/druid将会显示页面如下,可以对数据源、sql监控等进行查询: