springboot+Druid+MybatisPlus整合多数据源(MySQL+postgresql)
    		       		warning:
    		            这篇文章距离上次修改已过423天,其中的内容可能已经有所变动。
    		        
        		                
                整合多数据源的核心步骤如下:
- 配置多个数据源
- 配置多个SqlSessionFactory和SqlSessionTemplate
- 配置多个MybatisPlusInterceptor(如果需要)
- 配置多个DataSource
以下是一个简化的示例配置:
@Configuration
public class DataSourceConfig {
 
    @Bean
    @ConfigurationProperties("spring.datasource.mysql")
    public DataSource mysqlDataSource() {
        return DataSourceBuilder.create().build();
    }
 
    @Bean
    @ConfigurationProperties("spring.datasource.postgresql")
    public DataSource postgresqlDataSource() {
        return DataSourceBuilder.create().build();
    }
 
    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(mysqlDataSource());
        return sqlSessionFactoryBean.getObject();
    }
 
    @Bean
    public SqlSessionFactory sqlSessionFactoryPostgreSQL() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(postgresqlDataSource());
        return sqlSessionFactoryBean.getObject();
    }
 
    @Bean
    public SqlSessionTemplate sqlSessionTemplate() throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory());
    }
 
    @Bean
    public SqlSessionTemplate sqlSessionTemplatePostgreSQL() throws Exception {
        return new SqlSessionTemplate(sqlSessionFactoryPostgreSQL());
    }
}在这个配置中,我们定义了两个数据源mysqlDataSource()和postgresqlDataSource(),并为每个数据源创建了一个SqlSessionFactory和SqlSessionTemplate。
确保在application.properties或application.yml中配置了正确的数据源属性。
spring:
  datasource:
    mysql:
      url: jdbc:mysql://localhost:3306/mydb
      username: myuser
      password: mypassword
      driver-class-name: com.mysql.cj.jdbc.Driver
    postgresql:
      url: jdbc:postgresql://localhost:5432/mydb
      username: pguser
      password: pgpassword
      driver-class-name: org.postgresql.Driver在实际的应用中,你可能还需要配置事务管理器和切换数据源的方法。这样,你就可以在操作数据库时根据业务需求选择合适的数据源。
评论已关闭