存储
存储是缓存值存放的位置。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是同一个存储。