Skip to content

Commit d5a9aff

Browse files
author
id
committed
feat(cache): add expiration for cache
1 parent d1b2e6c commit d5a9aff

1 file changed

Lines changed: 10 additions & 6 deletions

File tree

cache.go

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,20 +5,23 @@ import (
55
"github.com/go-redis/redis"
66
uuidgen "github.com/google/uuid"
77
"sync"
8+
"time"
89
)
910

1011
const SyncCacheGroupCapacity = 10
1112

1213
type SyncCacheOpts struct {
13-
Address string
14-
Password string
15-
Db int
16-
Redis Redis
14+
Address string
15+
Password string
16+
Db int
17+
Redis Redis
18+
Expiration time.Duration
1719
}
1820

1921
type SyncCacheClient struct {
2022
redis Redis
2123
cacheGroupManager *CacheGroupsManager
24+
expiration time.Duration
2225
}
2326

2427
type CacheGroupsManager struct {
@@ -32,6 +35,7 @@ func NewSyncCacheClient(opts SyncCacheOpts) *SyncCacheClient {
3235
cacheGroupManager: &CacheGroupsManager{
3336
cacheGroups: make(map[string]*CacheGroup, SyncCacheGroupCapacity),
3437
},
38+
expiration: opts.Expiration,
3539
}
3640

3741
if opts.Redis != nil {
@@ -76,7 +80,7 @@ func (c *SyncCacheClient) RemoveCacheGroup(cacheGroupName string) {
7680

7781
func (c *SyncCacheClient) Update(cacheGroupName, key string) {
7882
newUuid := uuidgen.New().String()
79-
c.redis.Set(cacheGroupName+"_"+key, newUuid, 0)
83+
c.redis.Set(cacheGroupName+"_"+key, newUuid, c.expiration)
8084
}
8185

8286
func (c *SyncCacheClient) RedisFlushDb() {
@@ -108,7 +112,7 @@ func (c *SyncCacheClient) Get(cacheGroupName, key string) (interface{}, error) {
108112

109113
// and to Redis
110114
newUuid := uuidgen.New().String()
111-
c.redis.Set(cacheGroupName+"_"+key, newUuid, 0)
115+
c.redis.Set(cacheGroupName+"_"+key, newUuid, c.expiration)
112116

113117
if err := c.cacheGroupManager.cacheGroups[cacheGroupName].getterFunc(key, setCacheFunc); err != nil {
114118
return nil, err

0 commit comments

Comments
 (0)