Spring boot实现多数据源的一种方式

参考博客感谢作者

之所以说是一种方式,因为还有一种方式是通过继承AbstractRoutingDataSource来动态选择DataSource路由,通过AOP的方式进行切换。

该程序Dao层实现使用mybatis框架。

该方式实现的思路是:有多少个数据源就写多少个数据源的配置类,mybatis的Mapper接口分别对应放在不同的包下,Mapper.xml文件根据数据源的不同放在不同的目录下。不同的数据源扫描不同的Mapper接口和Mapper.xml文件。

项目结构:

application.properties配置文件

spring.datasource.cluster.driverClassName = com.mysql.jdbc.Driver
spring.datasource.cluster.url = jdbc:mysql://localhost:3306/std1?useUnicode=true&characterEncoding=utf-8
spring.datasource.cluster.username = root
spring.datasource.cluster.password = root


spring.datasource.master.driverClassName = com.mysql.jdbc.Driver
spring.datasource.master.url = jdbc:mysql://localhost:3306/std2?useUnicode=true&characterEncoding=utf-8
spring.datasource.master.username = root
spring.datasource.master.password = root

配置了两个数据源,一个是master,一个是cluster。有多少的数据源,就可以配置多少个数据源。

需要注意的是,Spring boot 2.0以后,数据源url和driveClassName的写法发生了变化,具体可以查找资料。

master数据源配置类

/**
 * mybaits Master库配置类
 * com.wanlihong.multi_mybatis.mapper.master 为Master数据源对应的Mapper接口类
 */
@Configuration
@MapperScan(basePackages = "com.wanlihong.multi_mybatis.mapper.master",sqlSessionTemplateRef = "masterSqlSessionTemplate")
public class MasterDataSourceConfig {

    /**
     * 创建数据源
     *@return DataSource
     */
    @Bean(name = "masterDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.master")
    @Primary
    public DataSource masterDataSource() {
        return DataSourceBuilder.create().build();
    }

    /**
     * 创建工厂
     *@param dataSource
     *@throws Exception
     *@return SqlSessionFactory
     */
    @Bean(name = "masterSqlSessionFactory")
    @Primary
    public SqlSessionFactory masterSqlSessionFactory(@Qualifier("masterDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        //master 数据源对应的mapper.xml
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/master/*.xml"));
        return bean.getObject
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值