mirror of
https://github.com/openimsdk/open-im-server.git
synced 2026-05-14 22:15:59 +08:00
feat: msg local cache
This commit is contained in:
@@ -2,11 +2,13 @@ package localcache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/openimsdk/open-im-server/v3/pkg/common/localcache/link"
|
||||
"github.com/openimsdk/open-im-server/v3/pkg/common/localcache/local"
|
||||
opt "github.com/openimsdk/open-im-server/v3/pkg/common/localcache/option"
|
||||
)
|
||||
|
||||
type Cache[V any] interface {
|
||||
Get(ctx context.Context, key string, fetch func(ctx context.Context) (V, error)) (V, error)
|
||||
Get(ctx context.Context, key string, fetch func(ctx context.Context) (V, error), opts ...*opt.Option) (V, error)
|
||||
Del(ctx context.Context, key ...string)
|
||||
}
|
||||
|
||||
@@ -15,7 +17,7 @@ func New[V any](opts ...Option) Cache[V] {
|
||||
for _, o := range opts {
|
||||
o(opt)
|
||||
}
|
||||
c := &cache[V]{opt: opt}
|
||||
c := &cache[V]{opt: opt, link: link.New(opt.localSlotNum)}
|
||||
c.local = local.NewCache[V](opt.localSlotNum, opt.localSlotSize, opt.localSuccessTTL, opt.localFailedTTL, opt.target, c.onEvict)
|
||||
go func() {
|
||||
c.opt.delCh(c.del)
|
||||
@@ -25,11 +27,16 @@ func New[V any](opts ...Option) Cache[V] {
|
||||
|
||||
type cache[V any] struct {
|
||||
opt *option
|
||||
link link.Link
|
||||
local local.Cache[V]
|
||||
}
|
||||
|
||||
func (c *cache[V]) onEvict(key string, value V) {
|
||||
|
||||
for k := range c.link.Del(key) {
|
||||
if key != k {
|
||||
c.local.Del(k)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *cache[V]) del(key ...string) {
|
||||
@@ -38,8 +45,15 @@ func (c *cache[V]) del(key ...string) {
|
||||
}
|
||||
}
|
||||
|
||||
func (c *cache[V]) Get(ctx context.Context, key string, fetch func(ctx context.Context) (V, error)) (V, error) {
|
||||
if c.opt.enable {
|
||||
func (c *cache[V]) Get(ctx context.Context, key string, fetch func(ctx context.Context) (V, error), opts ...*opt.Option) (V, error) {
|
||||
enable := c.opt.enable
|
||||
if len(opts) > 0 && opts[0].Enable != nil {
|
||||
enable = *opts[0].Enable
|
||||
}
|
||||
if enable {
|
||||
if len(opts) > 0 && len(opts[0].Link) > 0 {
|
||||
c.link.Link(key, opts[0].Link...)
|
||||
}
|
||||
return c.local.Get(key, func() (V, error) {
|
||||
return fetch(ctx)
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user