Java, 原创,

Spring Boot 使用druid多数据源使用不同package下mapper调用不同的数据源

上次写过一个采用AOP 模式和注解方式在一个mapper中配置不同数据源的方式:Spring boot 使用druid 多数据源 读写分离配置与调用 注解方式

这是我们改用 不同mapper调用不同数据源的写法

目录结构如下:

config
	SlaveDataSourceConfig.java
	MasterDataSourceConfig.java
	
mapper
	master
		MasterCustomerMapper.java
	slave
		SlaveCustomerMapper.java

配置SlaveDataSourceConfig.java ,并已读为主,Bean添加 @Primary

package cn.test.fmrs.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
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.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
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 javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = {"cn.test.fmrs.infrastructure.mapper.slave"}, sqlSessionFactoryRef = "slaveFcsSqlSessionFactory")
public class SlaveDataSourceConfig {

    @Primary
    @Bean(name = "slaveFcsDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.druid.slave")
    public DataSource dataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    @Primary
    @Bean(name = "slaveFcsSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("slaveFcsDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);

        //如果使用了 mapper.xml的方式写sql则需要添加资源
        //PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new PathMatchingResourcePatternResolver();
        //sqlSessionFactoryBean.setMapperLocations(pathMatchingResourcePatternResolver.getResources("classpath*:/mybatis/*.xml"));
        return sqlSessionFactoryBean.getObject();
    }

    @Primary
    @Bean(name = "slaveFcsSqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("slaveFcsSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}

MasterDataSourceConfig类似, 去掉其中的 @Primary, 并替换其中slave为master

剩下的就只需要在对应的 package 下面创建mapper就可以了。

(89)

Related Post