-
Notifications
You must be signed in to change notification settings - Fork 0
/
read_through.go
54 lines (48 loc) · 1.31 KB
/
read_through.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package gcache
import (
"context"
"errors"
"fmt"
"golang.org/x/sync/singleflight"
"time"
)
var (
errFailedToRefreshCache = errors.New("gcache 刷新缓存失败")
)
type ReadTroughCache struct {
Cache
LoadFunc func(ctx context.Context, key string) (any, error) // 需要初始化
Expiration time.Duration // 过期时间
}
func (r *ReadTroughCache) Get(ctx context.Context, key string) (any, error) {
val, err := r.Cache.Get(ctx, key)
if err == errKeyNotFound { // 未找到
val, err = r.LoadFunc(ctx, key)
if err == nil {
errSet := r.Cache.Set(ctx, key, val, r.Expiration)
if errSet != nil {
return val, fmt.Errorf("%w, 原因: %s", errFailedToRefreshCache, errSet.Error())
}
}
}
return val, err
}
type ReadThroughCacheV1[T any] struct {
Cache
LoadFunc func(ctx context.Context, key string) (T, error)
Expiration time.Duration
g singleflight.Group
}
func (r *ReadThroughCacheV1[T]) Get(ctx context.Context, key string) (T, error) {
val, err := r.Cache.Get(ctx, key)
if err == errKeyNotFound {
val, err = r.LoadFunc(ctx, key)
if err == nil {
errSet := r.Cache.Set(ctx, key, val, r.Expiration)
if errSet != nil {
return val.(T), fmt.Errorf("%w, 原因: %s", errFailedToRefreshCache, errSet.Error())
}
}
}
return val.(T), err
}