Spring Boot 使用Druid详解

时间:2021-05-20

Druid是Java语言中最好的数据库连接池,并且能够提供强大的监控和扩展功能,下面来说明如何在 SpringBoot 中配置使用Druid。
步骤:

1. 在pom.xml中加载依赖

2. 在application.properties中加入数据源配置

3. 编写DruidConfiguration,通过@Bean注解的方式注入druid servlet和filter,以便提供监控页面访问

4. 浏览器访问

一、在pom.xml中加入依赖

<dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.18</version> </dependency>

二、在application.properties中加入数据源配置

################## server ################################ server.port=8080 ################## datasource ################################ spring.datasource.url = jdbc:mysql://localhost:3306/spring spring.datasource.username = root spring.datasource.password = 123456 spring.datasource.driverClassName = com.mysql.jdbc.Driver #使用Druid数据源 spring.datasource.type=com.alibaba.druid.pool.DruidDataSource # 下面为连接池的补充设置,应用到上面所有数据源中 # 初始化大小,最小,最大 spring.datasource.initialSize=5 spring.datasource.minIdle=5 spring.datasource.maxActive=20 # 配置获取连接等待超时的时间 spring.datasource.maxWait=60000 # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 spring.datasource.timeBetweenEvictionRunsMillis=60000 # 配置一个连接在池中最小生存的时间,单位是毫秒 spring.datasource.minEvictableIdleTimeMillis=300000 spring.datasource.validationQuery=SELECT 1 FROMDUAL spring.datasource.testWhileIdle=true spring.datasource.testOnBorrow=false spring.datasource.testOnReturn=false # 打开PSCache,并且指定每个连接上PSCache的大小 spring.datasource.poolPreparedStatements=true spring.datasource.maxPoolPreparedStatementPerConnectionSize=20 # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙 spring.datasource.filters=stat,wall,log4j # 通过connectProperties属性来打开mergeSql功能;慢SQL记录 spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 # 合并多个DruidDataSource的监控数据 #spring.datasource.useGlobalDataSourceStat=true ################ Java Persistence Api ########################### # Specify the DBMS spring.jpa.database = MYSQL # Show or not log for each sql query spring.jpa.show-sql = true # Hibernate ddl auto (create, create-drop, update) spring.jpa.hibernate.ddl-auto = update #[org.hibernate.cfg.ImprovedNamingStrategy #org.hibernate.cfg.DefaultNamingStrategy] spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy # stripped before adding them to the entity manager) spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL5Dialect #暂时不用redis,所以none,spring.session.store-type=reids spring.session.store-type=none

以上是我项目中的配置信息,大家只要关注datasource部分即可。

三、编写DruidConfiguration配置类,通过@Bean注解的方式注入druid servlet和filter,以便提供监控页面访问

package com.example.config; import java.sql.SQLException; import javax.sql.DataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.support.http.StatViewServlet; import com.alibaba.druid.support.http.WebStatFilter; /** * 配置druid数据源 * */ @Configuration public class DruidConfiguration { private Logger logger = LoggerFactory.getLogger(DruidConfiguration.class); @Bean public ServletRegistrationBean druidStatViewServlet() { ServletRegistrationBean registrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*"); registrationBean.addInitParameter("allow", "127.0.0.1"); registrationBean.addInitParameter("deny", "192.168.31.234"); registrationBean.addInitParameter("loginUsername", "admin"); registrationBean.addInitParameter("loginPassword", "123456"); registrationBean.addInitParameter("resetEnable", "false"); return registrationBean; } @Bean public FilterRegistrationBean druidWebStatViewFilter() { FilterRegistrationBean registrationBean = new FilterRegistrationBean(new WebStatFilter()); registrationBean.addInitParameter("urlPatterns", "/*"); registrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*"); return registrationBean; } @Bean public DataSource druidDataSource(@Value("${spring.datasource.url}") String url, @Value("${spring.datasource.driverClassName}") String driver, @Value("${spring.datasource.username}") String userName, @Value("${spring.datasource.password}") String password, @Value("${spring.datasource.maxActive}") int maxActive, @Value("${spring.datasource.filters}") String filters, @Value("${spring.datasource.initialSize}") int initialSize, @Value("${spring.datasource.minIdle}") int minIdle, @Value("${spring.datasource.maxWait}") int maxWait, @Value("${spring.datasource.timeBetweenEvictionRunsMillis}") int timeBetweenEvictionRunsMillis, @Value("${spring.datasource.minEvictableIdleTimeMillis}") int minEvictableIdleTimeMillis, @Value("${spring.datasource.validationQuery}") String validationQuery, @Value("${spring.datasource.testWhileIdle}") boolean testWhileIdle, @Value("${spring.datasource.testOnBorrow}") boolean testOnBorrow, @Value("${spring.datasource.testOnReturn}") boolean testOnReturn, @Value("${spring.datasource.poolPreparedStatements}") boolean poolPreparedStatements, @Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}") int maxPoolPreparedStatementPerConnectionSize, @Value("${spring.datasource.connectionProperties}") String connectionProperties, @Value("${spring.datasource.useGlobalDataSourceStat}") boolean useGlobalDataSourceStat ) { DruidDataSource dataSource = new DruidDataSource(); dataSource.setUrl(url); dataSource.setDriverClassName(driver); dataSource.setUsername(userName); dataSource.setPassword(password); dataSource.setMaxActive(maxActive); dataSource.setInitialSize(initialSize); dataSource.setMinIdle(minIdle); dataSource.setMaxWait(maxWait); dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis); dataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis); dataSource.setValidationQuery(validationQuery); dataSource.setTestOnBorrow(testOnBorrow); dataSource.setTestOnReturn(testOnReturn); dataSource.setTestWhileIdle(testWhileIdle); dataSource.setPoolPreparedStatements(poolPreparedStatements); dataSource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize); dataSource.setConnectionProperties(connectionProperties); dataSource.setUseGlobalDataSourceStat(useGlobalDataSourceStat); try { dataSource.setFilters(filters); logger.info("Druid数据源初始化设置成功......"); } catch (SQLException e) { e.printStackTrace(); logger.info("Druid数据源filters设置失败......"); } return dataSource; } }

四、浏览器访问

在浏览器中输入http://localhost:8080/druid/index.html,首次访问需要使用账号和密码登录


在数据源一栏中,所有加"*"标识的都不能为空,,尤其是filter类名,否则会看不到SQL监控数据。

五、查看SQL监控

执行删除某条记录后,查看SQL监控

到这里,我们就把druid配置成功了。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章