Skip to Content
Cache

Cache

GoFrame provides a simple cache layer backed by your database. Values are by default GOB encoded and may expire after a TTL.

When using dependency injection, register the implementation as contracts.Cache so your services can depend on the interface.

_ = cache.Put(ctx, "session:123", data, coretypes.WithTTL(time.Hour)) var v SomeType _ = cache.Get(ctx, "session:123", &v)

You can watch for updates using PostgreSQL notifications:

watch.go
channel, err := cache.Watch[string](ctx, p.Cache, "last_user_email") if err != nil { panic(err) } for { select { case r := <-channel: fmt.Println("Cache updated:", r.Type, r.Key, "=", *r.Value) case <-ctx.Done(): return // Exit if the context is done } }

Modify cache encoder/decoder

By default the cache uses GOB encoding. You can change this by implementing the cache.Encode and cache.Decode functions. For example, to use JSON encoding:

to

func init() { cache.Encode = func(v any) ([]byte, error) { return json.Marshal(v) } cache.Decode = func(data []byte, out any) error { return json.Unmarshal(data, out) } }
Last updated on