花花_新世界
从【程序猿】到【程序员】的进化历程

在我们的实际业务中可能会遇到;在一个项目里面读取多个数据库的数据来进行展示,spring对同时配置多个数据源是支持的。

使用到的框架:springboot+mybatis

方法:在配置文件中配置多个数据源,然后通过配置类来获取数据源以及mapper相关的扫描配置

1.pom.xml

 1 <parent>
 2         <groupId>org.springframework.boot</groupId>
 3         <artifactId>spring-boot-starter-parent</artifactId>
 4         <version>1.5.9.RELEASE</version>
 5         <relativePath/>
 6     </parent>
 7   <dependencies>
 8               <!-- druid数据源驱动 -->
 9             <dependency>
10                <groupId>com.alibaba</groupId>
11                <artifactId>druid-spring-boot-starter</artifactId>
12                <version>1.1.0</version>
13             </dependency>
14               <dependency>
15                 <groupId>mysql</groupId>
16                 <artifactId>mysql-connector-java</artifactId>
17             </dependency>
18             <!--mybatis SpringBoot依赖 -->
19             <dependency>
20             <groupId>org.springframework.boot</groupId>
21             <artifactId>spring-boot-starter-web</artifactId>
22         </dependency>
23         
24         <dependency>
25             <groupId>org.springframework.boot</groupId>
26             <artifactId>spring-boot-starter-tomcat</artifactId>
27             <scope>compile</scope>
28         </dependency>
29         
30         <dependency>
31             <groupId>org.springframework.boot</groupId>
32             <artifactId>spring-boot-starter-test</artifactId>
33         </dependency>
34         
35         <!-- aop依赖 -->
36         <dependency>
37             <groupId>org.springframework.boot</groupId>
38             <artifactId>spring-boot-starter-aop</artifactId>
39         </dependency>
40         
41         <!-- mybatis -->
42         <dependency>
43             <groupId>org.mybatis.spring.boot</groupId>
44             <artifactId>mybatis-spring-boot-starter</artifactId>
45             <version>1.3.1</version>
46         </dependency>
47         
48         <!-- 通用mapper -->
49         <dependency>
50             <groupId>tk.mybatis</groupId>
51             <artifactId>mapper-spring-boot-starter</artifactId>
52             <version>1.1.5</version>
53         </dependency>
54             <!-- druid监控依赖 -->
55             <dependency>
56                 <groupId>com.alibaba</groupId>
57                 <artifactId>druid</artifactId>
58                 <version>1.0.28</version>
59             </dependency>
60   </dependencies>

2.application.yml

 1 spring:
 2   datasource:
 3     type: com.alibaba.druid.pool.DruidDataSource
 4     driverClassName: com.mysql.jdbc.Driver
 5     
 6     url: jdbc:mysql://127.0.0.1:3306/test2?useUnicode=true&characterEncoding=utf8
 7     username: root
 8     password: 123456
 9     
10     url2: jdbc:mysql://127.0.0.1:3306/test1?useUnicode=true&characterEncoding=utf8
11     username2: root
12     password2: 123456

3.DruidDBConfig 连接池相关配置

 1 package com.xbz.common.config;
 2  
 3 import com.alibaba.druid.support.http.StatViewServlet;
 4 import com.alibaba.druid.support.http.WebStatFilter;
 5 import org.slf4j.Logger;
 6 import org.slf4j.LoggerFactory;
 7 import org.springframework.boot.web.servlet.FilterRegistrationBean;
 8 import org.springframework.boot.web.servlet.ServletRegistrationBean;
 9 import org.springframework.context.annotation.Bean;
10 import org.springframework.context.annotation.Configuration;
11  
12 /**
13  * Druid监控
14  */
15 @SuppressWarnings("AlibabaRemoveCommentedCode")
16 @Configuration
17 public class DruidDBConfig {
18     private Logger logger = LoggerFactory.getLogger(DruidDBConfig.class);
19  
20     /**
21      * 注册ServletRegistrationBean
22      * @return
23      */
24     @Bean
25     public ServletRegistrationBean druidServlet() {
26         ServletRegistrationBean reg = new ServletRegistrationBean();
27         reg.setServlet(new StatViewServlet());
28         reg.addUrlMappings("/druid/*");
29         reg.addInitParameter("allow", ""); //白名单
30         return reg;
31     }
32  
33     /**
34      * 注册FilterRegistrationBean
35      * @return
36      */
37     @Bean
38     public FilterRegistrationBean filterRegistrationBean() {
39         FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
40         filterRegistrationBean.setFilter(new WebStatFilter());
41         filterRegistrationBean.addUrlPatterns("/*");
42         filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
43         filterRegistrationBean.addInitParameter("profileEnable", "true");
44         filterRegistrationBean.addInitParameter("principalCookieName", "USER_COOKIE");
45         filterRegistrationBean.addInitParameter("principalSessionName", "USER_SESSION");
46         filterRegistrationBean.addInitParameter("DruidWebStatFilter", "/*");
47         return filterRegistrationBean;
48     }
49 }

4.MasterDbConfig 注意读取数据库连接相关的键,以及扫描实体、mapper等

 1 package com.xbz.common.config;
 2  
 3 import com.alibaba.druid.pool.DruidDataSource;
 4 import org.apache.ibatis.session.SqlSessionFactory;
 5 import org.mybatis.spring.SqlSessionFactoryBean;
 6 import org.mybatis.spring.annotation.MapperScan;
 7 import org.slf4j.Logger;
 8 import org.slf4j.LoggerFactory;
 9 import org.springframework.beans.factory.annotation.Qualifier;
10 import org.springframework.beans.factory.annotation.Value;
11 import org.springframework.context.annotation.Bean;
12 import org.springframework.context.annotation.Configuration;
13 import org.springframework.context.annotation.Primary;
14 import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
15 import org.springframework.jdbc.datasource.DataSourceTransactionManager;
16  
17 import javax.sql.DataSource;
18 import java.sql.SQLException;
19  
20  
21 @Configuration
22 @MapperScan(basePackages  = MasterDbConfig.PACKAGE , sqlSessionFactoryRef = "masterSqlSessionFactory")
23 public class MasterDbConfig {
24     private Logger logger = LoggerFactory.getLogger(MasterDbConfig.class);
25     // 精确到 master 目录,以便跟其他数据源隔离
26     static final String PACKAGE = "com.xbz.**.dao.master";
27     private static final String MAPPER_LOCATION = "classpath*:mapper/master/*.xml";
28     private static final String DOMAIN_PACKAGE = "com.xbz.**.domain";
29  
30     @Value("${spring.datasource.url}")
31     private String dbUrl;
32  
33     @Value("${spring.datasource.username}")
34     private String username;
35  
36     @Value("${spring.datasource.password}")
37     private String password;
38  
39     @Value("${spring.datasource.driverClassName}")
40     private String driverClassName;
41  
42  
43     @Bean(name="masterDataSource")   //声明其为Bean实例
44     @Primary  //在同样的DataSource中,首先使用被标注的DataSource
45     public DataSource masterDataSource() {
46         DruidDataSource datasource = new DruidDataSource();
47  
48         datasource.setUrl(this.dbUrl);
49         datasource.setUsername(username);
50         datasource.setPassword(password);
51         datasource.setDriverClassName(driverClassName);
52  
53         return datasource;
54     }
55  
56     @Bean(name = "masterTransactionManager")
57     @Primary
58     public DataSourceTransactionManager masterTransactionManager() {
59         return new DataSourceTransactionManager(masterDataSource());
60     }
61  
62     @Bean(name = "masterSqlSessionFactory")
63     @Primary
64     public SqlSessionFactory masterSqlSessionFactory(@Qualifier("masterDataSource") DataSource masterDataSource)
65             throws Exception {
66         final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
67         sessionFactory.setDataSource(masterDataSource);
68         sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
69                 .getResources(MasterDbConfig.MAPPER_LOCATION));
70         sessionFactory.setTypeAliasesPackage(DOMAIN_PACKAGE);
71         //mybatis 数据库字段与实体类属性驼峰映射配置
72         sessionFactory.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
73         return sessionFactory.getObject();
74     }
75 }

5.ClusterDbConfig 

 1 package com.xbz.common.config;
 2  
 3 import com.alibaba.druid.pool.DruidDataSource;
 4 import org.apache.ibatis.session.SqlSessionFactory;
 5 import org.mybatis.spring.SqlSessionFactoryBean;
 6 import org.mybatis.spring.annotation.MapperScan;
 7 import org.slf4j.Logger;
 8 import org.slf4j.LoggerFactory;
 9 import org.springframework.beans.factory.annotation.Qualifier;
10 import org.springframework.beans.factory.annotation.Value;
11 import org.springframework.context.annotation.Bean;
12 import org.springframework.context.annotation.Configuration;
13 import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
14 import org.springframework.jdbc.datasource.DataSourceTransactionManager;
15  
16 import javax.sql.DataSource;
17 import java.sql.SQLException;
18  
19 /**
20  * 从数据源配置
21  * 若需要配置更多数据源 , 直接在yml中添加数据源配置再增加相应的新的数据源配置类即可
22  */
23 @Configuration
24 @MapperScan(basePackages  = ClusterDbConfig.PACKAGE , sqlSessionFactoryRef = "clusterSqlSessionFactory")
25 public class ClusterDbConfig {
26     private Logger logger = LoggerFactory.getLogger(ClusterDbConfig.class);
27     // 精确到 cluster 目录,以便跟其他数据源隔离
28     static final String PACKAGE = "com.xbz.**.dao.cluster";
29     private static final String MAPPER_LOCATION = "classpath*:mapper/cluster/*.xml";
30     private static final String DOMAIN_PACKAGE = "com.xbz.**.domain";
31  
32     @Value("${spring.datasource.url2}")
33     private String dbUrl;
34  
35     @Value("${spring.datasource.username2}")
36     private String username;
37  
38     @Value("${spring.datasource.password2}")
39     private String password;
40  
41     @Value("${spring.datasource.driverClassName}")
42     private String driverClassName;
43  
44     
45  
46     @Bean(name="clusterDataSource")   //声明其为Bean实例
47     public DataSource clusterDataSource() {
48         DruidDataSource datasource = new DruidDataSource();
49  
50         datasource.setUrl(this.dbUrl);
51         datasource.setUsername(username);
52         datasource.setPassword(password);
53         datasource.setDriverClassName(driverClassName);
54         return datasource;
55     }
56  
57     @Bean(name = "clusterTransactionManager")
58     public DataSourceTransactionManager clusterTransactionManager() {
59         return new DataSourceTransactionManager(clusterDataSource());
60     }
61  
62     @Bean(name = "clusterSqlSessionFactory")
63     public SqlSessionFactory clusterSqlSessionFactory(@Qualifier("clusterDataSource") DataSource culsterDataSource)
64             throws Exception {
65         final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
66         sessionFactory.setDataSource(culsterDataSource);
67         sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
68                 .getResources(ClusterDbConfig.MAPPER_LOCATION));
69         sessionFactory.setTypeAliasesPackage(DOMAIN_PACKAGE);
70         //mybatis 数据库字段与实体类属性驼峰映射配置
71         sessionFactory.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
72         return sessionFactory.getObject();
73     }
74 }

 

 

6.不同的数据源配置不佟的mapper扫描位置,然后需要哪一个数据源就注入哪一个mapper接口即可

 

 这样获取的数据就是来自不同的数据源了,这种方法比较简单。

参考文章:https://blog.csdn.net/qq_38058332/article/details/84325009  

posted on 2020-06-11 11:00  花花_新世界  阅读(2822)  评论(2编辑  收藏  举报