You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何缓存Kusto函数结果并每隔6小时自动刷新以降低数据库负载?

实现Kusto存储函数结果的定期缓存与复用

完全可以通过缓存表+周期性刷新任务的方式实现你的需求,既减轻数据库负载,又能复用查询结果。以下是具体实现步骤:

1. 创建缓存存储表

首先创建一张表来存储MyFunction的结果及元数据,字段需匹配你的函数参数和返回结构:

.create table MyFunctionCache (
    // 替换为你的函数实际参数(类型要对应)
    FunctionParam1: string,
    FunctionParam2: int,
    // 存储函数返回的结果,若返回结构化数据可拆分为单独字段,或用dynamic类型存储
    QueryResult: dynamic,
    // 记录缓存最后刷新时间,用于判断有效性
    LastRefreshed: datetime
)

2. 配置周期性刷新任务

用Kusto的周期性查询规则,每6小时自动运行MyFunction并更新缓存。

编写刷新脚本

先写好生成最新数据并写入缓存的脚本(假设你已经明确需要缓存的参数组合,若参数组合不固定,可先收集需要缓存的参数列表):

// 定义需要缓存的参数组合(根据实际情况调整)
let targetParams = datatable(FunctionParam1:string, FunctionParam2:int) [
    "ParamValue1", 100,
    "ParamValue2", 200,
    "ParamValue3", 300
];
// 调用存储函数获取最新数据
let freshResults = targetParams
| invoke MyFunction(FunctionParam1, FunctionParam2)
| join kind=inner targetParams on FunctionParam1, FunctionParam2
| extend LastRefreshed = now();
// 将数据写入缓存表(存在则覆盖,不存在则追加)
.set-or-append MyFunctionCache <| freshResults

创建周期性规则

可以通过Azure门户或CLI创建每6小时运行一次的查询规则:

az kusto query-rule create --cluster-name <你的集群名> --database-name <你的数据库名> --name RefreshMyFunctionCache --description "每6小时刷新MyFunction缓存" --query "<上面的Kusto脚本内容>" --frequency 6 --time-unit Hours --severity 3

3. 修改查询逻辑,优先读取缓存

后续调用时,先检查缓存是否有效(未超过6小时),有效则直接用缓存数据,无效或无缓存时再调用原函数(可选,也可等待下一次刷新):

// 定义本次调用的参数
let currentParam1 = "ParamValue1";
let currentParam2 = 100;
let cacheValidDuration = 6h;

// 尝试读取有效缓存
let cachedData = MyFunctionCache
| where FunctionParam1 == currentParam1 and FunctionParam2 == currentParam2
| where now() - LastRefreshed <= cacheValidDuration
| project QueryResult;

// 缓存无效时调用原函数(可选逻辑,避免冷启动)
let finalData = toscalar(cachedData) == dynamic(null)
    ? MyFunction(currentParam1, currentParam2)
    : cachedData;

// 使用最终数据
finalData

额外优化建议

  • 给缓存表设置数据保留策略,避免旧缓存堆积:
    .alter table MyFunctionCache policy retention softdelete = 30d
    
  • 如果参数组合频繁变化,可以在缓存表中添加清理逻辑,比如定期删除超过7天的旧缓存。
  • 若不需要实时回退到原函数,可以去掉缓存无效时调用原函数的逻辑,直接返回最新的缓存数据。

内容的提问来源于stack exchange,提问作者Luke Schoen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 06:00:02