feat: local cache

This commit is contained in:
withchao
2024-01-15 15:53:40 +08:00
parent abbb701192
commit c9193302a8
3 changed files with 45 additions and 19 deletions
-9
View File
@@ -107,15 +107,6 @@ func WithDeleteKeyBefore(fn func(ctx context.Context, key ...string)) Option {
}
}
func WithDeleteLocal(fn func(fn func(key ...string))) Option {
if fn == nil {
panic("fn should not be nil")
}
return func(o *option) {
o.delCh = fn
}
}
type emptyTarget struct{}
func (e emptyTarget) IncrGetHit() {}
+38 -3
View File
@@ -24,8 +24,43 @@ type GroupLocalCache struct {
local localcache.Cache[any]
}
func (g *GroupLocalCache) GetGroupMemberIDs(ctx context.Context, groupID string) ([]string, error) {
return localcache.AnyValue[[]string](g.local.Get(ctx, cachekey.GetGroupMemberIDsKey(groupID), func(ctx context.Context) (any, error) {
return g.client.GetGroupMemberIDs(ctx, groupID)
type listMap[V comparable] struct {
List []V
Map map[V]struct{}
}
func newListMap[V comparable](values []V, err error) (*listMap[V], error) {
if err != nil {
return nil, err
}
lm := &listMap[V]{
List: values,
Map: make(map[V]struct{}, len(values)),
}
for _, value := range values {
lm.Map[value] = struct{}{}
}
return lm, nil
}
func (g *GroupLocalCache) getGroupMemberIDs(ctx context.Context, groupID string) (*listMap[string], error) {
return localcache.AnyValue[*listMap[string]](g.local.Get(ctx, cachekey.GetGroupMemberIDsKey(groupID), func(ctx context.Context) (any, error) {
return newListMap(g.client.GetGroupMemberIDs(ctx, groupID))
}))
}
func (g *GroupLocalCache) GetGroupMemberIDs(ctx context.Context, groupID string) ([]string, error) {
res, err := g.getGroupMemberIDs(ctx, groupID)
if err != nil {
return nil, err
}
return res.List, nil
}
func (g *GroupLocalCache) GetGroupMemberIDMap(ctx context.Context, groupID string) (map[string]struct{}, error) {
res, err := g.getGroupMemberIDs(ctx, groupID)
if err != nil {
return nil, err
}
return res.Map, nil
}