Springboot多租户SaaS如何搭建

轻磊同学_3654

轻磊同学_3654

2023-05-12

1718人浏览

转载

技术框架

springboot版本为2.3.4.release

持久层采用JPA

租户Model设计

因为saas应用所有租户都使用同个服务和数据库,为隔离好租户数据,这里创建一个BaseSaasEntity

public abstract class BaseSaasEntity {
    @JsonIgnore
    @Column(nullable = false, updatable = false)
    protected Long tenantId;
    }

里面只有一个字段tenantId,对应的就是租户Id,所有租户业务entity都继承这个父类。最后通过tenantId来区分数据是哪个租户。

sql租户数据过滤

按往常,表建好就该接着对应的模块的CURD。但saas应用最基本的要求就是租户数据隔离,就是公司B的人不能看到公司A的数据,怎么过滤呢,这里上面我们建立的BaseSaasEntity就起作用了,通过区分当前请求是来自那个公司后,在所有tenant业务sql中加上where tenant=?就实现了租户数据过滤。

Hibernate filter

如果让我们在业务中都去加上租户sql过滤代码,那工作量不仅大,而且出错的概率也很大。理想是过滤sql拼接统一放在一起处理,在租户业务接口开启sql过滤。因为JPA是有hibernate实现的,这里我们可以利用hibernate的一些功能

@MappedSuperclass
@Data
@FilterDef(name = "tenantFilter", parameters = {@ParamDef(name = "tenantId", type = "long")})
@Filter(condition = "tenant_id=:tenantId", name = "tenantFilter")
public abstract class BaseSaasEntity {
    @JsonIgnore
    @Column(nullable = false, updatable = false)
    protected Long tenantId;


    @PrePersist
    public void onPrePersist() {
        if (getTenantId() != null) {
            return;
        }
        Long tenantId = TenantContext.getTenantId();
        Check.notNull(tenantId, "租户不存在");
        setTenantId(tenantId);
    }
}
Hibernate3 提供了一种创新的方式来处理具有“显性(visibility)”规则的数据,那就是使用Hibernate 过滤器。Hibernate 过滤器是全局有效的、具有名字、可以带参数的过滤器,对于某个特定的 Hibernate session 您可以选择是否启用(或禁用)某个过滤器。

这里我们通过@FilterDef和@Filter预先定义了一个sql过滤条件。然后通过一个@TenantFilter注解来标识接口需要进行数据过滤

springboot项目制作专家
springboot项目制作专家

通用的 Spring Boot 工程 skill,不绑定特定机器或项目,换台电脑直接用。 覆盖 Controller-Service-Repository 分层架构、JPA/MyBatis 双数据方案、RESTful API 规范、 Redis 缓存、AOP 日志、全局异常处理、定时任务、事务排查、性能调优。 含环境检测脚本和零硬编码路径设计。 触发关键词:Spring Boot、Java 后端、JPA、MyBatis、Spring Cloud、微服务、 Maven、@Transactional、@Res

下载
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Transactional
public @interface TenantFilter {

    boolean readOnly() default true;

}

可以看出这个接口是放在方法上,对应的就是Controller层。@Transactional增加事务注解的意义是因为激活hibernate filter必须要开启事务,这里默认是只读事务。 最后定义一个切面来激活filter

@Aspect
@Slf4j
@RequiredArgsConstructor
public class TenantSQLAspect {
    private static final String FILTER_NAME = "tenantFilter";
    private final EntityManager entityManager;
    @SneakyThrows
    @Around("@annotation(com.lvjusoft.njcommon.annotation.TenantFilter)")
    public Object aspect(ProceedingJoinPoint joinPoint) {
        Session session = entityManager.unwrap(Session.class);
        try {
            Long tenantId = TenantContext.getTenantId();
            Check.notNull(tenantId, "租户不存在");
            session.enableFilter(FILTER_NAME).setParameter("tenantId", tenantId);
            return joinPoint.proceed();
        } finally {
            session.disableFilter(FILTER_NAME);
        }
    }
}

这里切面的对象就是刚才自定义的@TenantFilter注解,在方法执行前拿到当前租户id,开启filter,这样租户数据隔离就大功告成了,只需要在租户业务接口上增加@TenantFilter注解即可, 开发只用关心业务代码。上图中的TenantContext是当前线程租户context,通过和前端约定好,接口请求头中增加租户id,服务端利用拦截器把获取到的租户id缓存在ThreadLocal中

public class IdentityInterceptor extends HandlerInterceptorAdapter {
    public IdentityInterceptor() {
        log.info("IdentityInterceptor init");
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader(AuthConstant.USER_TOKEN_HEADER_NAME);
        UserContext.setToken(token);
        String tenantId = request.getHeader(AuthConstant.TENANT_TOKEN_HEADER_NAME);
        TenantContext.setTenantUUId(tenantId);
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        UserContext.clear();
        TenantContext.clear();
    }
}

分库

随着租户数量的增加,mysql单库单表的数据肯定会达到瓶颈,这里只采用分库的手段。利用多数据源,将租户和数据源进行多对一的映射。

public class DynamicRoutingDataSource extends AbstractRoutingDataSource {
    private Map<object> targetDataSources;
    public DynamicRoutingDataSource() {
        targetDataSources =new HashMap();
        DruidDataSource druidDataSource1 = new DruidDataSource();
        druidDataSource1.setUsername("username");
        druidDataSource1.setPassword("password");
        druidDataSource1.setUrl("jdbc:mysql://localhost:3306/db?useSSL=false&useUnicode=true&characterEncoding=utf-8");
        targetDataSources.put("db1",druidDataSource1);
        
        DruidDataSource druidDataSource2 = new DruidDataSource();
        druidDataSource2.setUsername("username");
        druidDataSource2.setPassword("password");
        druidDataSource2.setUrl("jdbc:mysql://localhost:3306/db?useSSL=false&useUnicode=true&characterEncoding=utf-8");
        targetDataSources.put("db2",druidDataSource1);
        
        this.targetDataSources = targetDataSources;
        super.setTargetDataSources(targetDataSources);
        super.afterPropertiesSet();
    }
    public void addDataSource(String key, DataSource dataSource) {
        if (targetDataSources.containsKey(key)) {
            throw new IllegalArgumentException("dataSource key exist");
        }
        targetDataSources.put(key, dataSource);
        super.setTargetDataSources(targetDataSources);
        super.afterPropertiesSet();
    }
    @Override
    protected Object determineCurrentLookupKey() {
        return DataSourceContext.getSource();
    }
}</object>

通过实现AbstractRoutingDataSource来声明一个动态路由数据源,在框架使用datesource前,spring会调用determineCurrentLookupKey()方法来确定使用哪个数据源。这里的DataSourceContext和上面的TenantContext类似,在拦截器中获取到tenantInfo后,找到当前租户对应的数据源key并设置在ThreadLocal中。

相关文章

PHP速学视频免费教程(入门到精通)
PHP速学视频免费教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载

相关标签:

springboot

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

相关专题

更多
GoFrame框架Web开发与路由中间件
GoFrame框架Web开发与路由中间件

本专题聚焦GoFrame框架的Web开发,拆解路由注册与匹配规则、请求参数获取、参数校验与中间件执行顺序,说明统一响应、JWT鉴权、文件上传与接口文档生成的落地方式,并补充优雅重启与测试实践。

2026.11.17

20

15

GoFrame框架安装与gf命令行工具
GoFrame框架安装与gf命令行工具

本专题围绕GoFrame框架的安装与工具链配置展开,讲清Go版本要求、gf命令行的安装方式、代理镜像与依赖准备,说明项目初始化、热编译、交叉编译打包的做法,并整理安装阶段的常见报错与验证步骤。

2026.11.17

60

15

GoFrame框架零基础入门
GoFrame框架零基础入门

本专题整理GoFrame框架的入门知识,从模块化设计理念、环境准备到跑通第一个Web服务,讲清目录分层、配置加载、日志与中间件的用法,并对比Gin、Go-Zero的差异,帮助Go开发者建立整体认知。

2026.11.17

60

15

SQLAlchemy 一对多关系怎么建立
SQLAlchemy 一对多关系怎么建立

SQLAlchemy 一对多关系怎么建立?本专题整理父子表外键、relationship 双向映射、关联查询、级联删除和加载优化等相关文章,帮助你理解并实现常见的 ORM 关系建模。

2026.11.17

20

10

SQLAlchemy 如何增删改查
SQLAlchemy 如何增删改查

SQLAlchemy 如何增删改查?本专题整理 ORM 新增记录、条件查询、更新和删除、Session 事务提交与批量处理等实用文章,帮助你掌握 Python 数据库操作流程。

2026.11.17

60

11

SQLAlchemy ORM 模型怎么写
SQLAlchemy ORM 模型怎么写

SQLAlchemy ORM 模型怎么写?本专题整理模型类定义、Mapped 字段映射、主键与约束、表结构创建和常见报错的相关文章,帮助你从基础配置到实际建模逐步掌握 SQLAlchemy。

2026.11.17

40

16

Go-Zero API开发使用教程
Go-Zero API开发使用教程

本专题聚焦Go-Zero的API开发,拆解.api描述文件的语法结构、路由与分组定义、参数绑定与校验规则,说明统一响应体、JWT鉴权、跨域与接口文档生成的落地方式,并给出网关聚合与接口测试的实践建议。

2026.11.12

180

15

Go-Zero安装与goctl环境配置教程
Go-Zero安装与goctl环境配置教程

本专题围绕Go-Zero的安装与工具链配置展开,讲清Go版本要求、goctl安装方式、代理镜像、protoc依赖与环境变量设置,说明多版本共存、升级回退与CI流水线安装的做法,并整理安装阶段的常见报错与验证步骤。

2026.11.12

140

15

Go-Zero零基础入门教程
Go-Zero零基础入门教程

本专题整理Go-Zero的入门知识,从框架定位、环境准备到跑通第一个API服务,讲清目录分层、配置加载、日志与中间件的基本用法,并对比Gin、Kratos的差异,帮助Go开发者建立整体认知,判断它是否适合当前项目。

2026.11.12

160

15

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
LiblibAI API 开发手册
LiblibAI API 开发手册

共0课时 | 0人学习

Redis6入门到精通超详细教程
Redis6入门到精通超详细教程

共47课时 | 7.5万人学习