基于SpringBoot+Mybatis的SaaS平台搭建

SaaS平台是什么

        英语Software-as-a-Service ,就是提供软件服务的平台。基于JavaWeb的思想,可以在线上部署一套程序,根据权限将租户逻辑上分离,让每个租户具有独立的数据空间,当然也可以在数据库层面可以根据标识在同一个表中数据独立,也可以根据不同的租户设立不同的数据库进行数据独立。考虑到后续租户可能会大概率脱离SaaS平台私有搭建,所以本篇文章是以分库的方式实现SaaS平台。

MyBatis如何实现动态数据源

        话不多说,直接上代码

public class DynamicRoutingDataSource extends AbstractRoutingDataSource {

    private static Map<Object, Object> targetTargetDataSources = new ConcurrentHashMap<>();

    @Override
    protected Object determineCurrentLookupKey() {
        // 每次连接数据库,都会去设置数据源
        return DynamicDataSourceContextHolder.getDataSourceKey();
    }

    // 设置targetDataSources并记录数据源(这里可以记录每个数据源的最近使用时间,可以做删除不经常使用的数据源)
    @Override
    public void setTargetDataSources(Map<Object, Object> targetDataSources) {
        super.setTargetDataSources(targetDataSources);
        super.afterPropertiesSet();
        targetTargetDataSources = targetDataSources;
    }

    // 添加数据源
    public void addDataSource(String tenant, Map<String, Object> dataSourceProperties) {
        targetTargetDataSources.put(tenant, dataSource(dataSourceProperties));
        super.setTargetDataSources(targetTargetDataSources);
        afterPropertiesSet();
    }

    // 判断是否存在数据源,存在直接取
    public boolean existDataSource(String tenant) {
        return targetTargetDataSources.containsKey(tenant);
    }

    // 组装数据源
    public DataSource dataSource(Map<String, Object> dataSourceProperties) {
        DataSource dataSource;
        try {
            dataSource = DruidDataSourceFactory.createDataSource(dataSourceProperties);
        } catch (Exception e) {
            throw new RuntimeException();
        }
        return dataSource;
    }
}

核心代码就这些。SaaS平台分库的方式,其实根据不同的用户,使用不同的数据源。

猜你喜欢

转载自blog.csdn.net/zhong448676206/article/details/128418277