缓存调整

This commit is contained in:
xing 2023-01-20 18:43:11 +08:00
parent e780c358d7
commit cf6bf03d33
2 changed files with 71 additions and 2 deletions

7
cache/vars.go vendored
View File

@ -42,10 +42,13 @@ func (c *VarCache[T]) IsExpired() bool {
}
func (c *VarCache[T]) Flush() {
mu := c.v.Load().mutex
v := c.v.Load()
mu := v.mutex
mu.Lock()
defer mu.Unlock()
c.v.Delete()
var vv T
v.data = vv
c.v.Store(v)
}
func (c *VarCache[T]) GetCache(ctx context.Context, timeout time.Duration, params ...any) (T, error) {

66
cache/vars_test.go vendored Normal file
View File

@ -0,0 +1,66 @@
package cache
import (
"context"
"fmt"
"testing"
"time"
)
var cc = *NewVarCache(func(a ...any) (int, error) {
return 1, nil
}, time.Minute)
func TestVarCache_Flush(t *testing.T) {
type testCase[T any] struct {
name string
c VarCache[T]
}
tests := []testCase[int]{
{
name: "1",
c: cc,
},
}
c := context.Background()
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
fmt.Println(tt.c.GetCache(c, time.Second))
tt.c.Flush()
fmt.Println(tt.c.GetCache(c, time.Second))
})
}
}
func TestVarCache_IsExpired(t *testing.T) {
type testCase[T any] struct {
name string
c VarCache[T]
want bool
}
tests := []testCase[int]{
{
name: "expired",
c: cc,
want: true,
},
{
name: "not expired",
c: func() VarCache[int] {
v := *NewVarCache(func(a ...any) (int, error) {
return 1, nil
}, time.Minute)
_, _ = v.GetCache(context.Background(), time.Second)
return v
}(),
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := tt.c.IsExpired(); got != tt.want {
t.Errorf("IsExpired() = %v, want %v", got, tt.want)
}
})
}
}