Skip to content

Latest commit

History

6 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

MultipleDataSource

使用ssm框架,配置多数据源自动切换

说明

SpringBoot 版本 2.0.3

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>

已经引入了 postgreSQLmysql 的链接库

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>

使用 druid 连接池和 mybatis plus 插件

切换数据源说明

  1. 在配置文件中配置了多个数据源
    spring:
    datasource:
    multiple:
    db1:
    username: postgrespassword: postgresdriverClassName: org.postgresql.Driverurl: jdbc:postgresql://localhost:5432/data_ainitialSize: 5minIdle: 5maxActive: 20db2:
    username: rootpassword: rootdriver-class-name: com.mysql.jdbc.Driverurl: jdbc:mysql:///data_binitialSize: 5minIdle: 5maxActive: 20
  2. 然后在 MyBatiesPlusConfiguration 中注入
    @Bean(name = "db1")
    @ConfigurationProperties(prefix = "spring.datasource.multiple.db1" )
    publicDataSourcedb1() {
    returnDruidDataSourceBuilder.create().build();
    }
    @Bean(name = "db2")
    @ConfigurationProperties(prefix = "spring.datasource.multiple.db2" )
    publicDataSourcedb2() {
    returnDruidDataSourceBuilder.create().build();
    }
  3. 添加到multipleDataSource
    /** * 动态数据源配置 * @return */@Bean@PrimarypublicDataSourcemultipleDataSource(@Qualifier("db1") DataSourcedb1, @Qualifier("db2") DataSourcedb2) {
    MultipleDataSourcemultipleDataSource = newMultipleDataSource();
    Map< Object, Object > targetDataSources = newHashMap<>();
    targetDataSources.put(DataSourceEnum.DB1.getValue(), db1);
    targetDataSources.put(DataSourceEnum.DB2.getValue(), db2);
    //添加数据源multipleDataSource.setTargetDataSources(targetDataSources);
    //设置默认数据源multipleDataSource.setDefaultTargetDataSource(db1);
    returnmultipleDataSource;
    }
  4. 如果需要切换数据源,则在指定的方法上加上@DataSource注解即可
@Override@DataSource(DataSourceEnum.DB2)
publicList<Student> selectList(Wrapper<Student> wrapper) {
returnsuper.selectList(wrapper);
}

About

使用ssm框架,配置多数据源自动切换

Topics

Resources

Stars

7 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages