KScript 文档
ZH

缓存:KScript.Cache

简介

有些工作很慢:一次网络请求、读取大文件、一次长时间的计算。如果它的结果不会每次都变,你可以保存这个结果并重复使用。KScript.Cache 按键保存数值,保存时长由你指定,这样慢的工作只需做一次。

要开始使用,请导入该包并使用$cache:

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

<let name="repos" value="$cache->remember('repos', fn() => @api('https://api.example.com/repos')->convert(from: json), ttl: 10m)" />
<echo>{ $repos->count() } repos</echo>
import KScript.Cache
import KScript.Net

$repos = $cache->remember('repos', fn() => @api('https://api.example.com/repos')->convert(from: json), ttl: 10m)
echo "{ $repos->count() } repos"

remember 返回该键下保存的值。如果没有该值,或该值已过期,则调用该函数,将其返回结果保存十分钟,并返回该结果。

存储

存储是缓存值存放的位置。KScript.Cache 提供三种存储。

$cache将值保存在内存中,只要 kscript 在运行就一直有效。在kscript serve中,所有请求共享同一存储,因此一个请求保存的值,下一个请求也能读取:

<import package="KScript.Cache" />

<do>$cache->set('greeting', 'Hello', ttl: 1h)</do>
<echo value="$cache->get('greeting')" />
import KScript.Cache

$cache->set('greeting', 'Hello', ttl: 1h)
echo $cache->get('greeting')

@cache(file)将每个值保存在应用的cache文件夹中的一个文件里(参见应用文件夹),因此值在多次运行之间依然保留。值以 JSON 格式保存,所以文件存储可以保存映射、列表、文本、数字以及 true 或 false:

<import package="KScript.Cache" />

<let name="weather" value="@cache(file)" />
<do>$weather->set('london', { high: 14, low: 6 }, ttl: 3h)</do>
<echo value="$weather->get('london').high" />
import KScript.Cache

$weather = @cache(file)
$weather->set('london', { high: 14, low: 6 }, ttl: 3h)
echo $weather->get('london').high

@cache(database)将值保存在项目数据库的kscript_cache表中,因此使用该数据库的每台服务器都共享这些值:计数、锁和速率限制因而可以在所有服务器间保持一致。该表会在首次需要时自动创建:

<import package="KScript.Cache" />

<let name="shared" value="@cache(database, name: 'reports')" />
<do>$shared->increment('built')</do>
<echo>{ $shared->get('built') } reports built</echo>
import KScript.Cache

$shared = @cache(database, name: 'reports')
$shared->increment('built')
echo "{ $shared->get('built') } reports built"

为存储指定名称,使其键与其他存储的键分开:@cache(file, name: 'weather')。存储同样归属于其应用,因此两个应用永远看不到彼此的键。@cache(memory)与$cache是同一个存储。

使用缓存

读取值

->get()返回某个键下的值。当键不存在,或其值已过期时,返回null或你指定的默认值:

<import package="KScript.Cache" />

<let name="theme" value="$cache->get('theme', default: 'light')" />
<echo value="$theme" />
import KScript.Cache

$theme = $cache->get('theme', default: 'light')
echo $theme

->has()可在不读取值的情况下判断值是否存在,->ttl()以时长形式给出剩余时间(永不过期时为null),->keys()按排序列出所有键:

<import package="KScript.Cache" />

<do>$cache->set('token', 'abc123', ttl: 15m)</do>
<if $cache->has('token')>
  <echo>The token runs out in { $cache->ttl('token') }</echo>
</if>
<echo value="$cache->keys()" />
import KScript.Cache

$cache->set('token', 'abc123', ttl: 15m)
if $cache->has('token') => echo "The token runs out in { $cache->ttl('token') }"
echo $cache->keys()

存储值

->set()保存一个值并返回它。->set_if_absent()仅当键尚不存在(或已过期)时才保存,并且在本次调用确实保存了值时返回 true,因此可用作简单的锁:

<import package="KScript.Cache" />

<do>$cache->set('last_run', @now())</do>
<if $cache->set_if_absent('report_running', true, ttl: 5m)>
  <echo>Building the report</echo>
</if>
import KScript.Cache

$cache->set('last_run', @now())
if $cache->set_if_absent('report_running', true, ttl: 5m) {
  echo 'Building the report'
}

记忆结果

大多数情况下你需要的是->remember():读取值;若值不存在,则计算并保存它。该函数只在未命中时运行:

<import package="KScript.Cache" />

<fn name="slow_total" value="[1, 2, 3, 4]->sum()" />

<let name="total" value="$cache->remember('total', fn() => @slow_total(), ttl: 1h)" />
<echo value="$total" />
import KScript.Cache

fn slow_total() => [1, 2, 3, 4]->sum()

$total = $cache->remember('total', fn() => @slow_total(), ttl: 1h)
echo $total

计数

->increment()对数字进行累加并返回新值。不存在的键从 0 开始。累加是单步完成的,因此同时发生的请求和脚本都能被正确计数。计数会保留其启动时设定的时间限制,除非你给出新的限制:

<import package="KScript.Cache" />

<let name="store" value="@cache(file, name: 'visits')" />
<let name="count" value="$store->increment('today', ttl: 1d)" />
<do>$store->increment('downloads', by: 5)</do>
<echo>Visit { $count } today</echo>
import KScript.Cache

$store = @cache(file, name: 'visits')
$count = $store->increment('today', ttl: 1d)
$store->increment('downloads', by: 5)
echo "Visit { $count } today"

删除值

->remove()删除一个键,若该键存在则返回 true。->pull()一步完成取值并删除。->clear()删除所有键,并返回删除的数量:

<import package="KScript.Cache" />

<do>$cache->set('draft', 'Dear Joan')</do>
<do>$cache->remove('draft')</do>
<do>$cache->set('code', 123456, ttl: 10m)</do>
<let name="code" value="$cache->pull('code')" />
<echo>Cleared { $cache->clear() } values</echo>
import KScript.Cache

$cache->set('draft', 'Dear Joan')
$cache->remove('draft')
$cache->set('code', 123456, ttl: 10m)
$code = $cache->pull('code')
echo "Cleared { $cache->clear() } values"

锁

->lock()在持有锁的情况下执行一些工作,使用同一存储的其他请求、工作进程或进程都无法同时持有该锁,并返回工作的结果。用它可以避免两个工作进程同时生成同一份报告。ttl是锁被持有的最长时间,以防进程中途停止。当锁已被其他方持有时,->lock()会立即返回null,或在等待最多wait后返回。

<import package="KScript.Cache" />

<let name="store" value="@cache(file)" />
<let name="report" value="$store->lock('report:daily', ttl: 5m, wait: 10s, work: fn() => 'built')" />
<if $report == null>
  <echo>Another worker is building it</echo>
</if>
import KScript.Cache

$store = @cache(file)
$report = $store->lock('report:daily', ttl: 5m, wait: 10s, work: fn() => 'built')
if $report == null => echo "Another worker is building it"

每个锁保存在lock:之下及其键名下,并附带一个只有持有者知道的令牌,因此只有持有者才能释放它。内存存储在单个进程内加锁,文件存储在同一台机器的多个进程间加锁,数据库存储在使用该数据库的所有服务器间加锁。

速率限制

@rate_limit(key, limit:, per:) 会对某个键下的尝试次数进行计数,超过限制后拒绝这些尝试,适用于任何脚本,而不仅限于路由。计数保存在应用的内存缓存中,或保存在你提供的 store: 中:

<import package="KScript.Cache" />

<let name="limit" value="@rate_limit('login:ann@example.com', limit: 5, per: 1m)" />
<if $limit->is_limited()>
  <echo>Try again in { $limit->available_in() }</echo>
</if>
<do>$limit->hit()</do>
<echo>{ $limit->remaining() } tries left</echo>
<do>$limit->clear()</do>
import KScript.Cache

$limit = @rate_limit('login:ann@example.com', limit: 5, per: 1m)
if $limit->is_limited() => echo "Try again in { $limit->available_in() }"
$limit->hit()
echo "{ $limit->remaining() } tries left"
$limit->clear()
方法 作用
->attempt(work) 每次调用都会计为一次尝试并运行 work,然后返回其值。超过上限后会抛出带有 retry_after 的 TooManyRequests,路由会以 429 进行响应。
->hit() 统计一次尝试(例如登录失败),并返回剩余的尝试次数。
->is_limited() 当前次数已用完时为 True。
->remaining() 此窗口中剩余的尝试次数。
->available_in() 多长时间后可以再次尝试:0s,剩余次数用完后。
->clear() 忘记尝试次数,例如成功登录之后。

时间窗口从第一次尝试开始,持续per。要跨多台服务器统计,请提供一个共享存储:@rate_limit('login:' + $email, limit: 5, per: 1m, store: @cache(database))。

分组

分组是存储内部自带的小型缓存,拥有相同的方法。它的键与存储本身的键以及其他分组的键分开保存,->clear_group()可以一次性删除所有这些键:

<import package="KScript.Cache" />

<let name="rates" value="$cache->group('rates')" />
<do>$rates->set('GBP', 1.0)</do>
<do>$rates->set('EUR', 1.17)</do>
<echo>Removed { $cache->clear_group('rates') } rates</echo>
import KScript.Cache

$rates = $cache->group('rates')
$rates->set('GBP', 1.0)
$rates->set('EUR', 1.17)
echo "Removed { $cache->clear_group('rates') } rates"

时间限制

ttl是值的保存时长,以时长形式书写:500ms、30s、10m、2h、1d或1w,也可组合使用(1h30m)。纯数字表示秒,因此ttl: 90即一分半钟。若没有ttl,值将一直保留,直到你将其删除或清空存储。

HTTP 缓存

KScript.Http 使用 KScript.Cache 进行 HTTP 缓存。路由可以为其响应添加 ETag,当浏览器已经拥有最新响应时返回 304 Not Modified,设置 Cache-Control,并将完整响应保存在内存缓存中:

<KScript.Routes>
  <import path="controllers/people.kscript" as="people" />

  <Get path="/people" to="people.index" etag="true" cache="60" />
  <Get path="/stats" to="people.stats" middleware="'cache_response:5m'" />
</KScript.Routes>
import KScript.Http
import "controllers/people.kscript" as people

Routes {
  Get(path: /people, to: @people.index, etag: true, cache: 60)
  Get(path: /stats, to: @people.stats, middleware: 'cache_response:5m')
}

有关详细信息,请参见缓存与 ETag。

Edit this page on GitHub