forked from zeromicro/go-zero
-
Notifications
You must be signed in to change notification settings - Fork 0
/
immutableresource.go
77 lines (66 loc) · 1.67 KB
/
immutableresource.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package syncx
import (
"sync"
"time"
"github.com/tal-tech/go-zero/core/timex"
)
const defaultRefreshInterval = time.Second
type (
ImmutableResourceOption func(resource *ImmutableResource)
ImmutableResource struct {
fetch func() (interface{}, error)
resource interface{}
err error
lock sync.RWMutex
refreshInterval time.Duration
lastTime *AtomicDuration
}
)
func NewImmutableResource(fn func() (interface{}, error), opts ...ImmutableResourceOption) *ImmutableResource {
// cannot use executors.LessExecutor because of cycle imports
ir := ImmutableResource{
fetch: fn,
refreshInterval: defaultRefreshInterval,
lastTime: NewAtomicDuration(),
}
for _, opt := range opts {
opt(&ir)
}
return &ir
}
func (ir *ImmutableResource) Get() (interface{}, error) {
ir.lock.RLock()
resource := ir.resource
ir.lock.RUnlock()
if resource != nil {
return resource, nil
}
ir.maybeRefresh(func() {
res, err := ir.fetch()
ir.lock.Lock()
if err != nil {
ir.err = err
} else {
ir.resource, ir.err = res, nil
}
ir.lock.Unlock()
})
ir.lock.RLock()
resource, err := ir.resource, ir.err
ir.lock.RUnlock()
return resource, err
}
func (ir *ImmutableResource) maybeRefresh(execute func()) {
now := timex.Now()
lastTime := ir.lastTime.Load()
if lastTime == 0 || lastTime+ir.refreshInterval < now {
ir.lastTime.Set(now)
execute()
}
}
// Set interval to 0 to enforce refresh every time if not succeeded. default is time.Second.
func WithRefreshIntervalOnFailure(interval time.Duration) ImmutableResourceOption {
return func(resource *ImmutableResource) {
resource.refreshInterval = interval
}
}