使用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>已经引入了 postgreSQL 和 mysql 的链接库
<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 插件
- 在配置文件中配置了多个数据源
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
- 然后在
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(); }
- 添加到
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; }
- 如果需要切换数据源,则在指定的方法上加上
@DataSource注解即可
@Override@DataSource(DataSourceEnum.DB2)
publicList<Student> selectList(Wrapper<Student> wrapper) {
returnsuper.selectList(wrapper);
}