註解切換雙資料來源

義先生發表於2020-10-29

使用註解,調取相應的庫

application.yml配置:
spring:
    datasource:
        url: jdbc:sqlite:/appservice/db/app.db
        driver-class-name: org.sqlite.JDBC
        auto-reconnect: true
        max-active: 50
        test-on-borrow: true
    symbol-datasource:
        url: jdbc:sqlite:/appservice/db/symbol.db
        driver-class-name: org.sqlite.JDBC
        auto-reconnect: true
        max-active: 50
        test-on-borrow: true
新增調取哪個資料來源的標記註解,通過註解就能調取相應的庫了
 // 1. 主庫標記註解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface TargetAppDataSource {
}
//  2. 第二個庫的標記註解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface TargetSymbolDataSource {
}

新增資料庫配置Java類
  //1. 主庫配置AppDbConfig.java
@Configuration
@MapperScan(basePackages = {"com.abc.mapper"}, annotationClass = TargetAppDataSource.class, sqlSessionFactoryRef = "appSqlSessionFactory")
public class AppDbConfig {

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

    @Bean(name = "appSqlSessionFactory")
    @Primary
    public SqlSessionFactory appSqlSessionFactory(@Qualifier("appDataSource") DataSource appDataSource) throws Exception {
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(appDataSource());
        sessionFactoryBean.setTypeAliasesPackage("com.abc.domain");
        return sessionFactoryBean.getObject();
    }
}

 // 2. 第二個庫的配置Java類SymbolDbConfig.java
@Configuration
@MapperScan(basePackages = {"com.abc.mapper"}, annotationClass = TargetSymbolDataSource.class, sqlSessionFactoryRef = "symbolSqlSessionFactory")
public class SymbolDbConfig {

    @Bean(name = "symbolDataSource")
    @ConfigurationProperties(prefix = "spring.symbol-datasource")
    public DataSource symbolDataSource(){
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "symbolSqlSessionFactory")
    public SqlSessionFactory symbolSqlSessionFactory(@Qualifier("symbolDataSource") DataSource symbolDataSource) throws Exception {
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(symbolDataSource());
        sessionFactoryBean.setTypeAliasesPackage("com.abc.domain");
        return sessionFactoryBean.getObject();
    }    
}
使用註解,調取相應的庫
//  1.使用App庫
@TargetAppDataSource
public interface AppDao {
……
}

//  2. 使用Symbol庫
@TargetSymbolDataSource
public interface SymbolFileDao {
……
}
請參考下方

SpringBoot2實現多資料來源及分散式事務

SpringBoot專案多資料來源配置

相關文章