4.5.2 研发辅助之SQL优化

Oinone体系中是不需要针对模型写SQL的,默认提供了通用的数据管理器。在带来便利的情况下,也导致传统的sql审查就没办法开展。但是我们可以以技术的手段收集慢SQL和限制问题SQL执行。

  1. 慢SQL搜集目的:去发现非原则性问题的慢SQL,并进行整改

  2. 限制问题SQL执行:对应一些不规范的SQL系统上直接做限制,如果有特殊情况手动放开

一、发现慢SQL

这个功能并没有直接加入到oinone的版本中,需要业务自行写插件,插件代码如下。大家可以根据实际情况进行改造比如:

  1. 堆栈入口,例子中只是放了pamirs,可以根据实际情况改成业务包路径

  2. 对慢SQL的定义是5s还是3s,根据实际情况变

package pro.shushi.pamirs.demo.core.plugin;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Component;
import pro.shushi.pamirs.meta.annotation.fun.extern.Slf4j;

@Intercepts({
        @Signature(type = Executor.class,method = "query",args = {MappedStatement.class,Object.class, RowBounds.class, ResultHandler.class})
})
@Component
@Slf4j
public class SlowSQLAnalysisInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        long start = System.currentTimeMillis();
        Object result = invocation.proceed();
        long end = System.currentTimeMillis();
        if (end - start > 10000) {//大于10秒
            try {
                StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
                StringBuffer slowLog = new StringBuffer();
                slowLog.append(System.lineSeparator());
                for (StackTraceElement element : stackTraceElements) {
                    if (element.getClassName().indexOf("pamirs") > 0) {
                        slowLog.append(element.getClassName()).append(":").append(element.getMethodName()).append(":").append(element.getLineNumber()).append(System.lineSeparator());
                    }
                }
                Object parameter = null;
                if (invocation.getArgs().length > 1) {
                    parameter = invocation.getArgs()[1];
                }
                MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
                BoundSql boundSql = mappedStatement.getBoundSql(parameter);
                Configuration configuration = mappedStatement.getConfiguration();
                String originalSql = showSql(configuration, boundSql);
                originalSql = originalSql.replaceAll("\'", "").replace("\"", "");
                log.warn("检测到的慢SQL为:" + originalSql);
                log.warn("业务慢SQL入口为:" + slowLog.toString());
            } catch (Throwable e1) {
                //忽略
            }
        }
        return result;
    }

    public String showSql(Configuration configuration, BoundSql boundSql) {
        Object parameterObject = boundSql.getParameterObject();
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        String sql = boundSql.getSql().replaceAll("[\\s]+", " ");
        if (parameterMappings.size() > 0 && parameterObject != null) {
            TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
            if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
                sql = sql.replaceFirst("\\?", getParameterValue(parameterObject));

            } else {
                MetaObject metaObject = configuration.newMetaObject(parameterObject);
                for (ParameterMapping parameterMapping : parameterMappings) {
                    String propertyName = parameterMapping.getProperty();
                    if (metaObject.hasGetter(propertyName)) {
                        Object obj = metaObject.getValue(propertyName);
                        sql = sql.replaceFirst("\\?", getParameterValue(obj));
                    } else if (boundSql.hasAdditionalParameter(propertyName)) {
                        Object obj = boundSql.getAdditionalParameter(propertyName);
                        sql = sql.replaceFirst("\\?", getParameterValue(obj));
                    }
                }
            }
        }
        return sql;
    }

    private String getParameterValue(Object obj) {
        String value = null;
        if (obj instanceof String) {
            value = "'" + obj.toString() + "'";
        } else if (obj instanceof Date) {
            DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.CHINA);
            value = "'" + formatter.format(obj) + "'";
        } else {
            if (obj != null) {
                value = obj.toString();
            } else {
                value = "";
            }
        }
        return value;
    }

}

图4-5-2-1 插件代码

二、限制问题SQL

Oinone的非法SQL校验插件:IllegalSQLInterceptor

目前版本oinone并没有生效该非法SQL校验的拦截器,因为这个插件晚于业务加入,所以为了避免伙伴应用因为插件原因改造就放到下个版本去,后续业务系统升级版本的时候,需要注意这个点

Oinone社区 作者:史, 昂原创文章,如若转载,请注明出处:https://doc.oinone.top/oio4/9314.html

访问Oinone官网:https://www.oinone.top获取数式Oinone低代码应用平台体验

(0)
史, 昂的头像史, 昂数式管理员
上一篇 2024年5月23日
下一篇 2024年5月23日

相关推荐

  • 登录日志

    1. 登录日志 登录日志:记录企业成员/用户登录平台的历史明细,包括登录时间、位置、IP、登录设备、登录平台等信息,登录平台包括:PC Web、小程序、H5、APP。登录日志不需要通过审计规则订阅,平台会记录每位用户的登录日志。 操作支持导出、查看详情。

    2024年6月20日
    1.2K00
  • 4.2.4 框架之网络请求-HttpClient

    oinone提供统一的网络请求底座,基于graphql二次封装 一、初始化 import { HttpClient } from '@kunlun/dependencies'; const http = HttpClient.getInstance(); http.setMiddleware() // 必须设置,请求回调。具体查看文章https://shushi.yuque.com/yqitvf/oinone/vwo80g http.setBaseURL() // 必须设置,后端请求的路径 图4-2-4-1 初始化代码示例 二、HttpClient详细介绍 获取实例 import { HttpClient } from '@kunlun/dependencies'; const http = HttpClient.getInstance(); 图4-2-4-2 获取实例 接口地址 import { HttpClient } from '@kunlun/dependencies'; const http = HttpClient.getInstance(); http.setBaseURL('接口地址'); http.getBaseURL(); // 获取接口地址 图4-2-4-3 接口地址 请求头 import { HttpClient } from '@kunlun/dependencies'; const http = HttpClient.getInstance(); http.setHeader({key: value}); 图4-2-4-4 请求头 variables import { HttpClient } from '@kunlun/dependencies'; const http = HttpClient.getInstance(); http.setExtendVariables((moduleName: string) => { return customFuntion(); }); 图4-2-4-5 variables 回调 import { HttpClient } from '@kunlun/dependencies'; const http = HttpClient.getInstance(); http.setMiddleware([middleware]); 图4-2-4-6 回调 业务使用-query private http = HttpClient.getInstance(); private getTestQuery = async () => { const query = `gql str`; const result = await this.http.query('module name', query); console.log(result) return result.data[`xx`]['xx']; // 返回的接口,打印出result对象层次返回 }; 图4-2-4-7 业务使用-query 业务使用-mutate private http = HttpClient.getInstance(); private getTestMutate = async () => { const mutation = `gql str`; const result = await this.http.mutate('module name', mutation); console.log(result) return result.data[`xx`]['xx']; // 返回的接口,打印出result对象层次返回 }; 图4-2-4-8 业务使用-mutate 三、如何使用HttpClient 初始化 在项目目录src/main.ts下初始化httpClient 初始化必须要做的事: 设置服务接口链接 设置接口请求回调 业务实战 前文说到自定义新增宠物表单,让我们在这个基础上加入我们的httpClient; 第一步新增service.ts 图4-2-4-8 新增service.ts service.ts import { HttpClient }…

    2024年5月23日
    1.5K00
  • 4.1.9 函数之元位指令

    元位指令系统是通过给请求上下文的指令位字段作按位与标记来对函数处理下发对应指令的系统。 一、元位指令介绍 元位指令系统是通过给请求上下文的指令位字段作按位与标记来对函数处理下发对应指令的系统。 元位指令系统分为请求上下文指令和数据指令两种。 数据指令 数据指令基本都是系统内核指令。业务开发时用不到这里就不介绍了。前20位都是系统内核预留 请求上下文指令 请求上下文指令:使用session上下文中非持久化META_BIT属性设置指令。 位 指令 指令名 前端默认值 后端默认值 描述 20 builtAction 内建动作 否 否 是否是平台内置定义的服务器动作对应操作:PamirsSession.directive().disableBuiltAction(); PamirsSession.directive().enableBuiltAction(); 21 unlock 失效乐观锁 否 否 系统对带有乐观锁模型默认使用乐观锁对应操作:PamirsSession.directive().enableOptimisticLocker(); PamirsSession.directive().disableOptimisticLocker(); 22 check 数据校验 是 否 系统后端操作默认不进行数据校验,标记后生效数据校验对应操作:PamirsSession.directive().enableCheck(); PamirsSession.directive().disableCheck(); 23 defaultValue 默认值计算 是 否 是否自动填充默认值对应操作:PamirsSession.directive().enableDefaultValue(); PamirsSession.directive().disableDefaultValue(); 24 extPoint 执行扩展点 是 否 前端请求默认执行扩展点,可以标记忽略扩展点。后端编程式调用数据管理器默认不执行扩展点对应操作:PamirsSession.directive().enableExtPoint(); PamirsSession.directive().disableExtPoint(); 25 hook 拦截 是 否 是否进行函数调用拦截对应操作:PamirsSession.directive().enableHook(); PamirsSession.directive().disableHook(); 26 authenticate 鉴权 是 否 系统默认进行权限校验与过滤,标记后使用权限校验对应操作:PamirsSession.directive().sudo(); PamirsSession.directive().disableSudo(); 27 ormColumn ORM字段别名 否 否 系统指令,请勿设置 28 usePkStrategy 使用PK策略 是 否 使用PK是否空作为采用新增还是更新的持久化策略对应操作:PamirsSession.directive().enableUsePkStrategy(); PamirsSession.directive().disableUsePkStrategy(); 29 fromClient 是否客户端调用 是 否 是否客户端(前端)调用对应操作:PamirsSession.directive().enableFromClient(); PamirsSession.directive().disableFromClient(); 30 sync 同步执行函数 否 否 异步执行函数强制使用同步方式执行(仅对Spring Bean有效) 31 ignoreFunManagement 忽略函数管理 否 否 忽略函数管理器处理,防止Spring调用重复拦截对应操作:PamirsSession.directive().enableIgnoreFunManagement(); PamirsSession.directive().disableIgnoreFunManagement(); 表4-1-9-1 请求上下文指令 二、使用指令 普通模式 PamirsSession.directive().disableOptimisticLocker(); try{ 更新逻辑 } finally { PamirsSession.directive().enableOptimisticLocker(); } 图4-1-9-1 普通模式代码示意 批量设置模式 Models.directive().run(() -> {此处添加逻辑}, SystemDirectiveEnum.AUTHENTICATE) 图4-1-9-2 批量设置模式代码示意 三、使用举例 我们在4.1.5【模型之持久层配置】一文中提到过失效乐观锁,我们在这里就尝试下吧。 Step1 修改PetItemInventroyAction 手动失效乐观锁 package pro.shushi.pamirs.demo.core.action; import org.springframework.stereotype.Component; import pro.shushi.pamirs.demo.api.model.PetItemInventroy; import pro.shushi.pamirs.meta.annotation.Function; import pro.shushi.pamirs.meta.annotation.Model; import pro.shushi.pamirs.meta.api.session.PamirsSession; import pro.shushi.pamirs.meta.constant.FunctionConstants; import pro.shushi.pamirs.meta.enmu.FunctionOpenEnum; import pro.shushi.pamirs.meta.enmu.FunctionTypeEnum; import java.util.ArrayList; import java.util.List; @Model.model(PetItemInventroy.MODEL_MODEL) @Component public class PetItemInventroyAction { @Function.Advanced(type= FunctionTypeEnum.UPDATE) @Function.fun(FunctionConstants.update) @Function(openLevel = {FunctionOpenEnum.API}) public PetItemInventroy update(PetItemInventroy data){ List<PetItemInventroy> inventroys = new ArrayList<>(); inventroys.add(data); PamirsSession.directive().disableOptimisticLocker(); try{ //批量更新会,自动抛错 int i = data.updateBatch(inventroys); //单记录更新,不自动抛售需要自行判断 // int i = data.updateById();…

    2024年5月23日
    1.0K00
  • 应用审计

    1. 整体介绍 应用审计是基于模型字段记录用户操作留痕记录,通过定义审计规则,平台基于审计规则订阅的字段记录形成日志。平台名词概念: 应用日志:针对已订阅的审计规则记录用户操作信息,是用户在各应用中操作行为留痕记录。 审计规则:业务审计中,数据变化订阅记录的规则。 操作入口:应用中心——业务审计应用。 2. 审计规则 审计规则是指定义审计过程订阅数据变化的信息,根据模型、订阅到具体字段内容变化形成应用日志。如订阅销售订单的备注,销售订单S20231001888,订单备注【尽快发货】,备注修改为【需易碎品包装】,审计规则为:销售订单模型,订阅【备注】。 操作包括:新增、编辑、删除。 2.1. 新增 新增时,定义审计规则名称,选择需要审计的模型,指定需要订阅的字段信息,同时可以指定关联关系的字段。 需要注意:每个模型仅限定义单条审计规则。 2.2. 编辑 编辑同新增操作,不做赘述。 2.3. 删除 删除规则后,平台将不再监听对应数据的变更日志,请慎重删除。 3. 应用日志 应用日志是针对已订阅的审计规则记录用户操作信息。记录操作用户、IP、登录设备、位置、订阅的字段变化内容。 应用日志详情 4. 业务表达 4.1. 展示效果 表格-行操作—日志记录 详情—日志记录 4.2. 操作步骤 Step1:在应用中心,需要维护业务应用依赖业务审计应用; 操作入口:应用中心,找到业务应用——编辑,依赖模块选择业务审计。 Step2:配置审计规则; 操作入口:业务审计应用——审计规则——新增规则。 Step2:界面设计器配置日志记录; 操作入口:界面设计器,找到需要配置的页面——模型组件,将动作区的日志记录拖动到页面中。

    2024年1月20日
    1.2K00

Leave a Reply

登录后才能评论