KScript 문서
KO

언어

영어에서 자동 번역되었습니다. 원문은 영어입니다.

캐싱: KScript.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:과 키 아래에 보관되며, 보유자만 아는 토큰이 함께 저장되므로 보유자만 잠금을 해제할 수 있습니다. 메모리 저장소는 하나의 프로세스 안에서, 파일 저장소는 한 컴퓨터의 여러 프로세스에 걸쳐, 데이터베이스 저장소는 이 데이터베이스를 사용하는 모든 서버에 걸쳐 잠금을 보장합니다.