Files
open-im-server/pkg/common/db/cache/group.go
T

86 lines
2.4 KiB
Go
Raw Normal View History

2023-01-17 14:40:20 +08:00
package cache
import (
2023-01-28 13:19:36 +08:00
"Open_IM/pkg/common/db/relation"
2023-01-17 14:40:20 +08:00
"Open_IM/pkg/common/trace_log"
"Open_IM/pkg/utils"
"context"
"encoding/json"
"github.com/dtm-labs/rockscache"
"github.com/go-redis/redis/v8"
"time"
)
const GroupExpireTime = time.Second * 60 * 60 * 12
const groupInfoCacheKey = "GROUP_INFO_CACHE:"
type GroupCache struct {
2023-01-28 13:19:36 +08:00
db *relation.Group
2023-01-17 16:36:34 +08:00
expireTime time.Duration
redisClient *RedisClient
rcClient *rockscache.Client
2023-01-17 14:40:20 +08:00
}
2023-01-28 13:19:36 +08:00
func NewGroupCache(rdb redis.UniversalClient, db *relation.Group, opts rockscache.Options) *GroupCache {
2023-01-17 17:49:29 +08:00
return &GroupCache{rcClient: rockscache.NewClient(rdb, opts), expireTime: GroupExpireTime, db: db, redisClient: NewRedisClient(rdb)}
2023-01-17 16:36:34 +08:00
}
func (g *GroupCache) getRedisClient() *RedisClient {
return g.redisClient
2023-01-17 14:40:20 +08:00
}
2023-01-28 13:19:36 +08:00
func (g *GroupCache) GetGroupsInfoFromCache(ctx context.Context, groupIDs []string) (groups []*relation.Group, err error) {
2023-01-17 14:40:20 +08:00
for _, groupID := range groupIDs {
group, err := g.GetGroupInfoFromCache(ctx, groupID)
if err != nil {
return nil, err
}
groups = append(groups, group)
}
return groups, nil
}
2023-01-28 13:19:36 +08:00
func (g *GroupCache) GetGroupInfoFromCache(ctx context.Context, groupID string) (group *relation.Group, err error) {
2023-01-17 14:40:20 +08:00
getGroup := func() (string, error) {
groupInfo, err := g.db.Take(ctx, groupID)
if err != nil {
return "", utils.Wrap(err, "")
}
bytes, err := json.Marshal(groupInfo)
if err != nil {
return "", utils.Wrap(err, "")
}
return string(bytes), nil
}
2023-01-28 13:19:36 +08:00
group = &relation.Group{}
2023-01-17 14:40:20 +08:00
defer func() {
trace_log.SetCtxDebug(ctx, utils.GetFuncName(1), err, "groupID", groupID, "group", *group)
}()
2023-01-17 16:36:34 +08:00
groupStr, err := g.rcClient.Fetch(g.getGroupInfoCacheKey(groupID), g.expireTime, getGroup)
2023-01-17 14:40:20 +08:00
if err != nil {
return nil, utils.Wrap(err, "")
}
err = json.Unmarshal([]byte(groupStr), group)
return group, utils.Wrap(err, "")
}
func (g *GroupCache) DelGroupInfoFromCache(ctx context.Context, groupID string) (err error) {
defer func() {
trace_log.SetCtxDebug(ctx, utils.GetFuncName(1), err, "groupID", groupID)
}()
2023-01-17 16:36:34 +08:00
return g.rcClient.TagAsDeleted(g.getGroupInfoCacheKey(groupID))
}
func (g *GroupCache) DelGroupsInfoFromCache(ctx context.Context, groupIDs []string) error {
for _, groupID := range groupIDs {
if err := g.DelGroupInfoFromCache(ctx, groupID); err != nil {
return err
}
}
return nil
2023-01-17 14:40:20 +08:00
}
func (g *GroupCache) getGroupInfoCacheKey(groupID string) string {
return groupInfoCacheKey + groupID
}