当前位置:   article > 正文

springboot整合druid(多数据源配置)_druid多数据源配置 spring boot

druid多数据源配置 spring boot

Druid 是阿里巴巴一个开源项目,之前(hikari 出现之前)一直被认为是Java语言中各方面最好的数据库连接池,并且Druid还能够提供强大的监控和扩展功能,备受软件开发人员推崇。本文主要介绍springboot整合druid流程,及多数据配置。

一、pom引入druid依赖

  1. <dependency>
  2. <groupId>com.alibaba</groupId>
  3. <artifactId>druid-spring-boot-starter</artifactId>
  4. <version>1.1.10</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>com.alibaba</groupId>
  8. <artifactId>druid</artifactId>
  9. <version>1.1.10</version>
  10. </dependency>

二、properties或yml文件配置数据源信息(SQLServer、mySQL多数据源)

  1. ## SQLServer数据源信息
  2. spring.datasource.druid.sqlserver.type=com.alibaba.druid.pool.DruidDataSource
  3. spring.datasource.druid.sqlserver.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
  4. spring.datasource.druid.sqlserver.url=jdbc:sqlserver://192.168.1.8:1433;DatabaseName=myDB;useUnicode=true;characterEncoding=utf8;characterSetResults=utf8;allowMultiQueries=true;multiStatementAllow=true
  5. spring.datasource.druid.sqlserver.username=sa
  6. spring.datasource.druid.sqlserver.password=DBadmin
  7. spring.datasource.druid.sqlserver.initial-size=5
  8. spring.datasource.druid.sqlserver.min-idle=5
  9. spring.datasource.druid.sqlserver.max-active=300
  10. spring.datasource.druid.sqlserver.max-wait=30000
  11. spring.datasource.druid.sqlserver.time-between-eviction-runs-millis=60000
  12. spring.datasource.druid.sqlserver.min-evictable-idle-time-millis=30000
  13. spring.datasource.druid.sqlserver.validation-query=SELECT 1
  14. spring.datasource.druid.sqlserver.test-while-idle=true
  15. spring.datasource.druid.sqlserver.test-on-borrow=false
  16. spring.datasource.druid.sqlserver.test-on-return=false
  17. spring.datasource.druid.sqlserver.pool-prepared-statements=true
  18. spring.datasource.druid.sqlserver.max-pool-prepared-statement-per-connection-size=20
  19. spring.datasource.druid.sqlserver.filters=stat
  20. spring.datasource.druid.sqlserver.connection-properties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
  21. spring.datasource.druid.sqlserver.use-global-data-source-stat=true
  22. ## mySql数据源信息
  23. spring.datasource.druid.mysql.type=com.alibaba.druid.pool.DruidDataSource
  24. spring.datasource.druid.mysql.driver-class-name=com.mysql.jdbc.Driver
  25. spring.datasource.druid.mysql.url=jdbc:sqlserver://192.168.1.8:3306;DatabaseName=myDB;useUnicode=true;characterEncoding=utf8;characterSetResults=utf8;allowMultiQueries=true;multiStatementAllow=true
  26. spring.datasource.druid.mysql.username=sa
  27. spring.datasource.druid.mysql.password=DBadmin
  28. spring.datasource.druid.mysql.initial-size=5
  29. spring.datasource.druid.mysql.min-idle=5
  30. spring.datasource.druid.mysql.max-active=300
  31. spring.datasource.druid.mysql.max-wait=30000
  32. spring.datasource.druid.mysql.time-between-eviction-runs-millis=60000
  33. spring.datasource.druid.mysql.min-evictable-idle-time-millis=30000
  34. spring.datasource.druid.mysql.validation-query=SELECT 1
  35. spring.datasource.druid.mysql.test-while-idle=true
  36. spring.datasource.druid.mysql.test-on-borrow=false
  37. spring.datasource.druid.mysql.test-on-return=false
  38. spring.datasource.druid.mysql.pool-prepared-statements=true
  39. spring.datasource.druid.mysql.max-pool-prepared-statement-per-connection-size=20
  40. spring.datasource.druid.mysql.filters=stat
  41. spring.datasource.druid.mysql.connection-properties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
  42. spring.datasource.druid.mysql.use-global-data-source-stat=true

常用属性参数信息:

属性说明
type连接池类型
driver-class-name数据库驱动类型
url数据库连接地址
username数据库账号
password数据库密码
initial-size初始化连接数
min-idle最小活跃连接数
max-active最大活跃连接数
max-wait连接最大等待(超时)时间(毫秒)
time-between-eviction-runs-millis检测连接并进行回收处理的时间间隔数(毫秒)
min-evictable-idle-time-millis连接在数据池中最短生存时间(毫秒)
validation-query测试验证连接
test-while-idle取用连接时,通过与回收时间比较检测是否有效
test-on-borrow取用连接时,检测是否有效
test-on-return归还连接时,检测是否有效
pool-prepared-statements是否缓存preparedStatement
max-pool-prepared-statement-per-connection-sizepreparedStatement大小
filters拦截filter:监控SQL、防火墙或日志等
connection-properties打开mergeSql功能,记录慢SQL
use-global-data-source-stat合并多个datasource监控数据
…………

三、SQLServerSettings.java:属性配置文件(以SQLServer为例)

  1. package com.example.demo.config;
  2. import org.springframework.boot.context.properties.ConfigurationProperties;
  3. import org.springframework.stereotype.Component;
  4. @Component
  5. //properties文件中获取SQLServer属性信息
  6. @ConfigurationProperties(prefix = "spring.datasource.druid.sqlserver")
  7. public class SQLServerSettings {
  8. private String type;
  9. private String driverClassName;
  10. private String url;
  11. private String username;
  12. private String password;
  13. private Integer initialSize;
  14. private Integer minIdle;
  15. private Integer maxActive;
  16. private Long maxWait;
  17. private Long timeBetweenEvictionRunsMillis;
  18. private Long minEvictableIdleTimeMillis;
  19. private String validationQuery;
  20. private boolean testWhileIdle;
  21. private boolean testOnBorrow;
  22. private boolean testOnReturn;
  23. private boolean poolPreparedStatements;
  24. private Integer maxPoolPreparedStatementPerConnectionSize;
  25. private String filters;
  26. private String connectionProperties;
  27. private boolean useGlobalDataSourceStat;
  28. public String getType() {
  29. return type;
  30. }
  31. public void setType(String type) {
  32. this.type = type;
  33. }
  34. public String getDriverClassName() {
  35. return driverClassName;
  36. }
  37. public void setDriverClassName(String driverClassName) {
  38. this.driverClassName = driverClassName;
  39. }
  40. public String getUrl() {
  41. return url;
  42. }
  43. public void setUrl(String url) {
  44. this.url = url;
  45. }
  46. public String getUsername() {
  47. return username;
  48. }
  49. public void setUsername(String username) {
  50. this.username = username;
  51. }
  52. public String getPassword() {
  53. return password;
  54. }
  55. public void setPassword(String password) {
  56. this.password = password;
  57. }
  58. public Integer getInitialSize() {
  59. return initialSize;
  60. }
  61. public void setInitialSize(Integer initialSize) {
  62. this.initialSize = initialSize;
  63. }
  64. public Integer getMinIdle() {
  65. return minIdle;
  66. }
  67. public void setMinIdle(Integer minIdle) {
  68. this.minIdle = minIdle;
  69. }
  70. public Integer getMaxActive() {
  71. return maxActive;
  72. }
  73. public void setMaxActive(Integer maxActive) {
  74. this.maxActive = maxActive;
  75. }
  76. public Long getMaxWait() {
  77. return maxWait;
  78. }
  79. public void setMaxWait(Long maxWait) {
  80. this.maxWait = maxWait;
  81. }
  82. public Long getTimeBetweenEvictionRunsMillis() {
  83. return timeBetweenEvictionRunsMillis;
  84. }
  85. public void setTimeBetweenEvictionRunsMillis(Long timeBetweenEvictionRunsMillis) {
  86. this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
  87. }
  88. public Long getMinEvictableIdleTimeMillis() {
  89. return minEvictableIdleTimeMillis;
  90. }
  91. public void setMinEvictableIdleTimeMillis(Long minEvictableIdleTimeMillis) {
  92. this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
  93. }
  94. public String getValidationQuery() {
  95. return validationQuery;
  96. }
  97. public void setValidationQuery(String validationQuery) {
  98. this.validationQuery = validationQuery;
  99. }
  100. public boolean isTestWhileIdle() {
  101. return testWhileIdle;
  102. }
  103. public void setTestWhileIdle(boolean testWhileIdle) {
  104. this.testWhileIdle = testWhileIdle;
  105. }
  106. public boolean isTestOnBorrow() {
  107. return testOnBorrow;
  108. }
  109. public void setTestOnBorrow(boolean testOnBorrow) {
  110. this.testOnBorrow = testOnBorrow;
  111. }
  112. public boolean isTestOnReturn() {
  113. return testOnReturn;
  114. }
  115. public void setTestOnReturn(boolean testOnReturn) {
  116. this.testOnReturn = testOnReturn;
  117. }
  118. public boolean isPoolPreparedStatements() {
  119. return poolPreparedStatements;
  120. }
  121. public void setPoolPreparedStatements(boolean poolPreparedStatements) {
  122. this.poolPreparedStatements = poolPreparedStatements;
  123. }
  124. public Integer getMaxPoolPreparedStatementPerConnectionSize() {
  125. return maxPoolPreparedStatementPerConnectionSize;
  126. }
  127. public void setMaxPoolPreparedStatementPerConnectionSize(Integer maxPoolPreparedStatementPerConnectionSize) {
  128. this.maxPoolPreparedStatementPerConnectionSize = maxPoolPreparedStatementPerConnectionSize;
  129. }
  130. public String getFilters() {
  131. return filters;
  132. }
  133. public void setFilters(String filters) {
  134. this.filters = filters;
  135. }
  136. public String getConnectionProperties() {
  137. return connectionProperties;
  138. }
  139. public void setConnectionProperties(String connectionProperties) {
  140. this.connectionProperties = connectionProperties;
  141. }
  142. public boolean isUseGlobalDataSourceStat() {
  143. return useGlobalDataSourceStat;
  144. }
  145. public void setUseGlobalDataSourceStat(boolean useGlobalDataSourceStat) {
  146. this.useGlobalDataSourceStat = useGlobalDataSourceStat;
  147. }
  148. }

四、SQLServerConfig.java:数据源配置信息(以SQLServer为例)

  1. package com.example.demo.config;
  2. import java.util.Properties;
  3. import javax.sql.DataSource;
  4. import org.apache.ibatis.session.SqlSessionFactory;
  5. import org.mybatis.spring.SqlSessionFactoryBean;
  6. import org.mybatis.spring.SqlSessionTemplate;
  7. import org.mybatis.spring.annotation.MapperScan;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.beans.factory.annotation.Qualifier;
  10. import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
  11. import org.springframework.boot.context.properties.ConfigurationProperties;
  12. import org.springframework.boot.web.servlet.ServletRegistrationBean;
  13. import org.springframework.context.annotation.Bean;
  14. import org.springframework.context.annotation.Configuration;
  15. import org.springframework.context.annotation.Primary;
  16. import org.springframework.core.io.ClassPathResource;
  17. import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
  18. import com.alibaba.druid.pool.DruidDataSource;
  19. import com.alibaba.druid.support.http.StatViewServlet;
  20. @Configuration
  21. //扫描注入SQLServer数据访问层DAO
  22. @MapperScan(basePackages = "com.example.demo.dao.sqlServerDao", sqlSessionTemplateRef = "sqlServerSqlSessionTemplate")
  23. public class SQLServerConfig {
  24. @Autowired
  25. private SQLServerSettings sqlServerSettings;
  26. @Bean(name = "sqlServerDataSource")
  27. @ConfigurationProperties("spring.datasource.druid.sqlserver.*")
  28. public DataSource DataSource(DataSourceProperties properties) throws Exception{
  29. DruidDataSource dataSource = new DruidDataSource();
  30. dataSource.setDriverClassName(sqlServerSettings.getDriverClassName());
  31. dataSource.setUrl(sqlServerSettings.getUrl());
  32. dataSource.setUsername(sqlServerSettings.getUsername());
  33. dataSource.setPassword(sqlServerSettings.getPassword());
  34. dataSource.setInitialSize(sqlServerSettings.getInitialSize());
  35. dataSource.setMinIdle(sqlServerSettings.getMinIdle());
  36. dataSource.setMaxActive(sqlServerSettings.getMaxActive());
  37. dataSource.setMaxWait(sqlServerSettings.getMaxWait());
  38. dataSource.setTimeBetweenEvictionRunsMillis(sqlServerSettings.getTimeBetweenEvictionRunsMillis());
  39. dataSource.setMinEvictableIdleTimeMillis(sqlServerSettings.getMinEvictableIdleTimeMillis());
  40. String validationQuery = sqlServerSettings.getValidationQuery();
  41. if (validationQuery != null && !"".equals(validationQuery)) {
  42. dataSource.setValidationQuery(validationQuery);
  43. }
  44. dataSource.setTestWhileIdle(sqlServerSettings.isTestWhileIdle());
  45. dataSource.setTestOnBorrow(sqlServerSettings.isTestOnBorrow());
  46. dataSource.setTestOnReturn(sqlServerSettings.isTestOnReturn());
  47. if(sqlServerSettings.isPoolPreparedStatements()){
  48. dataSource.setMaxPoolPreparedStatementPerConnectionSize(sqlServerSettings.getMaxPoolPreparedStatementPerConnectionSize());
  49. }
  50. dataSource.setFilters(sqlServerSettings.getFilters());
  51. String connectionPropertiesStr = sqlServerSettings.getConnectionProperties();
  52. if(connectionPropertiesStr != null && !"".equals(connectionPropertiesStr)){
  53. Properties connectProperties = new Properties();
  54. String[] propertiesList = connectionPropertiesStr.split(";");
  55. for(String propertiesTmp:propertiesList){
  56. String[] obj = propertiesTmp.split("=");
  57. String key = obj[0];
  58. String value = obj[1];
  59. connectProperties.put(key,value);
  60. }
  61. dataSource.setConnectProperties(connectProperties);
  62. }
  63. dataSource.setUseGlobalDataSourceStat(sqlServerSettings.isUseGlobalDataSourceStat());
  64. return dataSource;
  65. }
  66. @Bean(name="sqlServerSqlSessionFactroy")
  67. public SqlSessionFactory sqlServerSqlSessionFactroy(@Qualifier("sqlServerDataSource") DataSource dataSource) throws Exception{
  68. SqlSessionFactoryBean factoryBean=new SqlSessionFactoryBean();
  69. factoryBean.setDataSource(dataSource);
  70. factoryBean.setConfigLocation(new ClassPathResource("mybatis/mybatis-config.xml"));
  71. factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/*/*.xml"));
  72. return factoryBean.getObject();
  73. }
  74. @Primary
  75. @Bean(name="sqlServerSqlSessionTemplate")
  76. public SqlSessionTemplate sqlServerSqlSessionTemplate(@Qualifier("sqlServerSqlSessionFactroy") SqlSessionFactory sqlSessionFactory) throws Exception{
  77. return new SqlSessionTemplate(sqlSessionFactory);
  78. }
  79. @Bean
  80. //druid监控配置
  81. public ServletRegistrationBean<StatViewServlet> druidServlet() {
  82. ServletRegistrationBean<StatViewServlet> servletRegistrationBean = new ServletRegistrationBean<StatViewServlet>(new StatViewServlet(), "/druid/*");
  83. //白名单(多个IP逗号分隔)
  84. servletRegistrationBean.addInitParameter("allow", "");
  85. //黑名单(多个IP逗号分隔,如果黑名单deny与白名单allow同时存在,deny优先于allow)
  86. servletRegistrationBean.addInitParameter("deny", "");
  87. //用户名
  88. servletRegistrationBean.addInitParameter("loginUsername", "admin");
  89. //密码
  90. servletRegistrationBean.addInitParameter("loginPassword", "admin");
  91. //是否可以重置Druid监控计数器
  92. servletRegistrationBean.addInitParameter("resetEnable", "true");
  93. return servletRegistrationBean ;
  94. }
  95. }

五、SQLServerDaoSupport.java:数据访问层DAO实现类

  1. package com.example.demo.dao.sqlServerDao;
  2. import javax.annotation.Resource;
  3. import org.mybatis.spring.SqlSessionTemplate;
  4. import org.springframework.stereotype.Repository;
  5. @Repository("sqlServerDao")
  6. public class SQLServerDaoSupport implements SQLServerDao {
  7. @Resource(name = "sqlServerSqlSessionTemplate")
  8. private SqlSessionTemplate sqlServerSqlSessionTemplate;
  9. /**
  10. * 保存对象
  11. * @param str
  12. * @param obj
  13. * @return
  14. * @throws Exception
  15. */
  16. public Object save(String str, Object obj) throws Exception {
  17. return sqlServerSqlSessionTemplate.insert(str, obj);
  18. }
  19. /**
  20. * 修改对象
  21. * @param str
  22. * @param obj
  23. * @return
  24. * @throws Exception
  25. */
  26. public Object update(String str, Object obj) throws Exception {
  27. return sqlServerSqlSessionTemplate.update(str, obj);
  28. }
  29. /**
  30. * 删除对象
  31. * @param str
  32. * @param obj
  33. * @return
  34. * @throws Exception
  35. */
  36. public Object delete(String str, Object obj) throws Exception {
  37. return sqlServerSqlSessionTemplate.delete(str, obj);
  38. }
  39. /**
  40. * 查找对象
  41. * @param str
  42. * @param obj
  43. * @return
  44. * @throws Exception
  45. */
  46. public Object findForObject(String str, Object obj) throws Exception {
  47. return sqlServerSqlSessionTemplate.selectOne(str, obj);
  48. }
  49. /**
  50. * 查找对象
  51. * @param str
  52. * @param obj
  53. * @return
  54. * @throws Exception
  55. */
  56. public Object findForList(String str, Object obj) throws Exception {
  57. return sqlServerSqlSessionTemplate.selectList(str, obj);
  58. }
  59. }

mySql数据源配置类似,不再赘述。

再来看一下Service怎样使用:

  1. package com.example.demo.service;
  2. import java.util.HashMap;
  3. import java.util.List;
  4. import javax.annotation.Resource;
  5. import org.springframework.stereotype.Service;
  6. import com.example.demo.dao.sqlServerDao.SQLServerDao;
  7. import com.example.demo.dao.mySqlDao.MySqlDao;
  8. import com.example.demo.entity.User;
  9. @Service
  10. public class UserService {
  11. @Resource(name = "sqlServerDao")
  12. private SQLServerDao sqlServerDao;
  13. @Resource(name = "mySqlDao")
  14. private MySqlDao mySqlDao;
  15. //获取SQLServer数据信息
  16. public List<User> getUserList(HashMap<String, Object> paramMap) throws Exception {
  17. return (List<User>) sqlServerDao.findForList("UserMapper.getUserList", paramMap);
  18. }
  19. //获取MySql数据信息
  20. public List<User> getUserList(HashMap<String, Object> paramMap) throws Exception {
  21. return (List<User>) mySqlDao.findForList("UserMapper.getUserList", paramMap);
  22. }
  23. }

Druid监控信息:

以上,即是springboot整合druid,并实现多数据源的配置过程, 除此之外,我们还可以使用动态数据源配置的方式达到类似功能,文章所介绍的只是一种相对而言逻辑简单、结构清晰的多数据源配置方式。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/210941
推荐阅读
相关标签
  

闽ICP备14008679号