encore-go-cache — скилл для Claude Code: кэш в Redis из Encore Go
Скилл учит агента писать кэш в Redis из Go-сервисов на Encore: типизированные keyspaces, TTL, атомарные счётчики.
npx skills add encoredev/skills --skill encore-go-cache -a claude-code
npx skills add encoredev/skills --skill go-cache -a claude-codeЧто делает encore-go-cache
Скилл описывает, как в Encore Go объявить cache.Cluster и завести keyspaces под каждый вид данных. Ключ собирается из KeyPattern и структуры ключа, значение хранится типизированно: строки, целые, float64, структуры в JSON, списки и множества. Для счётчиков есть атомарные Increment и Decrement, для условной записи — SetIfNotExists и Replace.
TTL задаётся через cache.ExpireIn, cache.ExpireDailyAt и cache.NeverExpire, а cache.KeepTTL сохраняет текущий срок при обновлении. Промах возвращается как cache.Miss, конфликт при вставке — как cache.KeyExists, и оба проверяются через errors.Is. Политику вытеснения выбирают в ClusterConfig, по умолчанию стоит cache.AllKeysLRU.
Локально Encore поднимает Redis в памяти с ограничением примерно на 100 ключей, поэтому нагрузочные тесты на нём ставить не стоит. Для постоянного хранения скилл отправляет к encore-go-database на Postgres или encore-go-bucket для объектов.
Какие задачи решает
- закэшировать горячее чтение в Go-сервисе на Encore
- считать запросы пользователя и упираться в лимит по счётчику
- хранить короткоживущие токены сессий с истечением
- собрать таблицу лидеров на атомарных инкрементах
- разложить кэш по keyspaces вместо ручных строковых ключей
Примеры запросов агенту
- закэшируй профиль пользователя в Redis через encore-go-cache с TTL в час
- сделай счётчик запросов на пользователя с атомарным Increment и окном 10 секунд
- положи токен сессии в keyspace со сроком жизни и обработай cache.Miss
Как установить encore-go-cache
1Через Skills CLI (Vercel)
npx skills add encoredev/skills --skill encore-go-cache -a claude-codenpx skills add encoredev/skills --skill go-cache -a claude-code2Вручную: положить файлы
~/.claude/skills/go-cache/SKILL.mdПапка скилла целиком; для одного проекта — .claude/skills/go-cache/
1Через Skills CLI (Vercel)
npx skills add encoredev/skills --skill go-cache -a codex2Вручную: положить файлы
.agents/skills/go-cache/SKILL.mdДля всех проектов — ~/.agents/skills/
1Через Skills CLI (Vercel)
npx skills add encoredev/skills --skill go-cache -a cursor2Вручную: положить файлы
.cursor/skills/go-cache/SKILL.mdCursor читает и .agents/skills/, и .claude/skills/
1GitHub CLI
gh skill install encoredev/skills go-cache2Вручную: положить файлы
.github/skills/go-cache/SKILL.md1Через Skills CLI (Vercel)
npx skills add encoredev/skills --skill go-cache -a gemini-cli2Командой платформы
gemini skills install https://github.com/encoredev/skills --path encore/go-cacheВручную: положить файлы
.devin/skills/go-cache/SKILL.mdСтарый путь .windsurf/skills/ тоже читается
Через Skills CLI (Vercel)
npx skills add encoredev/skills --skill go-cache -a opencodeClaude.ai
Упакуйте папку в zip и загрузите в Settings → Capabilities → Skills
По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов
Из того же набора10
Похожие
Рядом в теме «Бэкенд и API»
Всё по теме «Бэкенд и API» →Вопросы о encore-go-cache
Как установить encore-go-cache в Claude?
Через skills CLI: npx skills add encoredev/skills --skill encore-go-cache -a claude-code. Файл скилла окажется в ~/.claude/skills/go-cache/SKILL.md.
Что делает encore-go-cache?
Подсказывает агенту, как работать с кэшем в Encore Go: объявлять кластер, создавать типизированные keyspaces, ставить TTL и вызывать атомарные операции.
Чем кэш отличается от базы и бакета в Encore?
Кэш годится для эфемерных данных с истечением. Для постоянного хранения скилл советует encore-go-database на Postgres или encore-go-bucket для объектов.
Исходный текст
SKILL.md · Apache-2.0
---
name: encore-go-cache
description: Cache data in Redis from Encore Go using `cache.NewCluster` and typed keyspaces from `encore.dev/storage/cache`. Type-safe key/value access with TTLs, atomic increments, and per-keyspace data shapes.
when_to_use: >-
User wants to cache values in a Go service, store ephemeral state, rate-limit by counter, build a leaderboard, speed up a hot read, or store short-lived tokens. Covers `cache.NewCluster`, `cache.NewStringKeyspace`, `cache.NewIntKeyspace`, `cache.NewStructKeyspace`, list/set keyspaces, TTL helpers (`cache.ExpireIn`, `cache.ExpireDailyAt`, `cache.NeverExpire`), atomic `Increment`/`Decrement`, `SetIfNotExists`, `Replace`, eviction policies, and `cache.Miss`/`cache.KeyExists` errors. Trigger phrases: "cache this", "Redis", "key-value store", "rate limit", "TTL", "expire after", "in-memory store", "session token store", "leaderboard counter".
---
# Encore Go Caching (Redis)
## Instructions
Encore Go's cache is a typed wrapper around Redis. Declare a `cache.Cluster` once, then create `Keyspace` objects for each shape of data you need.
### Cluster
```go
package mycache
import "encore.dev/storage/cache"
var Cluster = cache.NewCluster("my-cache", cache.ClusterConfig{
EvictionPolicy: cache.AllKeysLRU,
})
```
Eviction policies: `cache.AllKeysLRU` (default), `cache.NoEviction`, `cache.AllKeysLFU`, `cache.AllKeysRandom`, `cache.VolatileLRU`, `cache.VolatileLFU`, `cache.VolatileTTL`, `cache.VolatileRandom`.
### Keyspace types
Each keyspace has a key shape (used to build the Redis key from `KeyPattern`) and a value type.
```go
package mycache
import (
"context"
"time"
"encore.dev/storage/cache"
)
type TokenKey struct {
TokenID string
}
// Strings
var Tokens = cache.NewStringKeyspace[TokenKey](Cluster, cache.KeyspaceConfig{
KeyPattern: "token/:TokenID",
DefaultExpiry: cache.ExpireIn(time.Hour),
})
func example(ctx context.Context) {
_ = Tokens.Set(ctx, TokenKey{TokenID: "abc"}, "value")
val, err := Tokens.Get(ctx, TokenKey{TokenID: "abc"}) // cache.Miss on miss
_ = Tokens.Delete(ctx, TokenKey{TokenID: "abc"})
_ = val
_ = err
}
```
```go
// Integers (atomic counters)
type CounterKey struct {
UserID string
}
var Counters = cache.NewIntKeyspace[CounterKey](Cluster, cache.KeyspaceConfig{
KeyPattern: "requests/:UserID",
DefaultExpiry: cache.ExpireIn(10 * time.Second),
})
func incr(ctx context.Context) {
count, _ := Counters.Increment(ctx, CounterKey{UserID: "user123"}, 1)
_, _ = Counters.Decrement(ctx, CounterKey{UserID: "user123"}, 1)
_ = count
}
```
```go
// Structs (JSON-encoded)
type ProfileKey struct {
UserID string
}
type UserProfile struct {
Name string
Email string
}
var Profiles = cache.NewStructKeyspace[ProfileKey, UserProfile](Cluster, cache.KeyspaceConfig{
KeyPattern: "profile/:UserID",
DefaultExpiry: cache.ExpireIn(time.Hour),
})
func setProfile(ctx context.Context) {
_ = Profiles.Set(ctx, ProfileKey{UserID: "123"}, UserProfile{
Name: "Alice", Email: "[email protected]",
})
}
```
### Other keyspace types
All from `encore.dev/storage/cache`:
- `NewFloatKeyspace` — float64 values, has `Increment`.
- `NewListKeyspace` — list values, with `PushLeft`/`PushRight`/`PopLeft`/`PopRight`/`GetRange`.
- `NewSetKeyspace` — set values, with `Add`/`Remove`/`Contains`/`Items`.
### Multi-field key patterns
```go
type ResourceKey struct {
UserID string
ResourcePath string
}
var ResourceRequests = cache.NewIntKeyspace[ResourceKey](Cluster, cache.KeyspaceConfig{
KeyPattern: "requests/:UserID/:ResourcePath",
DefaultExpiry: cache.ExpireIn(10 * time.Second),
})
```
### Expiry helpers
```go
import (
"encore.dev/storage/cache"
"time"
)
cache.ExpireIn(time.Hour) // relative
cache.ExpireDailyAt(2, 0, 0, time.UTC) // specific UTC time each day
cache.NeverExpire // no expiry
cache.KeepTTL // keep existing TTL when updating
```
### Errors
```go
import "encore.dev/storage/cache"
val, err := keyspace.Get(ctx, key)
if errors.Is(err, cache.Miss) {
// not in cache
}
err = keyspace.SetIfNotExists(ctx, key, value)
if errors.Is(err, cache.KeyExists) {
// already there
}
```
## Guidelines
- Declare `cache.Cluster` and keyspaces as package-level variables.
- Pick the most specific keyspace type — `IntKeyspace` for counters gives you atomic `Increment`/`Decrement` for free.
- `Get()` returns `cache.Miss` on miss; `Replace()` and `SetIfNotExists()` return `cache.Miss`/`cache.KeyExists` on conflict.
- Local development uses an in-memory Redis with a ~100-key cap — don't load-test it.
- For durable storage, use `encore-go-database` (Postgres) or `encore-go-bucket` (object storage) instead.
© encoredev · Apache-2.0 · encoredev/skills