All Downloads are FREE. Search and download functionalities are using the official Maven repository.

matrix.boot.jdbc.config.DynamicDataSourceAutoConfiguration Maven / Gradle / Ivy

The newest version!
package matrix.boot.jdbc.config;

import lombok.extern.slf4j.Slf4j;
import matrix.boot.jdbc.beans.DynamicDataSource;
import matrix.boot.jdbc.beans.MoreDataSource;
import matrix.boot.jdbc.properties.JdbcProperties;
import matrix.boot.jdbc.scanner.DynamicDataSourceSwitchScanner;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 动态数据源自动装配
 * @author wangcheng
 * 2021/8/16
 **/
@EnableConfigurationProperties(JdbcProperties.class)
@ConditionalOnExpression("${matrix.jdbc.enabled} && '${matrix.jdbc.init-type}'.equals('Dynamic')")
@ImportAutoConfiguration(DynamicDataSourceSwitchScanner.class)
@Slf4j
public class DynamicDataSourceAutoConfiguration {

    /**
     * 动态数据源bean创建
     *
     * @param moreDataSource 多数据源信息
     * @return 数据源
     */
    @Bean
    public DataSource dynamicDataSource(MoreDataSource moreDataSource) {
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        //获取主数据库
        dynamicDataSource.setDefaultTargetDataSource(moreDataSource.getMasterDataSource());
        //定义数据库列表
        Map targetDataSources = new HashMap<>();
        Iterator> iterator = moreDataSource.getDataSourceMap().entrySet().iterator();
        //第一个数据库不用放入target, 为主数据库
        iterator.next();
        while (iterator.hasNext()) {
            Map.Entry map = iterator.next();
            targetDataSources.put(map.getKey(), map.getValue());
        }
        dynamicDataSource.setTargetDataSources(targetDataSources);
        log.info("DynamicDataSource init success!");
        return dynamicDataSource;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy