java – 在Spring Boot中使用两个数据源

我在我的项目中使用 Spring Boot 1.3.3和一个数据库,现在我想使用两个具有相同模式但连接不同的数据库.

我想使用相同的存储库,实体并找到方法告诉spring我想要使用哪个数据源,具体取决于具体情况.

解决方法

如果有人有这个问题,我找到了解决方案:

首先,您的application.properties应如下所示:

datasource:
primary:
    url: jdbc:MysqL://localhost:3306/primary_db
    username: your_username
    password: your_password
    driver-class-name: com.MysqL.jdbc.Driver
secondary:
    url: jdbc:MysqL://localhost:3306/secondary_db
    username: your_username
    password: your_password
    driver-class-name: com.MysqL.jdbc.Driver

之后,您必须使用数据库创建枚举:

public enum Database {
    PRIMARY,SECONDARY
}

然后,您创建一个ThreadLocal:

public class Databasethreadcontext {

    private static final ThreadLocal<Database> current = new ThreadLocal<>();

    public static void setCurrentDatabase(Database database) {
        current.set(database);
    }

    public static Object getCurrentDatabase() {
        return current.get();
    }

}

这就是魔术,你必须使用在2007年春季2中实现的AbstractRoutingDataSource:

public class RoutingDataSource extends AbstractRoutingDataSource {

    @Override
    protected Object determineCurrentLookupKey() {
        return Databasethreadcontext.getCurrentDatabase();
    }

}

最后在Spring Boot App中注入一个配置:

@Configuration
public class DatabaseRouter {

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

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

    @Bean
    @Primary
    public DataSource dataSource() {
        Map<Object,Object> targetDatasources = new HashMap<Object,Object>(){{
            put(Database.SECONDARY,secondaryDataSource());
            put(Database.PRIMARY,primaryDataSource());
        }};
        RoutingDataSource routingDataSource = new RoutingDataSource();
        routingDataSource.setDefaultTargetDataSource(primaryDataSource());
        routingDataSource.setTargetDataSources(targetDatasources);
        routingDataSource.afterPropertiesSet();
        return routingDataSource;
    }

}

在每个请求中,如果要在数据库之间进行更改,只需使用此函数:Databasethreadcontext.setCurrentDatabase(Database.PRIMARY);.

此外,您可以同时拥有两个以上的数据库.

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...