美文网首页Spring Boot实践记录
SpringBoot整合多数据源xml方式

SpringBoot整合多数据源xml方式

作者: Chinesszz | 来源:发表于2017-04-22 10:15 被阅读78次

    项目中遇到需要连接多个数据库,本来使用SpringBoot默认配置连接是非常简单的,但是由于涉及多个数据库,不得不再自定义配置了,一次性整明白,下次就之间copy使用。

    • 1.首先学习一个注解@ConfigurationProperties(prefix = "druid")

    默认注入,配置文件中druid开头的属性。eg:

    druid.url=jdbc:postgresql://139.198.x.x:1x020/account
    druid.url2=jdbc:postgresql://139.198.x.x:1x020/oto_saas
    druid.driver-class=org.postgresql.Driver
    druid.username=root
    druid.password=XXX123
    druid.initial-size=1
    druid.min-idle=1
    druid.max-active=20
    druid.test-on-borrow=true
    druid.timeBetweenEvictionRunsMillis=9000
    
    
    
    
    /**
     *
     * @author liuxin
     * @since 2017/4/19
     */
    @ConfigurationProperties(prefix = "druid")
    public class DruidProperties {
        private String url;
        private String url2;
        private String username;
        private String password;
        private String driverClass;
        private int maxActive;//最大连接数
        private int minIdle;//最小连接数
        private int initialSize;//初始化数量和
        private boolean testOnBorrow;
        private Long timeBetweenEvictionRunsMillis;//心跳
    
    • 2.添加数据源配置A
        /**
         * @Package: pterosaur.account.config.druid
         * @Description: account 数据源1
         * @author: liuxin
         * @date: 17/4/21 下午7:11
         */
        @Configuration
        @EnableConfigurationProperties(DruidProperties.class) //开启属性注入,通过@autowired注入 //注入DruidProerties,就是根据第一个注解,创建的配置类
        @ConditionalOnClass(DruidDataSource.class)//判断这个类是否在classpath中存在
        @ConditionalOnProperty(prefix = "druid", name = "url")
        @MapperScan(basePackages = "pterosaur.account.mapper.account", sqlSessionTemplateRef  = "accountSqlSessionTemplate")//配置实体类包
        public class DruidAutoConfiguration1 {
            @Autowired
            private DruidProperties properties;
        
            @Bean(name = "accountDataSource") 
            @Primary  //DataSource 是一个接口,因为是两个数据源,所以用Primary标记其中一个,防止报错
            public DataSource dataSource() {
                DruidDataSource dataSource = new DruidDataSource();
                dataSource.setUrl(properties.getUrl());
                dataSource.setUsername(properties.getUsername());
                dataSource.setPassword(properties.getPassword());
                dataSource.setTimeBetweenEvictionRunsMillis(properties.getTimeBetweenEvictionRunsMillis());
                if (properties.getInitialSize() > 0) {
                    dataSource.setInitialSize(properties.getInitialSize());
                }
                if (properties.getMinIdle() > 0) {
                    dataSource.setMinIdle(properties.getMinIdle());
                }
                if (properties.getMaxActive() > 0) {
                    dataSource.setMaxActive(properties.getMaxActive());
                }
                dataSource.setTestOnBorrow(properties.isTestOnBorrow());
                try {
                    dataSource.init();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
                return dataSource;
            }
        
        
            @Bean(name = "accountSqlSessionFactory")
            @Primary //同上
            public SqlSessionFactory testSqlSessionFactory(@Qualifier("accountDataSource") DataSource dataSource) throws Exception {
                SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
                bean.setDataSource(dataSource);
                bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/account/*.xml"));
                return bean.getObject(); //配置映射文件地址
            }
        
            @Bean(name = "accountTransactionManager")
            @Primary
            public DataSourceTransactionManager testTransactionManager(@Qualifier("accountDataSource") DataSource dataSource) {
                return new DataSourceTransactionManager(dataSource);
            }
        
            @Bean(name = "accountSqlSessionTemplate")
            @Primary
            public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("accountSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
                return new SqlSessionTemplate(sqlSessionFactory);
            }
        }
    
    • 3.添加数据源配置B
        package pterosaur.account.config.druid;
        
        import com.alibaba.druid.pool.DruidDataSource;
        import org.apache.ibatis.session.SqlSessionFactory;
        import org.mybatis.spring.SqlSessionFactoryBean;
        import org.mybatis.spring.SqlSessionTemplate;
        import org.mybatis.spring.annotation.MapperScan;
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.beans.factory.annotation.Qualifier;
        import org.springframework.boot.autoconfigure.AutoConfigureBefore;
        import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
        import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
        import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
        import org.springframework.boot.context.properties.ConfigurationProperties;
        import org.springframework.boot.context.properties.EnableConfigurationProperties;
        import org.springframework.context.annotation.Bean;
        import org.springframework.context.annotation.Configuration;
        import org.springframework.context.annotation.Primary;
        import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
        import org.springframework.jdbc.datasource.DataSourceTransactionManager;
        
        import javax.sql.DataSource;
        import java.sql.SQLException;
        
        /**
         * @Package: pterosaur.account.config.druid
         * @Description: otosaas 数据源2
         * @author: liuxin
         * @date: 17/4/21 下午7:11
         */
        @Configuration
        @EnableConfigurationProperties(DruidProperties.class)
        @ConditionalOnClass(DruidDataSource.class)
        @ConditionalOnProperty(prefix = "druid", name = "url")
        @MapperScan(basePackages = "pterosaur.account.mapper.otosaas", sqlSessionTemplateRef  = "otoSaaSSqlSessionTemplate")
        public class DruidAutoConfiguration2 {
            @Autowired
            private DruidProperties properties;
        
            @Bean(name = "otoSaaSDataSource")
            public DataSource dataSource() {
                DruidDataSource dataSource = new DruidDataSource();
                dataSource.setUrl(properties.getUrl2());
                dataSource.setUsername(properties.getUsername());
                dataSource.setPassword(properties.getPassword());
                dataSource.setTimeBetweenEvictionRunsMillis(properties.getTimeBetweenEvictionRunsMillis());
                if (properties.getInitialSize() > 0) {
                    dataSource.setInitialSize(properties.getInitialSize());
                }
                if (properties.getMinIdle() > 0) {
                    dataSource.setMinIdle(properties.getMinIdle());
                }
                if (properties.getMaxActive() > 0) {
                    dataSource.setMaxActive(properties.getMaxActive());
                }
                dataSource.setTestOnBorrow(properties.isTestOnBorrow());
                try {
                    dataSource.init();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
                return dataSource;
            }
        
        
            @Bean(name = "otoSaaSSqlSessionFactory")
            public SqlSessionFactory testSqlSessionFactory(@Qualifier("otoSaaSDataSource") DataSource dataSource) throws Exception {
                SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
                bean.setDataSource(dataSource);
                bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/otosaas/*.xml"));
                return bean.getObject();
            }
        
            @Bean(name = "accountTransactionManager")
            public DataSourceTransactionManager testTransactionManager(@Qualifier("otoSaaSDataSource") DataSource dataSource) {
                return new DataSourceTransactionManager(dataSource);
            }
        
            @Bean(name = "otoSaaSSqlSessionTemplate")
            public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("otoSaaSSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
                return new SqlSessionTemplate(sqlSessionFactory);
            }
        }
        
    
    

    参考地址
    代码地址

    @ConditionalOnBean(仅仅在当前上下文中存在某个对象时,才会实例化一个Bean)
    @ConditionalOnClass(某个class位于类路径上,才会实例化一个Bean)
    @ConditionalOnExpression(当表达式为true的时候,才会实例化一个Bean)
    @ConditionalOnMissingBean(仅仅在当前上下文中不存在某个对象时,才会实例化一个Bean)
    @ConditionalOnMissingClass(某个class类路径上不存在的时候,才会实例化一个Bean)

    相关文章

      网友评论

        本文标题:SpringBoot整合多数据源xml方式

        本文链接:https://www.haomeiwen.com/subject/gdfszttx.html