KScript 문서
KO

언어

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

캐싱: 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는 키에 저장된 값을 반환해요. 저장된 값이 없거나 만료되었으면 함수를 호출하고, 반환된 값을 10분 동안 보관한 뒤 그 값을 반환해요.

저장소

저장소는 캐시된 값이 보관되는 곳입니다. 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을(를) 실행한 뒤 그 값을 반환해요. 제한을 넘으면 TooManyRequests을(를) retry_after와(과) 함께 던지며, 이는 라우트에서 429로 응답돼요.
->hit() 로그인 실패처럼 시도 횟수를 집계하고, 남은 횟수를 반환해요.
->is_limited() 시도 횟수를 모두 사용했으면 참이에요.
->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는 1분 30초입니다. ttl이 없으면 값은 직접 제거하거나 저장소를 비울 때까지 보관됩니다.

HTTP 캐싱

KScript.Http는 HTTP 캐싱에 KScript.Cache를 사용해요. 라우트는 응답에 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