Spring boot 简单配置多数据源

欢迎访问github

首先在配置文件中配入各个数据源的地址和用户名密码

spring.datasource.common.url=jdbc:mysql://127.0.0.1:3306/training?useUnicode=true&characterEncoding=UTF-8&rewriteBatchedStatements=true&zeroDateTimeBehavior=convertToNull
spring.datasource.common.username=root
spring.datasource.common.password=123456

spring.datasource.common.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.common.initial-size=10
spring.datasource.common.max-active=20
spring.datasource.common.validation-query=SELECT 1;
spring.datasource.common.test-on-borrow=true
spring.datasource.common.test-while-idle=true

spring.datasource.learningmap.url=jdbc:mysql://127.0.0.1:3306/learning_map?useUnicode=true&characterEncoding=UTF-8&rewriteBatchedStatements=true&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&useAffectedRows=true
spring.datasource.learningmap.username=root
spring.datasource.learningmap.password=123456

spring.datasource.learningmap.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.learningmap.initial-size=10
spring.datasource.learningmap.max-active=20
spring.datasource.learningmap.validation-query=SELECT 1;
spring.datasource.learningmap.test-on-borrow=true
spring.datasource.learningmap.test-while-idle=true

 然后在Spring boot启动类的子级目录下新建配置文件DataSourceConfig,配置各个数据源的DataSource

@Configuration
public class DataSourceConfig {

    @Bean(name = "learningMapDatasourceProperties")
    @Qualifier("learningMapDatasourceProperties")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.learningmap")
    public DataSourceProperties learningMapDatasourceProperties() {
        return new DataSourceProperties();
    }

    @Bean(name = "learningMapDatasource")
    @Qualifier("learningMapDatasource")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.learningmap")
    public DataSource learningMapDatasource() {
        return learningMapDatasourceProperties().initializeDataSourceBuilder().build();
    }

    @Bean(name = "commonDatasourceProperties")
    @Qualifier("commonDatasourceProperties")
    @ConfigurationProperties(prefix = "spring.datasource.common")
    public DataSourceProperties commonDatasourceProperties() {
        return new DataSourceProperties();
    }

    @Bean(name = "commonDatasource")
    @Qualifier("commonDatasource")
    @ConfigurationProperties(prefix = "spring.datasource.common")
    public DataSource commonDatasource() {
        return commonDatasourceProperties().initializeDataSourceBuilder().build();
    }
}

 配置完了DataSource,就要配置各个数据源的Mybatis或者是JPA了

Mybatis配置文件:

@Configuration
@MapperScan(basePackages = "com.nagisazz.saas.learningmap.data.mapper", sqlSessionTemplateRef = "learningMapSqlSessionTemplate", sqlSessionFactoryRef = "learningMapSqlSessionFactory")
public class LearningMapDataSourceConfig {

    static final String MAPPER_LOCATION = "classpath:mapping/**/*Mapper.xml";

    @Autowired
    @Qualifier("learningMapDatasource")
    public DataSource learningMapDatasource;

    @Bean(name = "learningMapTransactionManager")
    @Primary
    public DataSourceTransactionManager learningMapTransactionManager() {
        return new DataSourceTransactionManager(learningMapDatasource);
    }

    @Bean(name = "learningMapSqlSessionFactory")
    @Primary
    public SqlSessionFactory learningMapSqlSessionFactory() {
        SqlSessionFactory sessionFactory = null;
        try {
            SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
            bean.setDataSource(learningMapDatasource);
            bean.setMapperLocations(new PathMatchingResourcePatternResolver()
                    .getResources(LearningMapDataSourceConfig.MAPPER_LOCATION));

            //添加PageHelper插件
            Properties properties = new Properties();
            Interceptor interceptor = new PageInterceptor();
            interceptor.setProperties(properties);
            bean.setPlugins(new Interceptor[]{interceptor});

            sessionFactory = bean.getObject();
        } catch (Exception e) {
        }
        return sessionFactory;
    }

    @Bean(name = "learningMapSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate learningMapSqlSessionTemplate() {
        return new SqlSessionTemplate(learningMapSqlSessionFactory());
    }
}

JPA配置文件:

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "commonJPAManagerFactory", transactionManagerRef = "commonJPATransactionManager", basePackages = {"com.nagisazz.common.data.mapper"})
public class CommonJPADataSourceConfig {

    @Autowired
    @Qualifier("commonDatasource")
    private DataSource commonDatasource;

    @Bean(name = "entityManager")
    public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
        return commonJPAManagerFactory(builder).getObject().createEntityManager();
    }

    @Bean(name = "commonJPAManagerFactory")
    public LocalContainerEntityManagerFactoryBean commonJPAManagerFactory(EntityManagerFactoryBuilder builder) {
        return builder.dataSource(commonDatasource).packages("com.nagisazz.common.data.mapper").persistenceUnit("commonPersistenceUnit").build();
    }

    @Bean(name = "commonJPATransactionManager")
    public PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(commonJPAManagerFactory(builder).getObject());
    }
}

最后,还有一个注意点,当只有单数据源的时候,是不需要配置这些的,因为Spring boot会自动配置,所以,在多数据源时,就要在Spring boot 的启动类上加上如下一句

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})

意思是不让Spring boot 自动配置数据源,我们自己来配


 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值