261026SaaS多租户设计

675 字
3 分钟
261026SaaS多租户设计

三种隔离方案:

  1. 独立数据库
  2. 独立 Schema
  3. 共享库表 + 租户ID(普遍使用的)

独立数据库#

物理级隔离,一个租户一个数据库。

实现难点:如何根据租户tenantID进入不同数据库操作数据?

独立Schema#

逻辑级隔离,共享一个数据库实例,租户间表空间隔离。

特殊:MySQL

Schema几乎和Database等价,CREATE SCHEMA 就是 CREATE DATABASE,但在账号权限打通的前提下,依然可以共用同一个连接池。

实现方式:

连接级切换(JDBC Connection.setSchema() / search_path)🌟#

所有租户共用一个 Hikari 连接池。当 Spring / MyBatis 拿到数据库连接时,执行切换 Schema 命令,让该连接的后续所有 SQL 都自动在对应 Schema 下执行。

共享库表 + 租户ID#

通过tenantId字段控制。

过去往往还是通过AOP方式通过@TenantScope注入请求参数,然后到Mybatis SQL拼接,但似乎有更好的方案? 如何实现不用业务层手动拼 where tenant_id = ?

  1. 租户上下文
public class TenantContext {
private static final ThreadLocal<Long> CURRENT = new ThreadLocal<>();
public static void set(Long tenantId) { CURRENT.set(tenantId); }
public static Long get() { return CURRENT.get(); }
public static void clear() { CURRENT.remove(); }
}
  1. 注册拦截器
@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
TenantLineInnerInterceptor tenantInterceptor = new TenantLineInnerInterceptor();
// 配置租户处理器
tenantInterceptor.setTenantLineHandler(new TenantLineHandler() {
@Override
public Expression getTenantId() {
return new LongValue(TenantContext.get());
}
@Override
public boolean ignoreTable(String tableName) {
// 不需要隔离的表
return TenantIgnoreTables.isIgnore(tableName);
}
});
interceptor.addInnerInterceptor(tenantInterceptor);
return interceptor;
}
}
  1. 忽略表名单
public class TenantIgnoreTables {
private static final Set<String> IGNORE = Set.of(
"sys_tenant", // 租户表自身
"sys_dict", // 字典
"sys_config", // 全局配置
"area_code" // 行政区划
);
public static boolean isIgnore(String tableName) {
return IGNORE.contains(tableName.toLowerCase());
}
}
  1. 上游<解析租户塞上下文>

用 Filter 或拦截器,不要用你原来的 AOP 拼参数(AOP 留着做别的事):

@Component
public class TenantFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
try {
HttpServletRequest request = (HttpServletRequest) req;
String tid = request.getHeader("X-Tenant-Id");
if (StrUtil.isNotBlank(tid)) {
TenantContext.set(Long.parseLong(tid));
}
chain.doFilter(req, res);
} finally {
TenantContext.clear(); // 必须清理,线程复用会串租户
}
}
}

注意 finally 里的 clear()。Tomcat 线程是复用的,不清除就是下一个请求读到上一个租户的数据——这是这类方案最高频的事故来源。

  1. 单条方法级忽略(超管跨租户查询)
public @interface TenantIgnore {}
@Service
public class OpsOrderService {
@TenantIgnore // 自定义注解 + AOP:进方法前把上下文置空/打标记
public List<Order> statAllTenant() {
return orderMapper.selectList(null);
}
}
@Aspect
@Component
public class TenantIgnoreAspect {
@Around("@annotation(tenantIgnore)")
public Object around(ProceedingJoinPoint pjp, TenantIgnore tenantIgnore) throws Throwable {
Long backup = TenantContext.get();
TenantContext.remove(); // 置空 → 插件不追加条件
try {
return pjp.proceed();
} finally {
if (backup != null) TenantContext.set(backup);
}
}
}

别用「插件直接关掉」的方式,要用显式注解声明,让越权查询在代码里可审计、可 grep。

文章分享

如果这篇文章对你有帮助,欢迎分享给更多人!

261026SaaS多租户设计
https://shaio.top/posts/记录/261026saas多租户设计/
作者
沙海
发布于
2026-10-26
许可协议
CC BY-NC-SA 4.0

评论区

Profile Image of the Author
沙海
Hello, I'm Shai.
公告
欢迎来到我的博客!这是一则示例公告。
分类
标签
最新动态
站点统计
文章
109
分类
22
标签
87
总字数
145,450
运行时长
0 天
最后活动
0 天前
站点信息
构建平台
GitHub Actions
博客版本
Firefly v6.16.9
文章许可
CC BY-NC-SA 4.0
文章目录