多租戶的四種常用方案!
前言
某中型電商平臺的報表系統曾在深夜突然崩潰,起因竟是運營誤刪了共享表中的某租戶數據列。
運維團隊排查發現,因為缺乏有效租戶隔離,一條誤操作的ALTER TABLE語句導致全平臺數據混亂。
這讓我們警惕:選擇多租戶方案的每一步,都是安全與成本的權衡。
今天這篇文章就跟大家一起聊聊,多租戶的4種常用方案,希望對你會有所幫助。
一、字段隔離方案
低成本背后的高風險
字段隔離方案,是通過統一數據表+租戶ID過濾實現邏輯隔離。
如下圖所示:
圖片
初期開發成本極低,但將數據安全的壓力完全轉移到了代碼質量控制上。
致命缺陷檢查清單:
- 任意一次DAO層查詢漏加tenant_id條件 → 數據跨租戶泄露
- 索引必須將tenant_id作為最左前綴 → 性能瓶頸風險
- 全表掃描類查詢(如報表統計)無法避免跨租戶干擾
代碼防御示范
(1)MyBatis攔截器自動注入租戶ID
@Intercepts({@Signature(type = Executor.class, method = "update")})
public class TenantInterceptor implements Interceptor {
public Object intercept(Invocation iv) throws SQLException {
MappedStatement ms = (MappedStatement) iv.getArgs()[0];
Object param = iv.getArgs()[1];
// 實體類自動填充tenant_id
if (param instanceof BaseTenantEntity) {
Field tenantIdField = param.getClass().getDeclaredField("tenantId");
tenantIdField.setAccessible(true);
if (tenantIdField.get(param) == null) {
tenantIdField.set(param, TenantContext.get());
}
}
return iv.proceed();
}
}
(2)SQL防火墻:強制全表掃描必須聲明租戶范圍
/* 危險操作(可能掃全表) */
SELECT * FROM orders WHERE status = 'PAID';
/* 安全寫法(強制tenant_id過濾) */
SELECT * FROM orders
WHERE tenant_id = 'tenant_01'
AND status = 'PAID'
/* 必須添加LIMIT防止全量拉取 */
LIMIT 1000;
適用場景建議
- 初期快速驗證的MVP產品,用戶量比較少的業務系統。
- 對數據隔離要求較低的內部管理系統。
二、Schema隔離
數據庫層的單元房
在同一個數據庫實例中為每個租戶獨立Schema,實現庫級別隔離。
如下圖所示:
圖片
各租戶表結構相同但數據獨立,像小區里的不同住戶單元。
運維警告清單:
- 百級Schema數量級后,備份與遷移成本陡增
- 跨Schema關聯查詢必須引入中間聚合層
- 數據庫連接池需按最大租戶數配置 → 連接風暴風險
動態路由代碼實現
(1)Spring動態數據源配置
spring:
datasource:
dynamic:
primary: master
strict: true
datasource:
master:
url: jdbc:mysql://主庫地址
tenant_001:
url: jdbc:mysql://從庫地址?currentSchema=tenant_001
tenant_002:
url: jdbc:mysql://從庫地址?currentSchema=tenant_002
(2)AOP切面動態切換Schema
@Aspect
@Component
public class SchemaAspect {
@Before("@annotation(requireTenant)")
public void switchSchema(JoinPoint joinPoint) {
HttpServletRequest request = getCurrentRequest();
String tenantId = request.getHeader("X-Tenant-ID");
// 驗證租戶合法性
if (!tenantService.isValid(tenantId)) {
throw new IllegalTenantException("租戶身份異常!");
}
// 動態切換數據源
DynamicDataSourceContextHolder.push(tenantId);
}
@After("@annotation(requireTenant)")
public void clearSchema() {
DynamicDataSourceContextHolder.clear();
}
}
適用場景建議
- 需要中等安全級別的行業(教育、零售)。
- 租戶數<50且數據規模可控的系統。
三、獨立數據庫
數據隔離的終極形態
每個租戶享有獨立數據庫實例。
如下圖所示:
圖片
從存儲到底層連接完全隔離。
安全性最高但成本呈線性增長。
財務預警清單:
- 每個實例約增加¥3000/月(云RDS基礎配置)
- 跨租戶數據聚合需額外ETL系統支持
- DBA運維成本隨租戶數量直線上升
數據源動態路由核心代碼
(1)抽象路由控制器
public class TenantDataSourceRouter extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return TenantContextHolder.get();
}
@Override
protected DataSource determineTargetDataSource() {
String tenantId = (String) determineCurrentLookupKey();
DataSource ds = dataSourceMap.get(tenantId);
if (ds == null) {
ds = createNewDataSource(tenantId); // 動態創建新租戶數據源
dataSourceMap.put(tenantId, ds);
}
return ds;
}
}
(2)多租戶事務同步器(關鍵!)
@Bean
public PlatformTransactionManager transactionManager() {
return new DataSourceTransactionManager() {
@Override
protected void doBegin(Object transaction, TransactionDefinition definition) {
TenantDataSourceRouter router = (TenantDataSourceRouter) getDataSource();
router.initTenantDataSource(TenantContextHolder.get()); // 確保事務綁定正確數據源
super.doBegin(transaction, definition);
}
};
}
適用場景建議
- 金融、醫療等強合規行業
- 付費能力強且需要獨立資源池的KA客戶
四、混合架構
沒有銀彈的平衡術
核心原則:按租戶等級提供不同隔離方案
在系統中創建租戶時,根據租戶的實際情況,給它分配一個等級。
不同的等級,使用不同的隔離方案。
如下圖所示:
租戶等級 | 隔離方案 | 資源配置 |
S級 | 獨立數據庫 | 獨占RDS實例+只讀副本 |
A級 | Schema隔離 | 共享實例獨立Schema |
B級 | 字段過濾 | 共享表 |
動態策略選擇器
針對不同的租戶,我們可以使用策略模式,根據不同的等級,選擇不同的數據庫訪問方式。
代碼如下:
public class IsolationStrategyFactory {
public IsolationStrategy getStrategy(String tenantId) {
TenantConfig config = configService.getConfig(tenantId);
switch(config.getLevel()) {
case VIP:
return new IndependentDBStrategy();
case STANDARD:
return new SchemaStrategy();
case BASIC:
default:
return new SharedTableStrategy();
}
}
// 示例策略接口
public interface IsolationStrategy {
DataSource getDataSource();
void executeQuery(String sql);
}
}
運維避坑必讀
- 元數據管理:建立租戶-資源映射表,避免配置漂移
- 遷移工具鏈:開發自動化升降級工具(如VIP客戶從共享表遷移到獨立庫)
- 監控分層:不同方案的性能指標需獨立采集分析
總結
這篇文章列舉了多租戶的4種常用方案。
沒有最完美的,只有最合適的。
多租戶設計的本質是資源、安全、成本的黃金三角博弈。
與其追求理論完美,不如根據業務階段選擇最適方案。
畢竟能用可控成本解決問題的,才是真正的架構智慧。
如果看了文章有些收獲,記得給我點贊喔,謝謝你的支持和鼓勵。