SpringBoot+mybatis一寫多讀數(shù)據(jù)分離實(shí)現(xiàn)

項(xiàng)目源碼地址 https://github.com/HuangPugang/Java-lean

  • multidata 讀寫分離實(shí)現(xiàn)部分
  • multidata-test 測(cè)試項(xiàng)目

導(dǎo)讀

本文就springboot+mybatis實(shí)現(xiàn)數(shù)據(jù)庫一寫多讀方案的一些探討。實(shí)現(xiàn)數(shù)據(jù)庫的方案有很多,可以從代碼層實(shí)現(xiàn),也可以使用中間件進(jìn)行實(shí)現(xiàn)。
常見的中間件有Mycat、Atlas等,
而我們今天討論的是簡(jiǎn)易的代碼層通過多數(shù)據(jù)源實(shí)現(xiàn)。

思路

我們?cè)谑褂胹pringboot+mybatis的時(shí)候,會(huì)再application.yml中配置一個(gè)數(shù)據(jù)源,配置完之后我們就知道操作mapper的時(shí)候就會(huì)連接配置好的數(shù)據(jù)庫地址。
現(xiàn)在通過配置多個(gè)數(shù)據(jù)源+重寫AbstractRoutingDataSource數(shù)據(jù)源路由+注解 來實(shí)現(xiàn)一寫多讀的實(shí)現(xiàn)

代碼實(shí)現(xiàn)

DSProperties.java

配置文件,用于讀取配置文件的屬性

DSType.java

數(shù)據(jù)源類型,區(qū)分讀or寫

public enum DSType {
    read("read", "從庫"),
    write("write", "主庫");
}
DSTypeThreadLocal.java

數(shù)據(jù)源類型本地變量,使用ThreadLocal保存讀庫還是寫庫的類型,保證同一線程下訪問同一張表

public class DSTypeThreadLocal {

    private static Logger log = LoggerFactory.getLogger(DSTypeThreadLocal.class);

    //線程本地環(huán)境
    private static final ThreadLocal<String> dsType = new ThreadLocal<String>();

    public static ThreadLocal<String> getLocal() {
        return dsType;
    }
    
    public static void setRead() {
        dsType.set(DSType.read.getType());
    }

    public static void setWrite() {
        dsType.set(DSType.write.getType());
    }

    public static String getCurrentType() {
        if (StringUtils.isEmpty(dsType.get())) {
            return DSType.read.getType();
        }
        return dsType.get();
    }

    public static void clear() {
        dsType.remove();
    }
}

DBHelper.java

DB屬性封裝工具類

RoutingDS.java

數(shù)據(jù)源路由,在這個(gè)類中決定我們所要訪問的數(shù)據(jù)源

public class RoutingDS extends AbstractRoutingDataSource {
    AtomicInteger count = new AtomicInteger(0);

    private Integer readSize;

    public RoutingDS(Integer readSize) {
        this.readSize = readSize;
    }

    @Override
    protected Object determineCurrentLookupKey() {

        String typeKey = DSTypeThreadLocal.getCurrentType();

        if (typeKey == null) {
            return DSType.write.getType();
        }

        if (typeKey.equals(DSType.write.getType())) {
            return DSType.write.getType();
        }

        //讀庫, 簡(jiǎn)單負(fù)載均衡
        int number = count.getAndAdd(1);
        int lookupKey = number % readSize;

        return DSType.read.getType() + lookupKey;
    }
}
MybatisConfig.java

配置mybatis一些配置文件

@Configuration
@AutoConfigureAfter(DSProperties.class)
public class MybatisConfig {

    private static Logger log = LoggerFactory.getLogger(MybatisConfig.class);
    @Autowired
    DSProperties dp;

    private DataSource writeSource;

    private List<DataSource> readSourceList;


    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        try {
            SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
            sessionFactoryBean.setDataSource(roundRobinDataSourceProxy());

            //設(shè)置mapper.xml文件所在位置
            Resource[] resources = new PathMatchingResourcePatternResolver().getResources(dp.getMapperLocations());
            sessionFactoryBean.setMapperLocations(resources);
            return sessionFactoryBean.getObject();
        } catch (IOException e) {
            return null;
        } catch (Exception e) {
            return null;
        }
    }

    private void initWriteDataSource() {
        if (dp.getWrite() == null) {
            throw new RuntimeException("請(qǐng)先配置寫數(shù)據(jù)庫");
        }
        System.err.println("初始化寫數(shù)據(jù)源");
        PoolProperties p = DBHelper.buildPoolProperties(dp.getWrite());
        p.setLogAbandoned(true);
        p.setDefaultAutoCommit(true);
        writeSource = new org.apache.tomcat.jdbc.pool.DataSource(p) {
            @PreDestroy
            public void close() {
                super.close(true);
            }
        };
    }

    private void initReadDataSource() {
        readSourceList = new ArrayList<>();
        if (dp.getReads() == null || dp.getReads().size() == 0) {
            throw new RuntimeException("請(qǐng)先配置讀數(shù)據(jù)庫");
        }
        System.err.println("初始化讀數(shù)據(jù)源");
        for (int i = 0; i < dp.getReads().size(); i++) {
            PoolProperties p = DBHelper.buildPoolProperties(dp.getReads().get(i));
            p.setLogAbandoned(true);
            p.setDefaultAutoCommit(true);
            readSourceList.add(new org.apache.tomcat.jdbc.pool.DataSource(p) {
                @PreDestroy
                public void close() {
                    super.close(true);
                }
            });
        }
    }


    @Bean(name = "roundRobinDataSourceProxy")
    public AbstractRoutingDataSource roundRobinDataSourceProxy() {

        System.err.println("roundRobinDataSourceProxy");

        //初始化讀數(shù)據(jù)源
        initReadDataSource();

        //初始化寫數(shù)據(jù)源
        initWriteDataSource();

        Map<Object, Object> targetDataSources = new HashMap<Object, Object>();

        targetDataSources.put(DSType.write.getType(), writeSource);

        if (readSourceList == null && readSourceList.size() == 0) {
            throw new RuntimeException("請(qǐng)配置讀數(shù)據(jù)庫");
        }
        for (int i = 0; i < readSourceList.size(); i++) {
            System.err.println("targetDataSources=" + DSType.read.getType() + i);
            targetDataSources.put(DSType.read.getType() + i, readSourceList.get(i));
        }
        final int readSize = readSourceList.size();

        //路由類,尋找對(duì)應(yīng)的數(shù)據(jù)源
        AbstractRoutingDataSource proxy = new RoutingDS(readSize);

        proxy.setDefaultTargetDataSource(writeSource);//默認(rèn)庫
        proxy.setTargetDataSources(targetDataSources);
        return proxy;
    }


    @Bean
    @DependsOn("sqlSessionFactory")
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    //事務(wù)管理
    @Bean
    public PlatformTransactionManager annotationDriveTransactionManager() {
        System.out.println("事務(wù)管理");
        return new DataSourceTransactionManager((DataSource) SpringContext.getBean("roundRobinDataSourceProxy"));
    }

}

注解類
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface DSRead {

}
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface DSWrite {

}

切面實(shí)現(xiàn)

對(duì)于數(shù)據(jù)源選擇我們通過三種方式來決定讀還是寫

  • 攔截service方法
    攔截service方法只是簡(jiǎn)單通過方法名來確定是否是讀寫,通常讀數(shù)據(jù)庫為list select 開頭,而寫通常為add、insert、update、delete開頭,優(yōu)先級(jí)最低
  • 攔截自定義注解
    通過自定義注解來顯示指定讀庫還是寫庫
  • 攔截事務(wù)注解
    如果有有事務(wù),那必定是訪問寫庫,優(yōu)先級(jí)最高

具體代碼可參考項(xiàng)目源碼。通過寫此項(xiàng)目,可以加深對(duì)springboot、mybatis數(shù)據(jù)訪問的理解。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容