springboot 整合Druid

绝地灬酷狼 2022-05-29 11:36 373阅读 0赞
  • springBoot目录

1.Druid

Durid据说是Java语言中最好的一个数据库连接池。能够提供强大的监控和扩展功能。Druid是一个开源项目,源码托管在github上,源代码仓库地址是

[https://github.com/alibaba/druid\](https://github.com/alibaba/druid)

2.如何在Springboot中整合Druid.

项目结构图:

在这里插入图片描述
首先我们需要引入Druid相应的依赖

  1. <dependency>
  2. <groupId>com.alibaba</groupId>
  3. <artifactId>druid</artifactId>
  4. <version>1.0.26</version>
  5. </dependency>

其次在配置文件中配置该连接池(采用yml格式的配置文件)

  1. spring:
  2. datasource:
  3. url: jdbc:mysql://localhost/springboot
  4. driver-class-name: com.mysql.jdbc.Driver
  5. username: root
  6. password:
  7. type: com.alibaba.druid.pool.DruidDataSource
  8. druid:
  9. initial-size: 8
  10. # filter-class-names: stat
  11. filters: stat,config
  12. #初始化连接大小
  13. initial-size: 8
  14. #最小空闲连接数
  15. min-idle: 5
  16. #最大连接数
  17. max-active: 10
  18. #查询超时时间
  19. query-timeout: 6000
  20. #事务查询超时时间
  21. transaction-query-timeout: 6000
  22. #关闭空闲连接超时时间
  23. remove-abandoned-timeout: 1800

spring.datasource.type设置所使用的连接池为druid,
spring.datasource.druid.* 配置连接池的各种属性。

注意:关于spring.datasource.type属性
旧版本不支持 1.3.x开始支持,1.4.0不支持,1.4.1及之后都支持
接着要添加druid的支持类,及是项目结构图中的两个类
1.DruidDataSourceProperties

  1. package com.example.springboot.mysqldemo.util.configuration;
  2. import org.springframework.boot.context.properties.ConfigurationProperties;
  3. import java.util.Properties;
  4. @ConfigurationProperties("spring.datasource.druid")
  5. public class DruidDataSourceProperties {
  6. private Boolean testWhileIdle = true;
  7. private Boolean testOnBorrow;
  8. private String validationQuery = "SELECT 1";
  9. private Boolean useGlobalDataSourceStat;
  10. private String filters;
  11. private Long timeBetweenLogStatsMillis;
  12. private Integer maxSize;
  13. private Boolean clearFiltersEnable;
  14. private Boolean resetStatEnable;
  15. private Integer notFullTimeoutRetryCount;
  16. private Integer maxWaitThreadCount;
  17. private Boolean failFast;
  18. private Boolean phyTimeoutMillis;
  19. private Long minEvictableIdleTimeMillis = 300000L;
  20. private Long maxEvictableIdleTimeMillis;
  21. private Integer initialSize = 5;
  22. private Integer minIdle = 5;
  23. private Integer maxActive = 20;
  24. private Long maxWait = 60000L;
  25. private Long timeBetweenEvictionRunsMillis = 60000L;
  26. private Boolean poolPreparedStatements = true;
  27. private Integer maxPoolPreparedStatementPerConnectionSize = 20;
  28. private Properties connectionProperties = new Properties() {
  29. {
  30. put("druid.stat.mergeSql", "true");
  31. put("druid.stat.slowSqlMillis", "5000");
  32. }};
  33. public Boolean getTestWhileIdle() {
  34. return testWhileIdle;
  35. }
  36. public void setTestWhileIdle(Boolean testWhileIdle) {
  37. this.testWhileIdle = testWhileIdle;
  38. }
  39. public Boolean getTestOnBorrow() {
  40. return testOnBorrow;
  41. }
  42. public void setTestOnBorrow(Boolean testOnBorrow) {
  43. this.testOnBorrow = testOnBorrow;
  44. }
  45. public String getValidationQuery() {
  46. return validationQuery;
  47. }
  48. public void setValidationQuery(String validationQuery) {
  49. this.validationQuery = validationQuery;
  50. }
  51. public Boolean getUseGlobalDataSourceStat() {
  52. return useGlobalDataSourceStat;
  53. }
  54. public void setUseGlobalDataSourceStat(Boolean useGlobalDataSourceStat) {
  55. this.useGlobalDataSourceStat = useGlobalDataSourceStat;
  56. }
  57. public String getFilters() {
  58. return filters;
  59. }
  60. public void setFilters(String filters) {
  61. this.filters = filters;
  62. }
  63. public Long getTimeBetweenLogStatsMillis() {
  64. return timeBetweenLogStatsMillis;
  65. }
  66. public void setTimeBetweenLogStatsMillis(Long timeBetweenLogStatsMillis) {
  67. this.timeBetweenLogStatsMillis = timeBetweenLogStatsMillis;
  68. }
  69. public Integer getMaxSize() {
  70. return maxSize;
  71. }
  72. public void setMaxSize(Integer maxSize) {
  73. this.maxSize = maxSize;
  74. }
  75. public Boolean getClearFiltersEnable() {
  76. return clearFiltersEnable;
  77. }
  78. public void setClearFiltersEnable(Boolean clearFiltersEnable) {
  79. this.clearFiltersEnable = clearFiltersEnable;
  80. }
  81. public Boolean getResetStatEnable() {
  82. return resetStatEnable;
  83. }
  84. public void setResetStatEnable(Boolean resetStatEnable) {
  85. this.resetStatEnable = resetStatEnable;
  86. }
  87. public Integer getNotFullTimeoutRetryCount() {
  88. return notFullTimeoutRetryCount;
  89. }
  90. public void setNotFullTimeoutRetryCount(Integer notFullTimeoutRetryCount) {
  91. this.notFullTimeoutRetryCount = notFullTimeoutRetryCount;
  92. }
  93. public Integer getMaxWaitThreadCount() {
  94. return maxWaitThreadCount;
  95. }
  96. public void setMaxWaitThreadCount(Integer maxWaitThreadCount) {
  97. this.maxWaitThreadCount = maxWaitThreadCount;
  98. }
  99. public Boolean getFailFast() {
  100. return failFast;
  101. }
  102. public void setFailFast(Boolean failFast) {
  103. this.failFast = failFast;
  104. }
  105. public Boolean getPhyTimeoutMillis() {
  106. return phyTimeoutMillis;
  107. }
  108. public void setPhyTimeoutMillis(Boolean phyTimeoutMillis) {
  109. this.phyTimeoutMillis = phyTimeoutMillis;
  110. }
  111. public Long getMinEvictableIdleTimeMillis() {
  112. return minEvictableIdleTimeMillis;
  113. }
  114. public void setMinEvictableIdleTimeMillis(Long minEvictableIdleTimeMillis) {
  115. this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
  116. }
  117. public Long getMaxEvictableIdleTimeMillis() {
  118. return maxEvictableIdleTimeMillis;
  119. }
  120. public void setMaxEvictableIdleTimeMillis(Long maxEvictableIdleTimeMillis) {
  121. this.maxEvictableIdleTimeMillis = maxEvictableIdleTimeMillis;
  122. }
  123. public Integer getInitialSize() {
  124. return initialSize;
  125. }
  126. public void setInitialSize(Integer initialSize) {
  127. this.initialSize = initialSize;
  128. }
  129. public Integer getMinIdle() {
  130. return minIdle;
  131. }
  132. public void setMinIdle(Integer minIdle) {
  133. this.minIdle = minIdle;
  134. }
  135. public Integer getMaxActive() {
  136. return maxActive;
  137. }
  138. public void setMaxActive(Integer maxActive) {
  139. this.maxActive = maxActive;
  140. }
  141. public Long getMaxWait() {
  142. return maxWait;
  143. }
  144. public void setMaxWait(Long maxWait) {
  145. this.maxWait = maxWait;
  146. }
  147. public Long getTimeBetweenEvictionRunsMillis() {
  148. return timeBetweenEvictionRunsMillis;
  149. }
  150. public void setTimeBetweenEvictionRunsMillis(Long timeBetweenEvictionRunsMillis) {
  151. this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
  152. }
  153. public Boolean getPoolPreparedStatements() {
  154. return poolPreparedStatements;
  155. }
  156. public void setPoolPreparedStatements(Boolean poolPreparedStatements) {
  157. this.poolPreparedStatements = poolPreparedStatements;
  158. }
  159. public Integer getMaxPoolPreparedStatementPerConnectionSize() {
  160. return maxPoolPreparedStatementPerConnectionSize;
  161. }
  162. public void setMaxPoolPreparedStatementPerConnectionSize(Integer maxPoolPreparedStatementPerConnectionSize) {
  163. this.maxPoolPreparedStatementPerConnectionSize = maxPoolPreparedStatementPerConnectionSize;
  164. }
  165. public Properties getConnectionProperties() {
  166. return connectionProperties;
  167. }
  168. public void setConnectionProperties(Properties connectionProperties) {
  169. this.connectionProperties = connectionProperties;
  170. }
  171. public Properties toProperties() {
  172. Properties properties = new Properties();
  173. notNullAdd(properties, "testWhileIdle", this.testWhileIdle);
  174. notNullAdd(properties, "testOnBorrow", this.testOnBorrow);
  175. notNullAdd(properties, "validationQuery", this.validationQuery);
  176. notNullAdd(properties, "useGlobalDataSourceStat", this.useGlobalDataSourceStat);
  177. notNullAdd(properties, "filters", this.filters);
  178. notNullAdd(properties, "timeBetweenLogStatsMillis", this.timeBetweenLogStatsMillis);
  179. notNullAdd(properties, "stat.sql.MaxSize", this.maxSize);
  180. notNullAdd(properties, "clearFiltersEnable", this.clearFiltersEnable);
  181. notNullAdd(properties, "resetStatEnable", this.resetStatEnable);
  182. notNullAdd(properties, "notFullTimeoutRetryCount", this.notFullTimeoutRetryCount);
  183. notNullAdd(properties, "maxWaitThreadCount", this.maxWaitThreadCount);
  184. notNullAdd(properties, "failFast", this.failFast);
  185. notNullAdd(properties, "phyTimeoutMillis", this.phyTimeoutMillis);
  186. notNullAdd(properties, "minEvictableIdleTimeMillis", this.minEvictableIdleTimeMillis);
  187. notNullAdd(properties, "maxEvictableIdleTimeMillis", this.maxEvictableIdleTimeMillis);
  188. notNullAdd(properties, "initialSize", this.initialSize);
  189. notNullAdd(properties, "minIdle", this.minIdle);
  190. notNullAdd(properties, "maxActive", this.maxActive);
  191. notNullAdd(properties, "maxWait", this.maxWait);
  192. notNullAdd(properties, "timeBetweenEvictionRunsMillis", this.timeBetweenEvictionRunsMillis);
  193. notNullAdd(properties, "poolPreparedStatements", this.poolPreparedStatements);
  194. notNullAdd(properties, "maxPoolPreparedStatementPerConnectionSize", this.maxPoolPreparedStatementPerConnectionSize);
  195. return properties;
  196. }
  197. private void notNullAdd(Properties properties, String key, Object value) {
  198. if (value != null) {
  199. properties.setProperty("druid." + key, value.toString());
  200. }
  201. }
  202. }

2.DruidConfiguration

  1. package com.example.springboot.mysqldemo.util.configuration;
  2. import com.alibaba.druid.pool.DruidDataSource;
  3. import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
  4. import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
  5. import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
  6. import org.springframework.boot.context.properties.EnableConfigurationProperties;
  7. import org.springframework.context.annotation.Bean;
  8. import org.springframework.context.annotation.Configuration;
  9. @Configuration
  10. @ConditionalOnClass({DruidDataSource.class})
  11. @ConditionalOnProperty(
  12. name = {"spring.datasource.type"},
  13. havingValue = "com.alibaba.druid.pool.DruidDataSource",
  14. matchIfMissing = true
  15. )
  16. @EnableConfigurationProperties(DruidDataSourceProperties.class)
  17. public class DruidConfiguration {
  18. @Bean
  19. public DruidDataSource dataSource(DataSourceProperties dataSourceProperties, DruidDataSourceProperties druidDataSourceProperties) {
  20. DruidDataSource druidDataSource = dataSourceProperties.initializeDataSourceBuilder().type(DruidDataSource.class).build();
  21. druidDataSource.configFromPropety(druidDataSourceProperties.toProperties());
  22. druidDataSource.setInitialSize(druidDataSourceProperties.getInitialSize());
  23. druidDataSource.setMinIdle(druidDataSourceProperties.getMinIdle());
  24. druidDataSource.setMaxActive(druidDataSourceProperties.getMaxActive());
  25. druidDataSource.setMaxWait(druidDataSourceProperties.getMaxWait());
  26. druidDataSource.setConnectProperties(druidDataSourceProperties.getConnectionProperties());
  27. return druidDataSource;
  28. }
  29. }

至此druid就整合到springboot中了。

3.Druid的监控配置.

首先配置监控界面的servlet

  1. package com.example.springboot.mysqldemo.util.servlet;
  2. import javax.servlet.annotation.WebInitParam;
  3. import javax.servlet.annotation.WebServlet;
  4. import com.alibaba.druid.support.http.StatViewServlet;
  5. @WebServlet(urlPatterns = { "/druid/*" }, initParams = { @WebInitParam(name = "loginUsername", value = "root"), @WebInitParam(name = "loginPassword", value = "1234") })
  6. public class DruidStatViewServlet extends StatViewServlet {
  7. private static final long serialVersionUID = 1L;
  8. }

配置过滤器

  1. package com.example.springboot.mysqldemo.util.filter;
  2. import javax.servlet.annotation.WebFilter;
  3. import javax.servlet.annotation.WebInitParam;
  4. import com.alibaba.druid.support.http.WebStatFilter;
  5. /**
  6. * @author wujing
  7. */
  8. @WebFilter(filterName = "druidWebStatFilter", urlPatterns = "/*", initParams = { @WebInitParam(name = "exclusions", value = "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*") })
  9. public class DruidWebStatFilter extends WebStatFilter {
  10. }

最后启动tomact,测试链接http://localhost:8080/druid/login.html
这里写图片描述

但要配置sql监控则在配置文件中添加如下内容

  1. spring.datasource.druid.filters: stat,config

配置spring监控
在resouce文件夹下添加配置文件druid-bean.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="
  5. http://www.springframework.org/schema/beans
  6. http://www.springframework.org/schema/beans/spring-beans.xsd
  7. http://www.springframework.org/schema/aop
  8. http://www.springframework.org/schema/aop/spring-aop.xsd">
  9. <!-- 配置_Druid和Spring关联监控配置 -->
  10. <bean id="druid-stat-interceptor"
  11. class="com.alibaba.druid.support.spring.stat.DruidStatInterceptor" />
  12. <!-- 方法名正则匹配拦截配置 -->
  13. <bean id="druid-stat-pointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut" scope="prototype">
  14. <property name="patterns">
  15. <list>
  16. <value>com.example.springboot.mysqldemo.controller.*</value>
  17. </list>
  18. </property>
  19. </bean>
  20. <aop:config proxy-target-class="true">
  21. <aop:advisor advice-ref="druid-stat-interceptor" pointcut-ref="druid-stat-pointcut"></aop:advisor>
  22. </aop:config>
  23. </beans>

在需要添加监控的Controller下注解

  1. @ImportResource(locations = { "classpath:druid-bean.xml" })

例:

  1. package com.example.springboot.mysqldemo.controller;
  2. import com.example.springboot.mysqldemo.dao.UserInfoDao;
  3. import com.example.springboot.mysqldemo.model.UserInfo;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.context.annotation.ImportResource;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import org.springframework.web.bind.annotation.RestController;
  8. import java.util.List;
  9. @RestController
  10. @RequestMapping("/index")
  11. @ImportResource(locations = { "classpath:druid-bean.xml" })
  12. public class IndexController {
  13. @Autowired
  14. private UserInfoDao userInfoDao;
  15. @RequestMapping("/getInofo")
  16. public List<UserInfo> getInofo() {
  17. List<UserInfo> userInfos = userInfoDao.findAll();
  18. return userInfos;
  19. }
  20. }

druid还可以进行sql监听等扩展功能。。。。待续

发表评论

表情:
评论列表 (有 0 条评论,373人围观)

还没有评论,来说两句吧...

相关阅读

    相关 SpringBoot整合Druid

    SpringBoot整合Druid 简介:Druid是阿里巴巴提供的数据库连接池,文本讲解SpringBoot整合Druid。 创建项目 ![在这里插入图片描述]

    相关 Springboot 整合 Druid

    Druid( [阿里巴巴开源项目 Druid][Druid])首先是一个数据库连接池,但它不仅仅是一个数据库连接池,它还包含一个ProxyDriver,一系列内置的JDBC组件