查看: 1499|回复: 0

[Java语言] SpringBoot整合Mybatis使用Druid数据库连接池

发表于 2018-4-16 08:00:05

本文实例为大家分享了SpringBoot整合Mybatis使用Druid数据库连接池的方法,具体内容如下

在SpringBoot项目中,增加如下依赖

  1. <!-- spring mybatis -->
  2. <dependency>
  3. <groupId>org.mybatis.spring.boot</groupId>
  4. <artifactId>mybatis-spring-boot-starter</artifactId>
  5. <version>1.1.1</version>
  6. </dependency>
  7. <!-- mysql -->
  8. <dependency>
  9. <groupId>mysql</groupId>
  10. <artifactId>mysql-connector-java</artifactId>
  11. <scope>runtime</scope>
  12. </dependency>
  13. <!-- druid数据库连接池 -->
  14. <dependency>
  15. <groupId>com.alibaba</groupId>
  16. <artifactId>druid</artifactId>
  17. <version>1.0.26</version>
  18. </dependency>
复制代码

在resource目录下,创建jdbc.properties配置文件,加入以下配置

  1. #数据库配置
  2. spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false
  3. spring.datasource.username=admin
  4. spring.datasource.password=admin
  5. spring.datasource.driver-class-name=com.mysql.jdbc.Driver
  6. # 连接池配置
  7. # 初始化大小,最小,最大
  8. spring.datasource.initialSize=5
  9. spring.datasource.minIdle=5
  10. spring.datasource.maxActive=20
  11. # 配置获取连接等待超时的时间
  12. spring.datasource.maxWait=60000
  13. # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
  14. spring.datasource.timeBetweenEvictionRunsMillis=60000
  15. # 配置一个连接在池中最小生存的时间,单位是毫秒
  16. spring.datasource.minEvictableIdleTimeMillis=300000
  17. # 测试连接是否有效的sql
  18. spring.datasource.validationQuery=select 'x'
  19. # 建议配置为true,不影响性能,并且保证安全性
  20. # 申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效
  21. spring.datasource.testWhileIdle=true
  22. # 申请连接时执行validationQuery检测连接是否有效
  23. spring.datasource.testOnBorrow=false
  24. # 归还连接时执行validationQuery检测连接是否有效
  25. spring.datasource.testOnReturn=false
  26. # 要启用PSCache,必须配置大于0,当大于0时,poolPreparedStatements自动触发修改为true
  27. spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
  28. # 属性类型是字符串,通过别名的方式配置扩展插件,常用的插件有:
  29. # 监控统计用的filter:stat
  30. # 日志用的filter:log4j
  31. # 防御sql注入的filter:wall
  32. spring.datasource.filters=stat,log4j,wall
复制代码

创建数据源配置类DataSourceConfig.java,代码如下

  1. package com.liao.mybatis;
  2. import com.alibaba.druid.pool.DruidDataSource;
  3. import org.mybatis.spring.annotation.MapperScan;
  4. import org.slf4j.Logger;
  5. import org.slf4j.LoggerFactory;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.beans.factory.annotation.Value;
  8. import org.springframework.context.annotation.Bean;
  9. import org.springframework.context.annotation.Configuration;
  10. import org.springframework.context.annotation.PropertySource;
  11. import org.springframework.stereotype.Component;
  12. import javax.sql.DataSource;
  13. import java.sql.SQLException;
  14. /**
  15. * 数据源
  16. *
  17. * @author hongyangliao
  18. * @ClassName: DataSourceConfig
  19. * @Date 18-1-2 下午8:56
  20. */
  21. @Configuration
  22. @MapperScan("com.liao.**.dao")
  23. public class DataSourceConfig {
  24. private static final Logger logger = LoggerFactory.getLogger(DataSourceConfig.class);
  25. @Autowired
  26. private JdbcConfig jdbcConfig;
  27. @Bean
  28. @Primary //在同样的DataSource中,首先使用被标注的DataSource
  29. public DataSource dataSource() {
  30. DruidDataSource druidDataSource = new DruidDataSource();
  31. druidDataSource.setUrl(jdbcConfig.getUrl());
  32. druidDataSource.setUsername(jdbcConfig.getUserName());
  33. druidDataSource.setPassword(jdbcConfig.getPassword());
  34. druidDataSource.setInitialSize(jdbcConfig.getInitialSize());
  35. druidDataSource.setMinIdle(jdbcConfig.getMinIdle());
  36. druidDataSource.setMaxActive(jdbcConfig.getMaxActive());
  37. druidDataSource.setTimeBetweenEvictionRunsMillis(jdbcConfig.getTimeBetweenEvictionRunsMillis());
  38. druidDataSource.setMinEvictableIdleTimeMillis(jdbcConfig.getMinEvictableIdleTimeMillis());
  39. druidDataSource.setValidationQuery(jdbcConfig.getValidationQuery());
  40. druidDataSource.setTestWhileIdle(jdbcConfig.isTestWhileIdle());
  41. druidDataSource.setTestOnBorrow(jdbcConfig.isTestOnBorrow());
  42. druidDataSource.setTestOnReturn(jdbcConfig.isTestOnReturn());
  43. druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(jdbcConfig.getMaxPoolPreparedStatementPerConnectionSize());
  44. try {
  45. druidDataSource.setFilters(jdbcConfig.getFilters());
  46. } catch (SQLException e) {
  47. if (logger.isInfoEnabled()) {
  48. logger.info(e.getMessage(), e);
  49. }
  50. }
  51. return druidDataSource;
  52. }
  53. /**
  54. * Jdbc配置类
  55. *
  56. * @author hongyangliao
  57. * @ClassName: JdbcConfig
  58. * @Date 18-1-2 下午9:00
  59. */
  60. @PropertySource(value = "classpath:jdbc.properties")
  61. @Component
  62. public static class JdbcConfig {
  63. /**
  64. * 数据库用户名
  65. */
  66. @Value("${spring.datasource.username}")
  67. private String userName;
  68. /**
  69. * 驱动名称
  70. */
  71. @Value("${spring.datasource.driver-class-name}")
  72. private String driverClass;
  73. /**
  74. * 数据库连接url
  75. */
  76. @Value("${spring.datasource.url}")
  77. private String url;
  78. /**
  79. * 数据库密码
  80. */
  81. @Value("${spring.datasource.password}")
  82. private String password;
  83. /**
  84. * 数据库连接池初始化大小
  85. */
  86. @Value("${spring.datasource.initialSize}")
  87. private int initialSize;
  88. /**
  89. * 数据库连接池最小最小连接数
  90. */
  91. @Value("${spring.datasource.minIdle}")
  92. private int minIdle;
  93. /**
  94. * 数据库连接池最大连接数
  95. */
  96. @Value("${spring.datasource.maxActive}")
  97. private int maxActive;
  98. /**
  99. * 获取连接等待超时的时间
  100. */
  101. @Value("${spring.datasource.maxWait}")
  102. private long maxWait;
  103. /**
  104. * 多久检测一次
  105. */
  106. @Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
  107. private long timeBetweenEvictionRunsMillis;
  108. /**
  109. * 连接在池中最小生存的时间
  110. */
  111. @Value("${spring.datasource.minEvictableIdleTimeMillis}")
  112. private long minEvictableIdleTimeMillis;
  113. /**
  114. * 测试连接是否有效的sql
  115. */
  116. @Value("${spring.datasource.validationQuery}")
  117. private String validationQuery;
  118. /**
  119. * 申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,检测连接是否有效
  120. */
  121. @Value("${spring.datasource.testWhileIdle}")
  122. private boolean testWhileIdle;
  123. /**
  124. * 申请连接时,检测连接是否有效
  125. */
  126. @Value("${spring.datasource.testOnBorrow}")
  127. private boolean testOnBorrow;
  128. /**
  129. * 归还连接时,检测连接是否有效
  130. */
  131. @Value("${spring.datasource.testOnReturn}")
  132. private boolean testOnReturn;
  133. /**
  134. * PSCache大小
  135. */
  136. @Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")
  137. private int maxPoolPreparedStatementPerConnectionSize;
  138. /**
  139. * 通过别名的方式配置扩展插件
  140. */
  141. @Value("${spring.datasource.filters}")
  142. private String filters;
  143. public String getUserName() {
  144. return userName;
  145. }
  146. public void setUserName(String userName) {
  147. this.userName = userName;
  148. }
  149. public String getDriverClass() {
  150. return driverClass;
  151. }
  152. public void setDriverClass(String driverClass) {
  153. this.driverClass = driverClass;
  154. }
  155. public String getUrl() {
  156. return url;
  157. }
  158. public void setUrl(String url) {
  159. this.url = url;
  160. }
  161. public String getPassword() {
  162. return password;
  163. }
  164. public void setPassword(String password) {
  165. this.password = password;
  166. }
  167. public int getInitialSize() {
  168. return initialSize;
  169. }
  170. public void setInitialSize(int initialSize) {
  171. this.initialSize = initialSize;
  172. }
  173. public int getMinIdle() {
  174. return minIdle;
  175. }
  176. public void setMinIdle(int minIdle) {
  177. this.minIdle = minIdle;
  178. }
  179. public int getMaxActive() {
  180. return maxActive;
  181. }
  182. public void setMaxActive(int maxActive) {
  183. this.maxActive = maxActive;
  184. }
  185. public long getMaxWait() {
  186. return maxWait;
  187. }
  188. public void setMaxWait(long maxWait) {
  189. this.maxWait = maxWait;
  190. }
  191. public long getTimeBetweenEvictionRunsMillis() {
  192. return timeBetweenEvictionRunsMillis;
  193. }
  194. public void setTimeBetweenEvictionRunsMillis(long timeBetweenEvictionRunsMillis) {
  195. this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
  196. }
  197. public long getMinEvictableIdleTimeMillis() {
  198. return minEvictableIdleTimeMillis;
  199. }
  200. public void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis) {
  201. this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
  202. }
  203. public String getValidationQuery() {
  204. return validationQuery;
  205. }
  206. public void setValidationQuery(String validationQuery) {
  207. this.validationQuery = validationQuery;
  208. }
  209. public boolean isTestWhileIdle() {
  210. return testWhileIdle;
  211. }
  212. public void setTestWhileIdle(boolean testWhileIdle) {
  213. this.testWhileIdle = testWhileIdle;
  214. }
  215. public boolean isTestOnBorrow() {
  216. return testOnBorrow;
  217. }
  218. public void setTestOnBorrow(boolean testOnBorrow) {
  219. this.testOnBorrow = testOnBorrow;
  220. }
  221. public boolean isTestOnReturn() {
  222. return testOnReturn;
  223. }
  224. public void setTestOnReturn(boolean testOnReturn) {
  225. this.testOnReturn = testOnReturn;
  226. }
  227. public int getMaxPoolPreparedStatementPerConnectionSize() {
  228. return maxPoolPreparedStatementPerConnectionSize;
  229. }
  230. public void setMaxPoolPreparedStatementPerConnectionSize(int maxPoolPreparedStatementPerConnectionSize) {
  231. this.maxPoolPreparedStatementPerConnectionSize = maxPoolPreparedStatementPerConnectionSize;
  232. }
  233. public String getFilters() {
  234. return filters;
  235. }
  236. public void setFilters(String filters) {
  237. this.filters = filters;
  238. }
  239. }
  240. }
复制代码

创建Session工厂配置类SessionFactoryConfig.java,代码如下

  1. package com.liao.mybatis;
  2. import java.io.IOException;
  3. import javax.sql.DataSource;
  4. import org.mybatis.spring.SqlSessionFactoryBean;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.context.annotation.Bean;
  7. import org.springframework.context.annotation.Configuration;
  8. import org.springframework.core.io.ClassPathResource;
  9. import org.springframework.transaction.annotation.EnableTransactionManagement;
  10. @Configuration
  11. @EnableTransactionManagement // 启注解事务管理,等同于xml配置方式的 <tx:annotation-driven />
  12. public class SessionFactoryConfig {
  13. /**
  14. * mybatis 配置路径
  15. */
  16. private static String MYBATIS_CONFIG = "mybatis-config.xml";
  17. @Autowired
  18. private DataSource dataSource;
  19. /***
  20. * 创建sqlSessionFactoryBean
  21. * 并且设置configtion 如驼峰命名.等等
  22. * 设置mapper 映射路径
  23. * 设置datasource数据源
  24. *
  25. * @Title: createSqlSessionFactoryBean
  26. * @author: hongyangliao
  27. * @Date: 18-1-3 上午9:52
  28. * @param
  29. * @return org.mybatis.spring.SqlSessionFactoryBean sqlSessionFactoryBean实例
  30. * @throws
  31. */
  32. @Bean(name = "sqlSessionFactory")
  33. public SqlSessionFactoryBean createSqlSessionFactoryBean() throws IOException {
  34. SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
  35. // 设置mybatis configuration 扫描路径
  36. sqlSessionFactory.setConfigLocation(new ClassPathResource(MYBATIS_CONFIG));
  37. // 设置datasource
  38. sqlSessionFactory.setDataSource(dataSource);
  39. return sqlSessionFactory;
  40. }
  41. }
复制代码

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



回复

使用道具 举报