# 一、什么是多租戶
多租戶技術或稱多重租賃技術,簡稱多租戶。是一種軟件架構技術,是實現如何在多用戶環境下(此處的多用戶一般是面向企業用戶)共用相同的系統或程序組件,并且可確保各用戶間數據的隔離性。
簡單講:在一臺服務器上運行單個應用實例,它為多個租戶(客戶)提供服務。從定義中我們可以理解:多租戶是一種架構,目的是為了讓多用戶環境下使用同一套程序,且保證用戶間數據隔離。那么重點就很淺顯易懂了,多租戶的重點就是同一套程序下實現多用戶數據的隔離。
# 二、數據隔離有三種方案
1. 獨立數據庫:簡單來說就是一個租戶使用一個數據庫,這種數據隔離級別最高,安全性最好,但是提高成本。
2. 共享數據庫、隔離數據架構:多租戶使用同一個數據庫,但是每個租戶對應一個Schema(數據庫user)。
3. 共享數據庫、共享數據架構:使用同一個數據庫,同一個Schema,但是在表中增加了`租戶ID`的字段,這種共享數據程度最高,隔離級別最低。
這里采用方案三,即共享數據庫,共享數據架構,因為這種方案服務器成本最低,但是提高了開發成本。
# 三、Mybatis-plus實現多租戶方案
> 為什么選擇MyBatisPlus?
> 除了一些系統共用的表以外,其他租戶相關的表,我們都需要在sql不厭其煩的加上`AND t.tenant_id = ?`查詢條件,稍不注意就會導致數據越界,數據安全問題讓人擔憂。好在有了MybatisPlus這個神器,可以極為方便的實現多租戶SQL解析器。
Mybatis-plus就提供了一種多租戶的解決方案,實現方式是基于分頁插件(攔截器)進行實現的。
## 3.1 第一步:
* 在數據庫中添加維護一張sys\_tenant(租戶管理表),
* 在需要進行租戶數據隔離的數據表上新增租戶id;
## 3.2 第二步:
創建表:
~~~
CREATE TABLE `orders_1`.`tenant` (
`id` int(0) NOT NULL AUTO_INCREMENT COMMENT '自增主鍵',
`expire_date` datetime(0) COMMENT '協議到期時間',
`amount` decimal(8, 2) COMMENT '金額',
`tenant_id` int(0) COMMENT '租戶ID',
PRIMARY KEY (`id`)
);
~~~
自定義系統的上下文,存儲從cookie等方式獲取的租戶ID,在后續的getTenantId()使用。
~~~
package com.erbadagang.mybatis.plus.tenant.config;
import org.springframework.stereotype.Component;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* @description 系統的上下文幫助類。ConcurrentHashMap設置租戶ID,供后續的MP的getTenantId()取出
* @ClassName: ApiContext
* @author: 郭秀志 jbcode@126.com
* @date: 2020/7/12 21:50
* @Copyright:
*/
@Component
public class ApiContext {
private static final String KEY_CURRENT_TENANT_ID = "KEY_CURRENT_TENANT_ID";
private static final Map<String, Object> mContext = new ConcurrentHashMap<>();
public void setCurrentTenantId(Long providerId) {
mContext.put(KEY_CURRENT_TENANT_ID, providerId);
}
public Long getCurrentTenantId() {
return (Long) mContext.get(KEY_CURRENT_TENANT_ID);
}
}
~~~
核心類——`MyBatisPlusConfig`通過分頁插件配置MP多租戶。
~~~
package com.erbadagang.mybatis.plus.tenant.config;
import com.baomidou.mybatisplus.core.parser.ISqlParser;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.tenant.TenantHandler;
import com.baomidou.mybatisplus.extension.plugins.tenant.TenantSqlParser;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.ArrayList;
import java.util.List;
/**
* @description MyBatisPlus配置類,分頁插件,多租戶也是使用的分頁插件進行的配置。
* @ClassName: MyBatisPlusConfig
* @author: 郭秀志 jbcode@126.com
* @date: 2020/7/12 21:34
* @Copyright:
*/
@Configuration
@MapperScan("com.erbadagang.mybatis.plus.tenant.mapper")//配置掃描的mapper包
public class MyBatisPlusConfig {
@Autowired
private ApiContext apiContext;
/**
* 分頁插件
*
* @return
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
// 創建SQL解析器集合
List<ISqlParser> sqlParserList = new ArrayList<>();
// 創建租戶SQL解析器
TenantSqlParser tenantSqlParser = new TenantSqlParser();
// 設置租戶處理器
tenantSqlParser.setTenantHandler(new TenantHandler() {
// 設置當前租戶ID,實際情況你可以從cookie、或者緩存中拿都行
@Override
public Expression getTenantId(boolean select) {
// 從當前系統上下文中取出當前請求的服務商ID,通過解析器注入到SQL中。
Long currentProviderId = apiContext.getCurrentTenantId();
if (null == currentProviderId) {
throw new RuntimeException("Get CurrentProviderId error.");
}
return new LongValue(currentProviderId);
}
@Override
public String getTenantIdColumn() {
// 對應數據庫中租戶ID的列名
return "tenant_id";
}
@Override
public boolean doTableFilter(String tableName) {
// 是否需要需要過濾某一張表
/* List<String> tableNameList = Arrays.asList("sys_user");
if (tableNameList.contains(tableName)){
return true;
}*/
return false;
}
});
sqlParserList.add(tenantSqlParser);
paginationInterceptor.setSqlParserList(sqlParserList);
return paginationInterceptor;
}
}
~~~
# 四、測試
配置好之后,不管是查詢、新增、修改刪除方法,MP都會自動加上租戶ID的標識,測試如下:
~~~
package com.erbadagang.mybatis.plus.tenant;
import com.erbadagang.mybatis.plus.tenant.config.ApiContext;
import com.erbadagang.mybatis.plus.tenant.entity.Tenant;
import com.erbadagang.mybatis.plus.tenant.mapper.TenantMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
/**
* @description 多租戶測試用例
* @ClassName: MultiTanentApplicationTests
* @author: 郭秀志 jbcode@126.com
* @date: 2020/7/12 22:06
* @Copyright:
*/
@SpringBootTest
class MultiTanentApplicationTests {
@Autowired
private ApiContext apiContext;
@Autowired
private TenantMapper tenantMapper;
@Test
public void before() {
// 在上下文中設置當前服務商的ID
apiContext.setCurrentTenantId(1L);
}
@Test
public void select() {
List<Tenant> tenants = tenantMapper.selectList(null);
tenants.forEach(System.out::println);
}
}
~~~
輸出的SQL自動包括`WHERE tenant_id = 1`:
~~~
==> Preparing: SELECT id, expire_date, amount, tenant_id FROM t_tenant WHERE tenant_id = 1
==> Parameters:
<== Total: 0
~~~
# 五、特定SQL過濾
如果在程序中,有部分SQL不需要加上租戶ID的表示,需要過濾特定的sql,可以通過如下兩種方式:
## 5.1 方式一:
在配置分頁插件中加上配置ISqlParserFilter解析器,如果配置SQL很多,比較麻煩,不建議。
~~~
//有部分SQL不需要加上租戶ID的表示,需要過濾特定的sql。如果比較多不建議這里配置。
/*paginationInterceptor.setSqlParserFilter(new ISqlParserFilter() {
@Override
public boolean doFilter(MetaObject metaObject) {
MappedStatement ms = SqlParserHelper.getMappedStatement(metaObject);
// 對應Mapper或者dao中的方法
if("com.erbadagang.mybatis.plus.tenant.mapper.UserMapper.selectList".equals(ms.getId())){
return true;
}
return false;
}
});*/
~~~
## 5.2 方式二:
通過租戶注解的形式,目前只能作用于Mapper的方法上。特定sql過濾 過濾特定的方法 也可以在userMapper需要排除的方法上加入注解SqlParser(filter=true) 排除 SQL 解析。
~~~
package com.erbadagang.mybatis.plus.tenant.mapper;
import com.baomidou.mybatisplus.annotation.SqlParser;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.erbadagang.mybatis.plus.tenant.entity.Tenant;
import org.apache.ibatis.annotations.Select;
/**
* <p>
* Mapper 接口
* </p>
*
* @author 郭秀志 jbcode@126.com
* @since 2020-07-12
*/
public interface TenantMapper extends BaseMapper<Tenant> {
/**
* 自定Wrapper, @SqlParser(filter = true)注解代表不進行SQL解析也就沒有租戶的附加條件。
*
* @return
*/
@SqlParser(filter = true)
@Select("SELECT count(5) FROM t_tenant ")
public Integer myCount();
}
~~~
測試
~~~
@Test
public void myCount() {
Integer count = tenantMapper.myCount();
System.out.println(count);
}
~~~
SQL輸出
~~~
==> Preparing: SELECT count(5) FROM t_tenant
==> Parameters:
<== Columns: count(5)
<== Row: 0
<== Total: 1
~~~
開啟 SQL 解析緩存注解生效,如果你的MP版本在3.1.1及以上則不需要配置
~~~
# 開啟 SQL 解析緩存注解生效,如果你的MP版本在3.1.1及以上則不需要配置
mybatis-plus:
global-config:
sql-parser-cache: true
~~~
- 內容簡介
- 第一章 Spring boot 簡介
- 1.1 helloworld
- 1.2 提高開發效率工具lombok
- 1.3 IDEA熱部署
- 1.4 IDEA常用插件
- 1.5 常用注解
- 第二章 RESTful接口
- 2.1 RESTful風格API
- 2.1.1 spring常用注解開發RESTful接口
- 2.1.2 HTTP協議與Spring參數接收注解
- 2.1.3 Spring請求處理流程注解
- 2.2 JSON數據格式處理
- 2.2.1 Jackson的轉換示例代碼
- 2.3 針對接口編寫測試代碼
- 2.3.1 編碼接口測試示例代碼
- 2.3.2 帶severlet容器的接口測試示例代碼
- 2.3.3 Mockito測試示例代碼
- 2.3.4 Mockito輕量測試
- 2.4 使用swagger2構建API文檔
- 2.4.1 swagger2示例代碼
- 2.4.2 pom.xml
- 2.5 使用swagger2導出各種格式的接口文檔
- 第三章 sping boot配置管理
- 3.1 YAML語法
- 3.2 YAML綁定配置變量的方式
- 3.3 YAML配置屬性值校驗
- 3.4 YAML加載外部配置文件
- 3.5 SpEL表達式綁定配置項
- 3.6 不同環境下的多配置
- 3.7 配置文件的優先級
- 3.8 配置文件敏感字段加密
- 第四章 連接數據庫使用到的框架
- 4.1 spring JDBC
- 4.2 mybatis配置mybatisgenerator自動生成代碼
- 4.3 mybatis操作數據庫+dozer整合Bean自動加載
- 4.4 spring boot mybatis 規范
- 4.5 spirng 事務與分布式事務
- 4.6 spring mybaits 多數據源(未在git版本中實現)
- 4.7 mybatis+atomikos實現分布式事務(未在git版本中實現)
- 4.8 mybatis踩坑之逆向工程導致的服務無法啟動
- 4.9 Mybatis Plus
- 4.9.1.CURD快速入門
- 4.9.2.條件構造器使用與總結
- 4.9.3.自定義SQL
- 4.9.4.表格分頁與下拉分頁查詢
- 4.9.5.ActiveRecord模式
- 4.9.6.主鍵生成策略
- 4.9.7.MybatisPlus代碼生成器
- 4.9.8.邏輯刪除
- 4.9.9.字段自動填充
- 4.9.10.多租戶解決方案
- 4.9.11.雪花算法與精度丟失
- 第五章 頁面展現整合
- 5.1 webjars與靜態資源
- 5.2 模板引擎與未來趨勢
- 5.3 整合JSP
- 5.4 整合Freemarker
- 5.5 整合Thymeleaf
- 5.6 Thymeleaf基礎語法
- 5.7 Thymeleaf內置對象與工具類
- 5.8 Thymeleaf公共片段(標簽)和內聯JS
- 第六章 生命周期內的攔截、監聽
- 6.1 servlet與filter與listener的實現
- 6.1.1 FilterRegistration
- 6.1.2 CustomFilter
- 6.1.3 Customlister
- 6.1.4 FirstServlet
- 6.2 spring攔截器及請求鏈路說明
- 6.2.1 MyWebMvcConfigurer
- 6.2.2 CustomHandlerInterceptor
- 6.3 自定義事件的發布與監聽
- 6.4 應用啟動的監聽
- 第七章 嵌入式容器的配置與應用
- 7.1 嵌入式的容器配置與調整
- 7.2 切換到jetty&undertow容器
- 7.3 打war包部署到外置tomcat容器
- 第八章 統一全局異常處理
- 8.1 設計一個優秀的異常處理機制
- 8.2 自定義異常和相關數據結構
- 8.3 全局異常處理ExceptionHandler
- 8.3.1 HelloController
- 8.4 服務端數據校驗與全局異常處理
- 8.5 AOP實現完美異常處理方案
- 第九章 日志框架與全局日志管理
- 9.1 日志框架的簡介與選型
- 9.2 logback日志框架整合使用
- 9.3 log4j2日志框架整合與使用
- 9.4 攔截器實現用戶統一訪問日志
- 第十章 異步任務與定時任務
- 10.1 實現Async異步任務
- 10.2 為異步任務規劃線程池
- 10.3 通過@Scheduled實現定時任務
- 10.4 quartz簡單定時任務(內存持久化)
- 10.5 quartz動態定時任務(數據庫持久化)
- 番外章節
- 1.windows下安裝git
- 1 git的使用
- 2 idea通過git上傳代碼到github
- 2.maven配置
- 3.idea幾個輔助插件
- 4.idea配置數據庫
- 5.搭建外網穿透實現外網訪問內網項目
- 6.idea設置修改頁面自動刷新
- 7.本地tomcat啟動亂碼
- 8.win10桌面整理,得到一個整潔的桌面
- 9.//TODO的用法
- 10.navicat for mysql 工具激活
- 11.安裝redis
- 12.idea修改內存
- 13.IDEA svn配置
- 14.IntelliJ IDEA像Eclipse一樣打開多個項目