springboot多数据配置,实现读写分离

 

1、demo下载地址:

 链接:https://pan.baidu.com/s/1-F0v4b408nGTk1yU47CZtg 
提取码:2jyg 

2、关键代码说明

注:请下载整个demo后先自己研究一下,大概了解一下这个调用流程之后再看这个关键代码说明,可能会对您的理解有所帮助

 1)主从数据源配置类DataSourceConfiguration  

package com.yf.springboot.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 主从数据库配置类
 * @author [email protected]
 * @version V1.0.0
 * @title DataSourceConfiguration
 * @date 2019/4/9
 */
@Configuration
public class DataSourceConfiguration {
    private static Logger LOGGER = LoggerFactory.getLogger(DataSourceConfiguration.class);

    @Value("${spring.datasource.type}")
    private Class dataSourceType;

    @Bean(name="writeDataSource", destroyMethod = "close", initMethod="init")
    @Primary
    @ConfigurationProperties(prefix = "spring.master")
    public DataSource writeDataSource() {
        LOGGER.info("-------------------- writeDataSource init ---------------------");
        return DataSourceBuilder.create().type(dataSourceType).build();
    }
    /**
     * 有多少个从库就要配置多少个
     * @return
     */
    @Bean(name = "readDataSource", destroyMethod = "close", initMethod="init")
    @ConfigurationProperties(prefix = "spring.slave")
    public DataSource readDataSourceOne(){
        LOGGER.info("-------------------- readDataSourceOne init ---------------------");
        return DataSourceBuilder.create().type(dataSourceType).build();
    }
    /**
     * 这里的list是多个从库的情况下为了实现简单负载均衡
     * @return
     * @throws SQLException
     */
    @Bean("readDataSources")
    public List readDataSources() throws SQLException {
        List dataSources=new ArrayList<>();
        dataSources.add(readDataSourceOne());
        return dataSources;
    }
}

该配置类用于初始化读库和写库的Datasource对象bean,后面的MybatisConfiguration配置类中的roundRobinDataSouceProxy()方法将相应的DataSource的bean装载到不同的目标数据源中。

2)MybatisConfiguration类生成自定义的SqlSessionFactory

package com.yf.springboot.config;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@ConditionalOnClass({EnableTransactionManagement.class})
@Import({ DataSourceConfiguration.class})
@MapperScan(basePackages={"com.yf.springboot.dao"})
public class MybatisConfiguration {
    @Value("${spring.datasource.type}")
    private Class dataSourceType;
    @Value("${datasource.readSize}")
    private String dataSourceSize;

    @Bean
    @ConditionalOnMissingBean
    public SqlSessionFactory sqlSessionFactory(ApplicationContext ac) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        //装载Datasource
        sqlSessionFactoryBean.setDataSource(this.roundRobinDataSouceProxy(ac));
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
        sqlSessionFactoryBean.setTypeAliasesPackage("com.yf.springboot.model.dataobject");
        sqlSessionFactoryBean.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
        return sqlSessionFactoryBean.getObject();
    }
    /**
     * 有多少个数据源就要配置多少个bean
     * @return
     */
    @Bean
    public AbstractRoutingDataSource roundRobinDataSouceProxy(ApplicationContext ac) {
        int size = Integer.parseInt(dataSourceSize);
        System.out.println("size:" + size);
        //自定义的继承AbstractRoutingDataSource(数据源切换抽象类)的实现类
        MyAbstractRoutingDataSource proxy = new MyAbstractRoutingDataSource(size);
        Map targetDataSources = new HashMap();
        //多个读数据库时
        DataSource writeDataSource = (DataSource)ac.getBean("writeDataSource");
        List readDataSources = (List)ac.getBean("readDataSources");
        for (Integer i = 0; i < size; i++) {
            //设置数据源的key
            targetDataSources.put(DataSourceType.read.getType() + i.toString(), readDataSources.get(i));
        }
        //设置默认数据源
        proxy.setDefaultTargetDataSource(writeDataSource);
        //设置目标多数据源
        proxy.setTargetDataSources(targetDataSources);
        return proxy;
    }
}

rundRobinDataSouceProxy(ApplicationContext ac) 方法中的MyAbstractRoutingDataSource继承了AbstractRoutingDataSource抽象类,该抽象类会在调用mapper操作数据库数据之前会根据不同的key获取不同的dataource,以实现读写分离。下面我们来看看MyAbstractRoutingDataSource是怎么工作的:

3)MyAbstractRoutingDataSource类(继承AbstractRoutingDataSource)

package com.yf.springboot.config;

import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

public class MyAbstractRoutingDataSource extends AbstractRoutingDataSource{

    private final int dataSourceNumber;

    private AtomicInteger count = new AtomicInteger(0);

    public MyAbstractRoutingDataSource(int dataSourceNumber) {
        this.dataSourceNumber = dataSourceNumber;
    }
    //获取切换的数据源key
    @Override
    protected Object determineCurrentLookupKey() {
        //获取切换的值
        String typeKey = DataSourceContextHolder.getJdbcType();
        if (typeKey.equals(DataSourceType.write.getType())) {
            return DataSourceType.write.getType();
        }
        // 读简单负载均衡
        int number = count.getAndAdd(1);
        Integer targetNum = number % dataSourceNumber;
        String lookupKey = DataSourceType.read.getType() + targetNum.toString();
        return lookupKey;
    }
}
determineCurrentLookupKey()方法来自于AbstractRoutingDataSource抽象类,该方法用于获取不同的Datasource对应的key.下面我们来看这个方法在哪调用的:

springboot多数据配置,实现读写分离_第1张图片

     从上面可以看出这个determineCurrentLookupKey()的调用位置以及作用,而determineTargetDataSource()方法会在我们调用Mapper对象对数据库操作之前自动调用,以获取不同的Datasource,我们只需要重写determineCurrentLookupKey()方法获取不同的key,这样就实现了读写分离。下面我们再来看看这个resolvedDataSorces的Map对象和resolvedDefaultDataSource对象又是在哪加载的:

springboot多数据配置,实现读写分离_第2张图片

希望能对你的理解有所帮助

你可能感兴趣的:(springboot多数据配置,实现读写分离)