-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathristretto.go
More file actions
74 lines (65 loc) · 1.44 KB
/
ristretto.go
File metadata and controls
74 lines (65 loc) · 1.44 KB
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package hybrid
import (
"context"
"fmt"
"time"
"github.com/dgraph-io/ristretto"
)
type ristrettoCache[T any] struct {
cache *ristretto.Cache
cost int64
ttl time.Duration
opt *Option
}
// Set 实现接口
func (r *ristrettoCache[T]) Set(ctx context.Context, key string, val T, isEmpty bool) error {
ttl := r.ttl
if isEmpty {
if !r.opt.Empty {
return nil
}
if r.opt.EmptyTtl > 0 {
ttl = r.opt.EmptyTtl
}
}
if !r.cache.SetWithTTL(r.key(key), val, r.cost, ttl) {
return fmt.Errorf("ristretto could not set key %s", key)
}
return nil
}
// Get 实现接口
func (r *ristrettoCache[T]) Get(ctx context.Context, key string) (T, error) {
v, ok := r.cache.Get(r.key(key))
if !ok {
return *new(T), NotFindCache
}
if t, ok2 := v.(T); ok2 {
return t, nil
}
t := *new(T)
return t, fmt.Errorf("ristretto find key %s but [%T] is not [%T]", key, v, t)
}
// Del 实现接口
func (r *ristrettoCache[T]) Del(ctx context.Context, key string) error {
r.cache.Del(r.key(key))
return nil
}
func (r *ristrettoCache[T]) key(key string) string {
if r.opt.Prefix != "" {
return fmt.Sprintf("[%s]%s", r.opt.Prefix, key)
}
return key
}
// WithRistretto 使用ristretto本地缓存
func WithRistretto[T any](cache *ristretto.Cache, cost int64, ttl time.Duration, opts ...Options) Cache[T] {
opt := &Option{}
for _, optFn := range opts {
optFn(opt)
}
return &ristrettoCache[T]{
cache: cache,
cost: cost,
ttl: ttl,
opt: opt,
}
}