Files
open-im-server/pkg/localcache/cache.go
T

86 lines
1.7 KiB
Go
Raw Normal View History

2024-01-08 15:39:39 +08:00
package localcache
import (
"context"
2024-01-12 17:51:01 +08:00
"github.com/openimsdk/localcache/link"
"github.com/openimsdk/localcache/local"
lopt "github.com/openimsdk/localcache/option"
2024-01-08 15:39:39 +08:00
)
type Cache[V any] interface {
2024-01-12 15:41:05 +08:00
Get(ctx context.Context, key string, fetch func(ctx context.Context) (V, error), opts ...*lopt.Option) (V, error)
2024-01-08 15:39:39 +08:00
Del(ctx context.Context, key ...string)
}
func New[V any](opts ...Option) Cache[V] {
opt := defaultOption()
for _, o := range opts {
o(opt)
}
2024-01-12 15:41:05 +08:00
c := cache[V]{opt: opt}
if opt.localSlotNum > 0 && opt.localSlotSize > 0 {
c.local = local.NewCache[V](opt.localSlotNum, opt.localSlotSize, opt.localSuccessTTL, opt.localFailedTTL, opt.target, c.onEvict)
go func() {
c.opt.delCh(c.del)
}()
if opt.linkSlotNum > 0 {
c.link = link.New(opt.linkSlotNum)
}
}
return &c
2024-01-08 15:39:39 +08:00
}
type cache[V any] struct {
opt *option
2024-01-08 20:36:41 +08:00
link link.Link
2024-01-08 15:39:39 +08:00
local local.Cache[V]
}
2024-01-08 16:47:39 +08:00
func (c *cache[V]) onEvict(key string, value V) {
2024-01-12 15:41:05 +08:00
if c.link != nil {
lks := c.link.Del(key)
for k := range lks {
if key != k { // prevent deadlock
c.local.Del(k)
}
2024-01-10 16:13:55 +08:00
}
2024-01-08 20:36:41 +08:00
}
2024-01-08 16:47:39 +08:00
}
2024-01-08 15:39:39 +08:00
func (c *cache[V]) del(key ...string) {
for _, k := range key {
2024-01-10 16:03:49 +08:00
lks := c.link.Del(k)
2024-01-08 15:39:39 +08:00
c.local.Del(k)
2024-01-10 16:03:49 +08:00
for k := range lks {
c.local.Del(k)
}
2024-01-08 15:39:39 +08:00
}
}
2024-01-12 15:41:05 +08:00
func (c *cache[V]) Get(ctx context.Context, key string, fetch func(ctx context.Context) (V, error), opts ...*lopt.Option) (V, error) {
if c.local != nil {
2024-01-08 15:39:39 +08:00
return c.local.Get(key, func() (V, error) {
2024-01-12 15:41:05 +08:00
if c.link != nil {
for _, o := range opts {
c.link.Link(key, o.Link...)
}
}
2024-01-08 15:39:39 +08:00
return fetch(ctx)
})
} else {
return fetch(ctx)
}
}
func (c *cache[V]) Del(ctx context.Context, key ...string) {
if len(key) == 0 {
return
}
for _, fn := range c.opt.delFn {
fn(ctx, key...)
}
2024-01-12 15:41:05 +08:00
if c.local != nil {
2024-01-08 15:39:39 +08:00
c.del(key...)
}
}