Skip to content

Commit

Permalink
能指定缓存时间的上下偏差
Browse files Browse the repository at this point in the history
  • Loading branch information
zhanglp0129 committed Sep 26, 2024
1 parent 89b766e commit 1301e63
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 8 deletions.
7 changes: 4 additions & 3 deletions cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ type QueryFunc[T any] func() (T, error)
func QueryWithCache[T any](rdb redis.UniversalClient, key string, model *T, query QueryFunc[*T], options ...Option) (bool, error) {
// 获取缓存配置
config := CacheConfig{
cacheTime: getDefaultCacheTime(),
cacheTime: DefaultCacheTime,
diff: DefaultCacheTimeDiff,
ctx: context.Background(),
flush: false,
write: true,
Expand All @@ -36,7 +37,7 @@ func QueryWithCache[T any](rdb redis.UniversalClient, key string, model *T, quer

// 刷新缓存时间
if config.flush {
return true, rdb.Expire(config.ctx, key, config.cacheTime).Err()
return true, rdb.Expire(config.ctx, key, computeCacheTime(config.cacheTime, config.diff)).Err()
}
return true, nil
} else if errors.Is(err, redis.Nil) {
Expand Down Expand Up @@ -66,5 +67,5 @@ func cacheMiss[T any](rdb redis.UniversalClient, key string, model *T, query Que
return err
}

return rdb.SetEx(config.ctx, key, string(data), config.cacheTime).Err()
return rdb.SetEx(config.ctx, key, string(data), computeCacheTime(config.cacheTime, config.diff)).Err()
}
17 changes: 12 additions & 5 deletions option.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,26 +15,33 @@ var (

type CacheConfig struct {
cacheTime time.Duration
diff time.Duration
ctx context.Context
flush bool
write bool
}

// 获取默认缓存时间,默认为 [25, 35) min
func getDefaultCacheTime() time.Duration {
diff := time.Duration(rand.Int63()%int64(2*DefaultCacheTimeDiff)) - DefaultCacheTimeDiff
return max(0, DefaultCacheTime+diff)
// 计算缓存时间,默认为 [25, 35) min
func computeCacheTime(cacheTime time.Duration, diff time.Duration) time.Duration {
return max(0, cacheTime+time.Duration(rand.Int63()%int64(2*diff))-diff)
}

type Option func(c *CacheConfig)

// WithCacheTime 指定缓存时间,默认为 [25, 35) min
// WithCacheTime 指定缓存时间,默认为 30 min
func WithCacheTime(cacheTime time.Duration) Option {
return func(c *CacheConfig) {
c.cacheTime = cacheTime
}
}

// WithCacheTimeDiff 指定缓存时间上下偏差,默认为 5 min
func WithCacheTimeDiff(diff time.Duration) Option {
return func(c *CacheConfig) {
c.diff = diff
}
}

// WithContext 指定使用redis时的context,默认为background
func WithContext(ctx context.Context) Option {
return func(c *CacheConfig) {
Expand Down

0 comments on commit 1301e63

Please sign in to comment.