赞
踩
简单讲:在一台服务器上运行单个应用实例,它为多个租户(客户)提供服务。
从定义中我们可以理解:多租户是一种架构,目的是为了让多用户环境下使用同一套程序,且保证用户间数据隔离。
多租户的重点就是同一套程序下实现多用户数据的隔离。
独立数据库:简单来说就是一个租户使用一个数据库,这种数据隔离级别最高,安全性最好,但是提高成本。
共享数据库、隔离数据架构:多租户使用同一个数据库,但是每个租户对应一个Schema(数据库user)。
共享数据库、共享数据架构:使用同一个数据库,同一个Schema,但是在表中增加了租户ID
的字段,这种共享数据程度最高,隔离级别最低。
这里采用方案三,即共享数据库,共享数据架构,因为这种方案服务器成本最低,但是提高了开发成本。
为什么选择MyBatisPlus?
除了一些系统共用的表以外,其他租户相关的表,我们都需要在sql不厌其烦的加上AND t.tenant_id = ?
查询条件,稍不注意就会导致数据越界,数据安全问题让人担忧。好在有了MybatisPlus这个神器,可以极为方便的实现多租户SQL解析器
Mybatis-plus就提供了一种多租户的解决方案,实现方式是基于**分页插件(拦截器)**进行实现的。
在应用添加维护一张sys_tenant(租户管理表),在需要进行隔离的数据表上新增租户id;
创建表
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); } }
这里,jshERP中采用了Redis的实现方案
String token = request.getHeader("X-Access-Token");
Long tenantId = Tools.getTenantIdByToken(token);
什么是系统的上下文?
上下文(Context)可以理解为程序执行的背景环境,包含了在特定时刻程序所需的所有信息。这些信息可以包括变量的值、函数的调用情况、执行的位置等。就好像是在一场戏剧中,演员需要了解剧本、舞台布景和其他演员的动作一样,程序也需要上下文来理解自身在何处、在做什么。
核心类——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不需要加上租户ID的表示,需要过滤特定的sql,可以通过如下两种方式:
在配置分页插件中加上配置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;
}
});
通过租户注解的形式,目前只能作用于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(); }
测试
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。