feature add singleflight cache (#5119)
This commit is contained in:
18
client/cache/error_code.go
vendored
18
client/cache/error_code.go
vendored
@@ -123,6 +123,15 @@ var InvalidSsdbCacheValue = berror.DefineCode(4002022, moduleName, "InvalidSsdbC
|
||||
SSDB cache only accept string value. Please check your input.
|
||||
`)
|
||||
|
||||
var InvalidLoadFunc = berror.DefineCode(4002023, moduleName, "InvalidLoadFunc", `
|
||||
Invalid load function for read-through pattern decorator.
|
||||
You should pass a valid(non-nil) load function when initiate the decorator instance.
|
||||
`)
|
||||
|
||||
var LoadFuncFailed = berror.DefineCode(4002024, moduleName, "LoadFuncFailed", `
|
||||
Failed to load data, please check whether the loadfunc is correct
|
||||
`)
|
||||
|
||||
var InvalidInitParameters = berror.DefineCode(4002025, moduleName, "InvalidInitParameters", `
|
||||
Invalid init cache parameters.
|
||||
You can check the related function to confirm that if you pass correct parameters or configure to initiate a Cache instance.
|
||||
@@ -133,15 +142,6 @@ Failed to execute the StoreFunc.
|
||||
Please check the log to make sure the StoreFunc works for the specific key and value.
|
||||
`)
|
||||
|
||||
var InvalidLoadFunc = berror.DefineCode(4002023, moduleName, "InvalidLoadFunc", `
|
||||
Invalid load function for read-through pattern decorator.
|
||||
You should pass a valid(non-nil) load function when initiate the decorator instance.
|
||||
`)
|
||||
|
||||
var LoadFuncFailed = berror.DefineCode(4002024, moduleName, "InvalidLoadFunc", `
|
||||
Failed to load data, please check whether the loadfunc is correct
|
||||
`)
|
||||
|
||||
var DeleteFileCacheItemFailed = berror.DefineCode(5002001, moduleName, "DeleteFileCacheItemFailed", `
|
||||
Beego try to delete file cache item failed.
|
||||
Please check whether Beego generated file correctly.
|
||||
|
||||
63
client/cache/singleflight.go
vendored
Normal file
63
client/cache/singleflight.go
vendored
Normal file
@@ -0,0 +1,63 @@
|
||||
// Copyright 2014 beego Author. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/beego/beego/v2/core/berror"
|
||||
"golang.org/x/sync/singleflight"
|
||||
)
|
||||
|
||||
// SingleflightCache
|
||||
// This is a very simple decorator mode
|
||||
type SingleflightCache struct {
|
||||
Cache
|
||||
group *singleflight.Group
|
||||
expiration time.Duration
|
||||
loadFunc func(ctx context.Context, key string) (any, error)
|
||||
}
|
||||
|
||||
// NewSingleflightCache create SingleflightCache
|
||||
func NewSingleflightCache(c Cache, expiration time.Duration,
|
||||
loadFunc func(ctx context.Context, key string) (any, error),
|
||||
) (Cache, error) {
|
||||
if loadFunc == nil {
|
||||
return nil, berror.Error(InvalidLoadFunc, "loadFunc cannot be nil")
|
||||
}
|
||||
return &SingleflightCache{
|
||||
Cache: c,
|
||||
group: &singleflight.Group{},
|
||||
expiration: expiration,
|
||||
loadFunc: loadFunc,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Get In the Get method, single flight is used to load data and write back the cache.
|
||||
func (s *SingleflightCache) Get(ctx context.Context, key string) (any, error) {
|
||||
val, err := s.Cache.Get(ctx, key)
|
||||
if val == nil || err != nil {
|
||||
val, err, _ = s.group.Do(key, func() (interface{}, error) {
|
||||
v, er := s.loadFunc(ctx, key)
|
||||
if er != nil {
|
||||
return nil, berror.Wrap(er, LoadFuncFailed, "cache unable to load data")
|
||||
}
|
||||
er = s.Cache.Put(ctx, key, v, s.expiration)
|
||||
return v, er
|
||||
})
|
||||
}
|
||||
return val, err
|
||||
}
|
||||
72
client/cache/singleflight_test.go
vendored
Normal file
72
client/cache/singleflight_test.go
vendored
Normal file
@@ -0,0 +1,72 @@
|
||||
// Copyright 2014 beego Author. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestSingleflight_Memory_Get(t *testing.T) {
|
||||
bm, err := NewCache("memory", `{"interval":20}`)
|
||||
assert.Nil(t, err)
|
||||
|
||||
testSingleflightCacheConcurrencyGet(t, bm)
|
||||
}
|
||||
|
||||
func TestSingleflight_file_Get(t *testing.T) {
|
||||
fc := NewFileCache().(*FileCache)
|
||||
fc.CachePath = "////aaa"
|
||||
err := fc.Init()
|
||||
assert.NotNil(t, err)
|
||||
fc.CachePath = getTestCacheFilePath()
|
||||
err = fc.Init()
|
||||
assert.Nil(t, err)
|
||||
|
||||
testSingleflightCacheConcurrencyGet(t, fc)
|
||||
}
|
||||
|
||||
func testSingleflightCacheConcurrencyGet(t *testing.T, bm Cache) {
|
||||
key, value := "key3", "value3"
|
||||
db := &MockOrm{keysMap: map[string]int{key: 1}, kvs: map[string]any{key: value}}
|
||||
c, err := NewSingleflightCache(bm, 10*time.Second,
|
||||
func(ctx context.Context, key string) (any, error) {
|
||||
val, er := db.Load(key)
|
||||
if er != nil {
|
||||
return nil, er
|
||||
}
|
||||
return val, nil
|
||||
})
|
||||
assert.Nil(t, err)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(10)
|
||||
for i := 0; i < 10; i++ {
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
val, err := c.Get(context.Background(), key)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
assert.Equal(t, value, val)
|
||||
}()
|
||||
time.Sleep(1 * time.Millisecond)
|
||||
}
|
||||
wg.Wait()
|
||||
}
|
||||
2
client/cache/write_through_test.go
vendored
2
client/cache/write_through_test.go
vendored
@@ -27,7 +27,7 @@ import (
|
||||
)
|
||||
|
||||
func TestWriteThoughCache_Set(t *testing.T) {
|
||||
var mockDbStore = make(map[string]any)
|
||||
mockDbStore := make(map[string]any)
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
|
||||
Reference in New Issue
Block a user