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日

相关推荐

  • 4.1.10 函数之触发与定时(改)

    函数的触发和定时在很多场景中会用到,也是一个oinone的基础能力。比如我们的流程产品中在定义流程触发时就会让用户选择模型触发还是时间触发,就是用到了函数的触发与定时能力。 整体链路示意图(如下图4-1-10-1 所示),本文只讲trigger里的两类任务,一个是触发任务,一个是定时任务,异步任务放在4.1.11【函数之异步执行】一文中单独去介绍。 图4-1-10-1 整体链路示意图 一、触发任务TriggerTaskAction(举例) 触发任务的创建,使用pamirs-middleware-canal监听mysql的binlog事件,通过rocketmq发送变更数据消息,收到MQ消息后,创建TriggerAutoTask。 触发任务的执行,使用TBSchedule拉取触发任务后,执行相应函数。 注意:pamirs-middleware-canal监听的数据库表必须包含触发模型的数据库表。 Step1 下载canal中间件 下载pamirs-middleware-canal-deployer-3.0.1.zip,去.txt后缀为pamirs-middleware-canal-deployer-3.0.1.zip,解压文件如下: 图4-1-10-2 下载canal中间件 Step2 引入依赖pamirs-core-trigger模块 pamirs-demo-api增加pamirs-trigger-api <dependency> <groupId>pro.shushi.pamirs.core</groupId> <artifactId>pamirs-trigger-api</artifactId> </dependency> 图4-1-10-3 pamirs-trigger-api依赖包 DemoModule在模块依赖定义中增加@Module(dependencies={TriggerModule.MODULE_MODULE}) @Component @Module( name = DemoModule.MODULE_NAME, displayName = "oinoneDemo工程", version = "1.0.0", dependencies = {ModuleConstants.MODULE_BASE, CommonModule.MODULE_MODULE, UserModule.MODULE_MODULE, TriggerModule.MODULE_MODULE} ) @Module.module(DemoModule.MODULE_MODULE) @Module.Advanced(selfBuilt = true, application = true) @UxHomepage(PetShopProxy.MODEL_MODEL) public class DemoModule implements PamirsModule { ……其他代码 } 图4-1-10-4 模块依赖中增加Trigger模块 pamirs-demo-boot 增加pamirs-trigger-core和pamirs-trigger-bridge-tbschedule的依赖 <dependency> <groupId>pro.shushi.pamirs.core</groupId> <artifactId>pamirs-trigger-core</artifactId> </dependency> <dependency> <groupId>pro.shushi.pamirs.core</groupId> <artifactId>pamirs-trigger-bridge-tbschedule</artifactId> </dependency> 图4-1-10-5 增加pamirs-trigger-core和pamirs-trigger-bridge-tbschedule的依赖 修改pamirs-demo-boot的applcation-dev.yml 修改pamris.event.enabled和pamris.event.schedule.enabled为true pamirs_boot_modules增加启动模块:trigger pamirs: event: enabled: true schedule: enabled: true rocket-mq: namesrv-addr: 127.0.0.1:9876 boot: init: true sync: true modules: – base – common – sequence – resource – user – auth – message – international – business – trigger – demo_core 图4-1-10-6 启动模块中增加trigger模块 Step3 启动canal中间件 canal的库表需要手工建 create schema canal_tsdb collate utf8mb4_bin 图4-1-10-7 canal的建库语句 CREATE TABLE IF NOT EXISTS `meta_snapshot` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键', `gmt_create` datetime NOT NULL COMMENT '创建时间', `gmt_modified` datetime NOT NULL COMMENT '修改时间', `destination` varchar(128) DEFAULT NULL COMMENT '通道名称', `binlog_file` varchar(64) DEFAULT NULL COMMENT 'binlog文件名', `binlog_offest` bigint(20) DEFAULT NULL COMMENT 'binlog偏移量', `binlog_master_id` varchar(64) DEFAULT NULL COMMENT 'binlog节点id', `binlog_timestamp` bigint(20) DEFAULT NULL…

    2024年5月23日
    1.1K00
  • 用户中心

    1. 创建用户 进入用户中心应用,在用户列表中点击创建。 填写表单中的必填信息。 若未设置昵称,则右上角头像右侧展示名称。若设置了昵称,则右上角头像右侧展示昵称。 是否激活账号选择是,选择否时用户登录会显示“未找到首页”。 角色分组中,选择创建的用户的角色,默认选择了超级管理员(包含所有权限)。 点击确定,用户创建完成。 用户登录时可用登录账号/邮箱/手机号登录。 2. 用户相关操作 表格页中包含常规的搜索、批量删除功能。 冻结:当将“是否有效”状态为“是”时展示,将用户“是否有效”修改为“否”。 解冻:当将“是否有效”状态为“否”时展示,将用户“是否有效”修改为“是”。 修改:进入用户信息修改页面,“编码、登录账号、注册时间”只读。 重置密码:点击后在弹窗“账号确认”中输入账号,点击重置密码后,展示新密码。

    2024年6月20日
    1.8K00
  • 3.3.3 模型的数据管理器

    数据管理器和数据构造器是Oinone为模型自动赋予的Function是内在数据管理能力,数据管理器针对存储模型是方便在大家编程模式下可以利用数据管理器Function快速达到相关数据操作的目的。数据构造器则主要用于模型进行初始化时字段默认值计算和页面交互 数据管理器 只有存储模型才有数据管理器。如果@Model.Advanced注解设置了dataManager属性为false,则表示在UI层不开放默认数据管理器。开放级别为API则表示UI层可以通过HTTP请求利用4.1.15【Pamirs标准网关协议】进行数据交互。 模型默认数据读管理器 函数编码 描述 开放级别 queryByPk 根据主键查询单条记录,会进行主键值检查 Local、Remote queryByEntity 根据实体查询单条记录 Local、Remote、Api queryByWrapper 根据查询类查询单条记录 Local、Remote queryListByEntity 根据实体查询返回记录列表 Local、Remote queryListByWrapper 根据查询类查询记录列表 Local、Remote queryListByPage 根据实体分页查询返回记录列表 Local、Remote queryListByPageAndWrapper 根据查询类分页查询记录列表 Local、Remote queryPage 分页查询返回分页对象,分页对象中包含记录列表 Local、Remote、Api countByEntity 按实体条件获取记录数量 Local、Remote countByWrapper 按查询类条件获取记录数量 Local、Remote 表3-3-3-1 模型默认数据读管理器 模型默认数据写管理器 函数编码 描述 开放级别 createOne 提交新增单条记录 Local、Remote createOrUpdate 新增或更新,需要为模型设置唯一索引,如果数据库检测到索引冲突,会更新数据,若未冲突则新增数据 Local、Remote updateByPk 根据主键更新单条记录,会进行主键值检查 Local、Remote updateByUniqueField 条件更新,条件中必须包含唯一索引字段 Local、Remote updateByEntity 按实体条件更新记录 Local、Remote、Api updateByWrapper 按查询类条件更新记录 Local、Remote createBatch 批量新增记录 Local、Remote createOrUpdateBatch 批量新增或更新记录 Local、Remote updateBatch 根据主键批量更新记录,会进行主键值检查 Local、Remote deleteByPk 根据主键删除单条记录,会进行主键值检查 Local、Remote deleteByPks 根据主键批量删除,会进行主键值检查 Local、Remote deleteByUniqueField 按条件删除记录,条件中必须包含唯一索引字段 Local、Remote deleteByEntity 根据实体条件删除 Local、Remote、Api deleteByWrapper 根据查询类条件删除 Local、Remote createWithField 新增实体记录并更新实体字段记录 Local、Remote、Api updateWithField 更新实体记录并更新实体字段记录 Local、Remote、Api deleteWithFieldBatch 批量删除实体记录并删除关联关系 Local、Remote、Api 表3-3-3-2 模型默认数据写管理器 如果模型继承IdModel,模型会自动设置主键设置为id,则会继承queryById、updateById和deleteById函数。 queryById(详情,根据ID查询单条记录,开放级别为Remote) updateById(提交更新单条记录,根据ID更新单条记录,开放级别为Remote) deleteById(提交删除单条记录,根据ID删除单条记录,开放级别为Remote) 如果模型继承CodeModel,模型也会继承IdModel的数据管理器,编码字段code为唯一索引字段。在新增数据时会根据编码生成规则自动设置编码字段code的值,继承queryByCode、updateByCode和deleteByCode函数。 queryByCode(详情,根据code查询单条记录,开放级别为Remote) updateByCode(提交更新单条记录,根据code更新单条记录,开放级别为Remote) deleteByCode(提交删除单条记录,根据code删除单条记录,开放级别为Remote) 没有主键或唯一索引的模型,在UI层不会开放默认数据写管理器。 #### 使用场景 图3-3-3-1 数据管理器使用场景 数据构造器 模型数据构造器 construct:供前端新开页面构造默认数据使用。所有模型都拥有construct构造器,默认会将字段上配置的默认值返回给前端,另外可以在子类中覆盖construct方法。数据构造器 construct函数的开放级别为API,函数类型为QUERY查询函数,系统将识别模型中的以construct命名的函数强制设置为API开放级别和QUERY查询类型。 可以使用@Field的defaultValue属性配置字段的默认值。注意,枚举的默认值为枚举的name。

    2024年5月23日
    1.3K10
  • 3.4.3 函数的相关特性

    本小章会从oinone的函数拥有三方面特性,展开介绍 面向对象,继承与多态 面向切面编程,拦截器 SPI机制,扩展点

  • 6.6 消息

    在我们系统研发过程中经常需要发送短信、邮件、站内信等,笔者在本文给大家介绍下如何使用Oinone的消息模块。 准备工作 如果通过我们工程脚手架工具生成的则已经引入了无需做更多的配置,如果不是则需要按以下步骤先配置依赖和增加启动模块 pamirs-demo-boot的pom文件中引入pamirs-message-core包依赖 <dependency> <groupId>pro.shushi.pamirs.core</groupId> <artifactId>pamirs-message-core</artifactId> </dependency> pamirs-demo-boot的application-dev.yml文件中增加配置pamirs.boot.modules增加message,即在启动应用中增加message模块 pamirs: boot: modules: – message 消息参数设置 发送邮件和短信需要设置对应的发送邮箱服务器和短信云,短信目前默认阿里云短信。我们通过代码示例来完成对应邮箱和短信的参数设置 Step1 增加pamirs-message-api依赖 pamirs-demo-core的pom文件中引入pamirs-message-api包依赖 <dependency> <groupId>pro.shushi.pamirs.core</groupId> <artifactId>pamirs-message-api</artifactId> </dependency> Step2 消息参数设置 请自行替换邮箱服务器和短信通道的账号信息 package pro.shushi.pamirs.demo.core.init; import org.springframework.stereotype.Component; import pro.shushi.pamirs.boot.common.api.command.AppLifecycleCommand; import pro.shushi.pamirs.boot.common.api.init.InstallDataInit; import pro.shushi.pamirs.boot.common.api.init.UpgradeDataInit; import pro.shushi.pamirs.demo.api.DemoModule; import pro.shushi.pamirs.message.enmu.EmailSendSecurityEnum; import pro.shushi.pamirs.message.enmu.MessageEngineTypeEnum; import pro.shushi.pamirs.message.enmu.SMSChannelEnum; import pro.shushi.pamirs.message.model.EmailSenderSource; import pro.shushi.pamirs.message.model.SmsChannelConfig; import java.util.Collections; import java.util.List; @Component public class DemoMessageInit implements InstallDataInit, UpgradeDataInit { private void initEmail(){ EmailSenderSource emailSenderSource = new EmailSenderSource(); emailSenderSource.setName("邮件发送服务"); emailSenderSource.setType(MessageEngineTypeEnum.EMAIL_SEND); //优先级 emailSenderSource.setSequence(10); //发送账号 FIXME 自行替换 emailSenderSource.setSmtpUser(""); //发送密码 FIXME 自行替换 emailSenderSource.setSmtpPassword(""); //发送服务器地址和端口 emailSenderSource.setSmtpHost("smtp.exmail.qq.com"); emailSenderSource.setSmtpPort(465); //" None: SMTP 对话用明文完成。" + //" TLS (STARTTLS): SMTP对话的开始时要求TLS 加密 (建议)" + //" SSL/TLS: SMTP对话通过专用端口用 SSL/TLS 加密 (默认是: 465)") emailSenderSource.setSmtpSecurity(EmailSendSecurityEnum.SSL); emailSenderSource.createOrUpdate(); } private void initSms(){ SmsChannelConfig smsChannelConfig = new SmsChannelConfig(); smsChannelConfig.setType(MessageEngineTypeEnum.SMS_SEND); smsChannelConfig.setChannel(SMSChannelEnum.ALIYUN); //短信签名名称 smsChannelConfig.setSignName("oinone"); //阿里云账号信息 FIXME 自行替换 smsChannelConfig.setAccessKeyId(""); smsChannelConfig.setAccessKeySecret(""); smsChannelConfig.setEndpoint("https://dysmsapi.aliyuncs.com"); smsChannelConfig.setRegionId("cn-hangzhou"); smsChannelConfig.setTimeZone("GMT"); smsChannelConfig.setSignatureMethod("HMAC-SHA1"); smsChannelConfig.setSignatureVersion("1.0"); smsChannelConfig.setVersion("2017-05-25"); smsChannelConfig.createOrUpdate(); //初始化短信模版 //目前支持阿里云短信通道:获取短信模板,如没有短信模板,需要先创建模板,并审核通过 SmsTemplate smsTemplate = new SmsTemplate(); smsTemplate.setName("通知短信"); smsTemplate.setTemplateType(SMSTemplateTypeEnum.NOTIFY); smsTemplate.setTemplateCode("SMS_244595482");//从阿里云获取,自行提供 FIXME smsTemplate.setTemplateContent("尊敬的&{name},你的&{itemName}库存为&{quantity}"); smsTemplate.setChannel(SMSChannelEnum.ALIYUN); smsTemplate.setStatus(SMSTemplateStatusEnum.SUCCESS); smsTemplate.createOrUpdate(); } @Override public boolean init(AppLifecycleCommand command, String version) { initEmail(); initSms(); return Boolean.TRUE; } @Override public boolean upgrade(AppLifecycleCommand command, String version, String existVersion) { initEmail(); initSms(); return Boolean.TRUE; } @Override public List<String> modules() { return Collections.singletonList(DemoModule.MODULE_MODULE);…

    2024年5月23日
    1.1K00

Leave a Reply

登录后才能评论