SpringBoot2.X实现动态数据源

一、核心原理

动态数据源实现的核心类就是:AbstractRoutingDataSource,在这个类中有五个方法需要特别注意,分别如下:

   //设置目标数据源
    public void setTargetDataSources(Map<Object, Object> targetDataSources) {
        this.targetDataSources = targetDataSources;
    }

    //设置默认数据源
    public void setDefaultTargetDataSource(Object defaultTargetDataSource) {
        this.defaultTargetDataSource = defaultTargetDataSource;
    }

    //选择当前所需数据源
    protected DataSource determineTargetDataSource() {
        Assert.notNull(this.resolvedDataSources, "DataSource router not initialized");
        Object lookupKey = this.determineCurrentLookupKey();
        DataSource dataSource = (DataSource)this.resolvedDataSources.get(lookupKey);
        if (dataSource == null && (this.lenientFallback || lookupKey == null)) {
            dataSource = this.resolvedDefaultDataSource;
        }

        if (dataSource == null) {
            throw new IllegalStateException("Cannot determine target DataSource for lookup key [" + lookupKey + "]");
        } else {
            return dataSource;
        }
    }

    @Nullable
    //选择当前数据源所需K
    protected abstract Object determineCurrentLookupKey();

    //初始化resolveDataSources和defaultDataSources
    public void afterPropertiesSet() {
        if (this.targetDataSources == null) {
            throw new IllegalArgumentException("Property 'targetDataSources' is required");
        } else {
            this.resolvedDataSources = new HashMap(this.targetDataSources.size());
            this.targetDataSources.forEach((key, value) -> {
                Object lookupKey = this.resolveSpecifiedLookupKey(key);
                DataSource dataSource = this.resolveSpecifiedDataSource(value);
                this.resolvedDataSources.put(lookupKey, dataSource);
            });
            if (this.defaultTargetDataSource != null) {
                this.resolvedDefaultDataSource = this.resolveSp
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot 1.5.x 版本支持配置多个数据源,这对于处理高并发、读写分离或者分布式数据库环境非常有用。在1.5.x中,你可以通过`spring.factories`文件或传统的XML配置方式来管理多个数据源。以下是基本的配置步骤: 1. **使用`spring.factories`文件(推荐)**: 在`META-INF/spring.factories`文件中添加以下内容,指定不同的数据源别名和对应的`DataSource`实现: ```properties org.springframework.boot.context.properties.ConfigurationProperties=org.springframework.boot.datasource.DataSourceProperties spring.datasource.master.driver-class-name=com.mysql.jdbc.Driver spring.datasource.master.url=jdbc:mysql://localhost:3306/master_db spring.datasource.master.username=root spring.datasource.master.password=password spring.datasource.secondary.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver spring.datasource.secondary.url=jdbc:sqlserver://localhost:1433/secondary_db spring.datasource.secondary.username=sa spring.datasource.secondary.password=password ``` 2. **配置`application.properties`或`application.yml`**: 如果你更倾向于使用传统的配置文件,可以在`application.properties`或`application.yml`中添加类似的内容: ```properties # application.properties spring.datasource.master.driver-class-name=com.mysql.jdbc.Driver spring.datasource.master.url=jdbc:mysql://localhost:3306/master_db spring.datasource.master.username=root spring.datasource.master.password=password spring.datasource.secondary.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver spring.datasource.secondary.url=jdbc:sqlserver://localhost:1433/secondary_db spring.datasource.secondary.username=sa spring.datasource.secondary.password=password spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect (或对应其他数据库的Dialect) spring.jpa.platform=org.springframework.boot.orm.jpa.vendor.HibernateJpaPlatform ``` 还记得要在`spring.datasource`前加上相应的前缀,如`master.datasource`和`secondary.datasource`。 3. **使用`@Configuration`类和`@Primary`注解**: 如果你想控制哪个数据源作为默认数据源,可以在`DataSource` Bean上使用`@Primary`注解。 4. **配置`DataSourceTransactionManager`**: 如果你想利用Spring Data JPA或事务管理,确保你在`JpaProperties`中设置正确的数据源别名,例如: ```java @Bean public DataSourceTransactionManager transactionManager() { return new DataSourceTransactionManager(masterDataSource()); } ``` 相关问题: 1. 如何在Spring Boot中通过代码动态切换数据源? 2. 有没有什么方法可以避免在生产环境中直接暴露数据源URL和用户名? 3. Spring Boot如何处理不同数据源下的不同事务隔离级别?

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值