ruoyi-nbcio-plus基于vue3的多租户机制

devtools/2024/9/22 17:20:24/

更多ruoyi-nbcio功能请看演示系统

gitee源代码地址

前后端代码: https://gitee.com/nbacheng/ruoyi-nbcio

演示地址:RuoYi-Nbcio后台管理系统 http://122.227.135.243:9666/

更多nbcio-boot功能请看演示系统 

gitee源代码地址

后端代码: https://gitee.com/nbacheng/nbcio-boot

前端代码:https://gitee.com/nbacheng/nbcio-vue.git

在线演示(包括H5) : http://122.227.135.243:9888

       因为基于ruoyi-vue-plus的框架,所以多租户总体基于使用了 MyBatis-Plus (简称 MP)的多租户插件功能

      可以参考

  • MP官方文档 - 多租户插件
  • MP官方 Demo

    实现主要有以下步骤:

    在相关表添加多租户字段
    在多租户配置TenantConfig 里中添加多租户插件拦截器 TenantLineInnerInterceptor
根据业务对多租户插件拦截器 TenantLineInnerInterceptor 进行配置(多租户字段、需要进行过滤的表等)
    在数据库相关表中加入租户id字段 tenant_id(别忘了相关实体类也要加上)

具体代码如下:

java">@EnableConfigurationProperties(TenantProperties.class)
@AutoConfiguration(after = {RedisConfig.class, MybatisPlusConfig.class})
@ConditionalOnProperty(value = "tenant.enable", havingValue = "true")
public class TenantConfig {/*** 初始化租户配置*/@Beanpublic boolean tenantInit(MybatisPlusInterceptor mybatisPlusInterceptor,TenantProperties tenantProperties) {List<InnerInterceptor> interceptors = new ArrayList<>();// 多租户插件 必须放到第一位interceptors.add(tenantLineInnerInterceptor(tenantProperties));interceptors.addAll(mybatisPlusInterceptor.getInterceptors());mybatisPlusInterceptor.setInterceptors(interceptors);return true;}/*** 多租户插件*/public TenantLineInnerInterceptor tenantLineInnerInterceptor(TenantProperties tenantProperties) {return new TenantLineInnerInterceptor(new PlusTenantLineHandler(tenantProperties));}@Beanpublic RedissonAutoConfigurationCustomizer tenantRedissonCustomizer(RedissonProperties redissonProperties) {return config -> {TenantKeyPrefixHandler nameMapper = new TenantKeyPrefixHandler(redissonProperties.getKeyPrefix());SingleServerConfig singleServerConfig = ReflectUtils.invokeGetter(config, "singleServerConfig");if (ObjectUtil.isNotNull(singleServerConfig)) {// 使用单机模式// 设置多租户 redis key前缀singleServerConfig.setNameMapper(nameMapper);ReflectUtils.invokeSetter(config, "singleServerConfig", singleServerConfig);}ClusterServersConfig clusterServersConfig = ReflectUtils.invokeGetter(config, "clusterServersConfig");// 集群配置方式 参考下方注释if (ObjectUtil.isNotNull(clusterServersConfig)) {// 设置多租户 redis key前缀clusterServersConfig.setNameMapper(nameMapper);ReflectUtils.invokeSetter(config, "clusterServersConfig", clusterServersConfig);}};}/*** 多租户缓存管理器*/@Primary@Beanpublic CacheManager tenantCacheManager() {return new TenantSpringCacheManager();}/*** 多租户鉴权dao实现*/@Primary@Beanpublic SaTokenDao tenantSaTokenDao() {return new TenantSaTokenDao();}}

其中 自定义租户处理器代码如下:

java">/*** 自定义租户处理器** @author nbacheng*/
@Slf4j
@AllArgsConstructor
public class PlusTenantLineHandler implements TenantLineHandler {private final TenantProperties tenantProperties;@Overridepublic Expression getTenantId() {String tenantId = TenantHelper.getTenantId();if (StringUtils.isBlank(tenantId)) {log.error("无法获取有效的租户id -> Null");return new NullValue();}String dynamicTenantId = TenantHelper.getDynamic();if (StringUtils.isNotBlank(dynamicTenantId)) {// 返回动态租户return new StringValue(dynamicTenantId);}// 返回固定租户return new StringValue(tenantId);}@Overridepublic boolean ignoreTable(String tableName) {String tenantId = TenantHelper.getTenantId();// 判断是否有租户if (StringUtils.isNotBlank(tenantId)) {// 不需要过滤租户的表List<String> excludes = tenantProperties.getExcludes();// 非业务表List<String> tables = ListUtil.toList("gen_table","gen_table_column");tables.addAll(excludes);return tables.contains(tableName);}return true;}}

上面就是重载了mybasisplus的TenantLineHandler 

java">/*** 租户处理器( TenantId 行级 )** @author hubin* @since 3.4.0*/
public interface TenantLineHandler {/*** 获取租户 ID 值表达式,只支持单个 ID 值* <p>** @return 租户 ID 值表达式*/Expression getTenantId();/*** 获取租户字段名* <p>* 默认字段名叫: tenant_id** @return 租户字段名*/default String getTenantIdColumn() {return "tenant_id";}/*** 根据表名判断是否忽略拼接多租户条件* <p>* 默认都要进行解析并拼接多租户条件** @param tableName 表名* @return 是否忽略, true:表示忽略,false:需要解析并拼接多租户条件*/default boolean ignoreTable(String tableName) {return false;}/*** 忽略插入租户字段逻辑** @param columns        插入字段* @param tenantIdColumn 租户 ID 字段* @return*/default boolean ignoreInsert(List<Column> columns, String tenantIdColumn) {return columns.stream().map(Column::getColumnName).anyMatch(i -> i.equalsIgnoreCase(tenantIdColumn));}
}

多租户插件的调用流程如下图:

上面主要是用到了mybatisPlusInterceptor,

java">public class MybatisPlusInterceptor implements Interceptor {@Setterprivate List<InnerInterceptor> interceptors = new ArrayList<>();@Overridepublic Object intercept(Invocation invocation) throws Throwable {Object target = invocation.getTarget();Object[] args = invocation.getArgs();if (target instanceof Executor) {final Executor executor = (Executor) target;Object parameter = args[1];boolean isUpdate = args.length == 2;MappedStatement ms = (MappedStatement) args[0];if (!isUpdate && ms.getSqlCommandType() == SqlCommandType.SELECT) {RowBounds rowBounds = (RowBounds) args[2];ResultHandler resultHandler = (ResultHandler) args[3];BoundSql boundSql;if (args.length == 4) {boundSql = ms.getBoundSql(parameter);} else {// 几乎不可能走进这里面,除非使用Executor的代理对象调用query[args[6]]boundSql = (BoundSql) args[5];}for (InnerInterceptor query : interceptors) {if (!query.willDoQuery(executor, ms, parameter, rowBounds, resultHandler, boundSql)) {return Collections.emptyList();}query.beforeQuery(executor, ms, parameter, rowBounds, resultHandler, boundSql);}CacheKey cacheKey = executor.createCacheKey(ms, parameter, rowBounds, boundSql);return executor.query(ms, parameter, rowBounds, resultHandler, cacheKey, boundSql);} else if (isUpdate) {

上面进入beforeQuery

java">public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {if (InterceptorIgnoreHelper.willIgnoreTenantLine(ms.getId())) {return;}PluginUtils.MPBoundSql mpBs = PluginUtils.mpBoundSql(boundSql);mpBs.sql(parserSingle(mpBs.sql(), null));}

通过parserSingle的processParser

java">public String parserSingle(String sql, Object obj) {if (logger.isDebugEnabled()) {logger.debug("original SQL: " + sql);}try {Statement statement = JsqlParserGlobal.parse(sql);return processParser(statement, 0, sql, obj);} catch (JSQLParserException e) {throw ExceptionUtils.mpe("Failed to process, Error SQL: %s", e.getCause(), sql);}}
java">protected String processParser(Statement statement, int index, String sql, Object obj) {if (logger.isDebugEnabled()) {logger.debug("SQL to parse, SQL: " + sql);}if (statement instanceof Insert) {this.processInsert((Insert) statement, index, sql, obj);} else if (statement instanceof Select) {this.processSelect((Select) statement, index, sql, obj);} else if (statement instanceof Update) {this.processUpdate((Update) statement, index, sql, obj);} else if (statement instanceof Delete) {this.processDelete((Delete) statement, index, sql, obj);}sql = statement.toString();if (logger.isDebugEnabled()) {logger.debug("parse the finished SQL: " + sql);}return sql;}

通过这个processSelect的进入select


java">@Overrideprotected void processSelect(Select select, int index, String sql, Object obj) {final String whereSegment = (String) obj;processSelectBody(select.getSelectBody(), whereSegment);List<WithItem> withItemsList = select.getWithItemsList();if (!CollectionUtils.isEmpty(withItemsList)) {withItemsList.forEach(withItem -> processSelectBody(withItem, whereSegment));}}

其中进入processSelectBody处理

java">protected void processSelectBody(SelectBody selectBody, final String whereSegment) {if (selectBody == null) {return;}if (selectBody instanceof PlainSelect) {processPlainSelect((PlainSelect) selectBody, whereSegment);} else if (selectBody instanceof WithItem) {WithItem withItem = (WithItem) selectBody;processSelectBody(withItem.getSubSelect().getSelectBody(), whereSegment);} else {SetOperationList operationList = (SetOperationList) selectBody;List<SelectBody> selectBodyList = operationList.getSelects();if (CollectionUtils.isNotEmpty(selectBodyList)) {selectBodyList.forEach(body -> processSelectBody(body, whereSegment));}}}

之后进入processPlainSelect

java">protected void processPlainSelect(final PlainSelect plainSelect, final String whereSegment) {//#3087 githubList<SelectItem> selectItems = plainSelect.getSelectItems();if (CollectionUtils.isNotEmpty(selectItems)) {selectItems.forEach(selectItem -> processSelectItem(selectItem, whereSegment));}// 处理 where 中的子查询Expression where = plainSelect.getWhere();processWhereSubSelect(where, whereSegment);// 处理 fromItemFromItem fromItem = plainSelect.getFromItem();List<Table> list = processFromItem(fromItem, whereSegment);List<Table> mainTables = new ArrayList<>(list);// 处理 joinList<Join> joins = plainSelect.getJoins();if (CollectionUtils.isNotEmpty(joins)) {mainTables = processJoins(mainTables, joins, whereSegment);}// 当有 mainTable 时,进行 where 条件追加if (CollectionUtils.isNotEmpty(mainTables)) {plainSelect.setWhere(builderExpression(where, mainTables, whereSegment));}}

上面进入builderExpression 构造表达式

java">protected Expression builderExpression(Expression currentExpression, List<Table> tables, final String whereSegment) {// 没有表需要处理直接返回if (CollectionUtils.isEmpty(tables)) {return currentExpression;}// 构造每张表的条件List<Expression> expressions = tables.stream().map(item -> buildTableExpression(item, currentExpression, whereSegment)).filter(Objects::nonNull).collect(Collectors.toList());// 没有表需要处理直接返回if (CollectionUtils.isEmpty(expressions)) {return currentExpression;}// 注入的表达式Expression injectExpression = expressions.get(0);// 如果有多表,则用 and 连接if (expressions.size() > 1) {for (int i = 1; i < expressions.size(); i++) {injectExpression = new AndExpression(injectExpression, expressions.get(i));}}

上面的buildTableExpression加入了租户的条件

java">public Expression buildTableExpression(final Table table, final Expression where, final String whereSegment) {if (tenantLineHandler.ignoreTable(table.getName())) {return null;}return new EqualsTo(getAliasColumn(table), tenantLineHandler.getTenantId());}

最终通过前面的processParser获取select的sql表达式,加入了多租户条件。


http://www.ppmy.cn/devtools/8325.html

相关文章

Docker容器的使用与操作

1、什么是容器 镜像和容器的关系&#xff0c;就像是面向对象程序设计中的类和实例一样&#xff0c;镜像是静态的定义&#xff0c;容器是镜像运行时的实体&#xff0c;基于同一镜像可以创建若干个不同的容器。 每个容器都有一个软件镜像。可以将容器看作一个将应用程序及其依赖环…

Day 27 39. 组合总和 40.组合总和II 131.分割回文串

组合总和 给定一个无重复元素的数组 candidates 和一个目标数 target &#xff0c;找出 candidates 中所有可以使数字和为 target 的组合。 candidates 中的数字可以无限制重复被选取。 说明&#xff1a; 所有数字&#xff08;包括 target&#xff09;都是正整数。解集不能…

从事数据分析相关工作技术总结

在数据分析领域&#xff0c;掌握一系列技术和工具是非常重要的。以下是一些关键技术和技能&#xff0c;它们对于成为一名成功的数据分析师至关重要&#xff1a; 统计学和概率论 理基本的统计概念&#xff0c;如均值、中位数、方差、标准差、概率分布等。掌握假设检验、回归分析…

深度学习基础——循环神经网络的结构及参数更新方式

深度学习基础——循环神经网络的结构及参数更新方式 深度学习领域的一大重要分支是循环神经网络&#xff08;Recurrent Neural Networks&#xff0c;简称RNN&#xff09;&#xff0c;它是一种用于处理序列数据的神经网络结构。与传统的前馈神经网络不同&#xff0c;循环神经网…

Git 远程仓库多人协作

文章目录 前言一、操作远程仓库1、克隆远程仓库2、向远程仓库推送3、拉取远程仓库4、删除远程库 二、多人协作 前言 Git是分布式版本控制系统&#xff0c;同一个Git仓库&#xff0c;可以分布到不同的机器上。那么该怎么分布呢&#xff1f;首先肯定得有一台机器充当“原始库”&…

Stable Diffusion UI 从安装到实现文字图片融合(光影字,错觉图)图片制作详细教程

前言 最近在实践大模型本地部署&#xff0c;前几天在本地部署了一个ChatGLM大模型&#xff0c;刚好环境搭好了&#xff0c;也支持跑Stable Diffusion&#xff0c;所以就安装了再尝试一下。 原因是之前在B站上有大佬做了一个Windows电脑能一键运行的Stable Diffusion的安装包&…

LeetCode第797题: 所有可能的路径

目录 1.问题描述 2.问题分析 1.问题描述 给你一个有 n 个节点的有向无环图&#xff08;DAG&#xff09;&#xff0c;请你找出所有从节点 0 到节点 n-1 的路径并输出&#xff08;不要求按特定顺序&#xff09;。 graph[i] 是一个从节点 i 可以访问的所有节点的列表&#xff08…

C语言修炼——什么是流?什么是文件?什么是文件操作?

目录 一、为什么使用文件&#xff1f;二、什么是文件&#xff1f;2.1 程序文件2.2 数据文件2.3 文件名 三、二进制文件和文本文件四、文件的打开和关闭4.1 流和标准流4.1.1 流4.1.2 标准流 4.2 文件指针4.3 文件的打开和关闭 五、文件的顺序读写5.1 顺序读写函数介绍a. fgetcb.…