KScript 文档
ZH

KScript.Cache

按键缓存值,并带有时间限制:可存于内存,或存于应用缓存文件夹中的文件。

在脚本顶部导入:

<import package="KScript.Cache" />
import KScript.Cache

KScript.Cache 会在多次运行之间保留值,因此其示例无法直接在文档中运行。请将其复制到 .ks.xml 文件中,然后用 kscript 运行。

命令

命令可通过 @ 调用,可用于任何表达式:@name(arguments)。

#@cache(store?: memory|file|database, name?) → cache

缓存存储:memory(默认,类似 $cache)、file(将值保存在应用缓存文件夹的文件中,使其在多次运行之间保留)或 database(将值保存在项目数据库的 kscript_cache 表中,使所有服务器共享)。名称可将一个存储的键与其他存储的键区分开。
参数接受
store 可选以下词之一:memory|file|database
name 可选任意值

参数可以命名:@cache(…, name: …)。

示例
<let name="weather" value="@cache(file, name: 'weather')" />
<echo>{ $weather->remember('today', fn() => 'sunny', ttl: 1h) }</echo>
$weather = @cache(file, name: 'weather')
echo $weather->remember('today', fn() => 'sunny', ttl: 1h)

#@rate_limit(key, limit: number, per: duration, store?: cache) → rate_limit

对任意对象(不仅是路由)的速率限制:在每个 per 时间窗口内,每个键最多允许 limit 次尝试,例如每个邮箱每小时最多 5 次密码重置。尝试次数计入缓存存储:默认为应用的内存缓存,或指定的存储(@cache(file),或在多台服务器需要共同计数时使用共享存储)。
参数接受
key 必填任意值
limit 必填数字
per 必填duration
store 可选cache

参数可以命名:@rate_limit(…, limit: …, per: …)。

示例
<let name="limit" value="@rate_limit('reset:ann@example.com', limit: 5, per: 1h)" />
<echo>{ $limit->attempt(fn() => 'sent') } { $limit->remaining() } left</echo>
$limit = @rate_limit('reset:ann@example.com', limit: 5, per: 1h)
echo "{ $limit->attempt(fn() => 'sent') } { $limit->remaining() } left"

方法

cache 值上的方法:->get()、->has()、->set()、->set_if_absent()、->group()、->clear_group()、->remember()、->remove()、->pull()、->lock()、->increment()、->ttl()、->keys()、->clear()

rate_limit 值上的方法:->attempt()、->hit()、->is_limited()、->remaining()、->available_in()、->clear()

变量

变量类型说明
$cachecache应用的内存缓存:$cache->remember('repos', fn() => @get_json($url), ttl: 10m)。它在 kscript 运行期间有效,因此在 kscript serve 中会被所有请求共享。@cache(file) 可在多次运行之间保留值。