You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Open-IM-Server/pkg/common/db/cache/black.go

70 lines
2.0 KiB

2 years ago
package cache
import (
"Open_IM/pkg/common/tracelog"
"Open_IM/pkg/utils"
"context"
"encoding/json"
"github.com/dtm-labs/rockscache"
2 years ago
"github.com/go-redis/redis/v8"
2 years ago
"time"
)
const (
blackIDsKey = "BLACK_IDS:"
blackExpireTime = time.Second * 60 * 60 * 12
)
2 years ago
type BlackCache interface {
//get blackIDs from cache
GetBlackIDs(ctx context.Context, userID string, fn func(ctx context.Context, userID string) ([]string, error)) (blackIDs []string, err error)
//del user's blackIDs cache, exec when a user's black list changed
DelBlackIDs(ctx context.Context, userID string) (err error)
}
type BlackCacheRedis struct {
2 years ago
expireTime time.Duration
rcClient *rockscache.Client
}
2 years ago
func NewBlackCacheRedis(rdb redis.UniversalClient, blackDB BlackCache, options rockscache.Options) *BlackCacheRedis {
return &BlackCacheRedis{
2 years ago
expireTime: blackExpireTime,
rcClient: rockscache.NewClient(rdb, options),
2 years ago
}
}
2 years ago
func (b *BlackCacheRedis) getBlackIDsKey(ownerUserID string) string {
2 years ago
return blackIDsKey + ownerUserID
}
2 years ago
func (b *BlackCacheRedis) GetBlackIDs(ctx context.Context, userID string) (blackIDs []string, err error) {
2 years ago
getBlackIDList := func() (string, error) {
blackIDs, err := b.blackDB.GetBlackIDs(ctx, userID)
if err != nil {
return "", utils.Wrap(err, "")
}
bytes, err := json.Marshal(blackIDs)
if err != nil {
return "", utils.Wrap(err, "")
}
return string(bytes), nil
}
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "userID", userID, "blackIDList", blackIDs)
}()
2 years ago
blackIDListStr, err := b.rcClient.Fetch(blackListCache+userID, b.expireTime, getBlackIDList)
2 years ago
if err != nil {
return nil, utils.Wrap(err, "")
}
err = json.Unmarshal([]byte(blackIDListStr), &blackIDs)
return blackIDs, utils.Wrap(err, "")
}
2 years ago
func (b *BlackCacheRedis) DelBlackIDs(ctx context.Context, userID string) (err error) {
2 years ago
defer func() {
2 years ago
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "userID", userID)
2 years ago
}()
return b.rcClient.TagAsDeleted(blackListCache + userID)
}