SpringBoot多数据源最佳实践__orm基于MybatisPlus

一个SpringBoot有时会涉及多个数据源(多个数据库),不同数据访问就需要切换数据源,比较常用的方案是dynamic-datasource,但是这种鸡肋框架确实没有太大引入项目的必要(而且有时会出现数据源切换失败的情况),我们可以按如下方式手动配置多数据源DataSource!

Github地址:https://github.com/ashe-c0de/multiple_data_source.git    # 需更改数据源配置信息(示例中使用的是Oracle + MySQL)

 

application.yml配置多数据源

spring:
  datasource:
    primary:
      url: jdbc:oracle:thin:@localhost:1522:XE
      username: username
      password: password
      driver-class-name: oracle.jdbc.OracleDriver
      druid:
        initial-size: 5
        min-idle: 5
        max-active: 20
        filters: stat,wall,log4j
    secondary:
      url: jdbc:mysql://localhost:3306/database?serverTimezone=Asia/Shanghai
      username: username
      password: password
      driver-class-name: com.mysql.cj.jdbc.Driver
      druid:
        initial-size: 5
        min-idle: 5
        max-active: 20
        filters: stat,wall,log4j

 

手动配置DataSource

@Configuration
@MapperScan(basePackages = "org.ashe.mapper.primary", sqlSessionFactoryRef = "primarySqlSessionFactory")
public class PrimaryDataSourceConfig {

    @Bean(name = "primaryDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.primary")
    @Primary
    public DataSource primaryDataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean(name = "primarySqlSessionFactory")
    @Primary
    public SqlSessionFactory primarySqlSessionFactory(@Qualifier("primaryDataSource") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/primary/*.xml"));
        return bean.getObject();
    }
}
@Configuration
@MapperScan(basePackages = "org.ashe.mapper.secondary", sqlSessionFactoryRef = "secondarySqlSessionFactory")
public class SecondaryDataSourceConfig {

    @Bean(name = "secondaryDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.secondary")
    public DataSource secondaryDataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean(name = "secondarySqlSessionFactory")
    public SqlSessionFactory secondarySqlSessionFactory(@Qualifier("secondaryDataSource") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/secondary/*.xml"));
        return bean.getObject();
    }
}

 

按图示结构搭建mapper

src
└── main
    ├── java
    │   └── org
    │       └── ashe
    │           ├── config
    │           │   ├── PrimaryDataSourceConfig.java
    │           │   └── SecondaryDataSourceConfig.java
    │           ├── mapper
    │           │   ├── primary
    │           │   │   └── PrimaryMapper.java
    │           │   └── secondary
    │           │       └── SecondaryMapper.java
    │           └── service
    │               └── UserService.java
    └── resources
        ├── application.yml
        └── mapper
            ├── primary
            │   └── PrimaryMapper.xml
            └── secondary
                └── SecondaryMapper.xml

 

如此配置后,无论是使用MybatisPlus的提供的通用CURD方法,还是自己在mapper.xml文件自定义的SQL都能按预期执行,对于事务管理我并未测试(我倾向于假定使用默认的@Transactional注解依旧能实现事务管理,不必单独声明各自特定的事务管理器)

posted @ 2024-06-29 18:11  Ashe|||^_^  阅读(18)  评论(0编辑  收藏  举报