缓存支持读取缓存key的剩余有效时间

This commit is contained in:
2024-10-09 18:30:12 +08:00
parent 225a1ae9b2
commit 9088f515d3
5 changed files with 52 additions and 6 deletions

View File

@ -32,6 +32,24 @@ func (g *Gocache) Exist(ctx context.Context, cacheInstanceFlag string, key strin
return exist, nil
}
func (g *Gocache) TTL(ctx context.Context, cacheInstanceFlag string, key string) (int64, error) {
var (
exist bool
expireAt time.Time
)
_, expireAt, exist = GocacheStorageClient.Get(cacheInstanceFlag).GetWithExpiration(key)
if !exist {
// 和redis key不存在返回值一致
return -2, nil
}
if expireAt.Unix() == 0 {
// 存在并且未设置过期时间, 和redis key返回值一致
return -1, nil
}
return expireAt.Unix() - time.Now().Unix(), nil
}
func (g *Gocache) Set(ctx context.Context, cacheInstanceFlag string, key string, value string, ttl int64) error {
now := time.Now()
if now.Unix() < ttl {