mirror of
https://github.com/halejohn/Cloudreve.git
synced 2026-01-26 09:34:57 +08:00
Feat: cache in-memory store
This commit is contained in:
10
pkg/cache/driver.go
vendored
Normal file
10
pkg/cache/driver.go
vendored
Normal file
@@ -0,0 +1,10 @@
|
||||
package cache
|
||||
|
||||
// Store 缓存存储器
|
||||
var Store Driver = NewMemoStore()
|
||||
|
||||
// Driver 键值缓存存储容器
|
||||
type Driver interface {
|
||||
Set(key string, value interface{}) error
|
||||
Get(key string) (interface{}, bool)
|
||||
}
|
||||
26
pkg/cache/memo.go
vendored
Normal file
26
pkg/cache/memo.go
vendored
Normal file
@@ -0,0 +1,26 @@
|
||||
package cache
|
||||
|
||||
import "sync"
|
||||
|
||||
// MemoStore 内存存储驱动
|
||||
type MemoStore struct {
|
||||
Store *sync.Map
|
||||
}
|
||||
|
||||
// NewMemoStore 新建内存存储
|
||||
func NewMemoStore() *MemoStore {
|
||||
return &MemoStore{
|
||||
Store: &sync.Map{},
|
||||
}
|
||||
}
|
||||
|
||||
// Set 存储值
|
||||
func (store *MemoStore) Set(key string, value interface{}) error {
|
||||
store.Store.Store(key, value)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Get 取值
|
||||
func (store *MemoStore) Get(key string) (interface{}, bool) {
|
||||
return store.Store.Load(key)
|
||||
}
|
||||
61
pkg/cache/memo_test.go
vendored
Normal file
61
pkg/cache/memo_test.go
vendored
Normal file
@@ -0,0 +1,61 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"github.com/stretchr/testify/assert"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNewMemoStore(t *testing.T) {
|
||||
asserts := assert.New(t)
|
||||
|
||||
store := NewMemoStore()
|
||||
asserts.NotNil(store)
|
||||
asserts.NotNil(store.Store)
|
||||
}
|
||||
|
||||
func TestMemoStore_Set(t *testing.T) {
|
||||
asserts := assert.New(t)
|
||||
|
||||
store := NewMemoStore()
|
||||
err := store.Set("KEY", "vAL")
|
||||
asserts.NoError(err)
|
||||
|
||||
val, ok := store.Store.Load("KEY")
|
||||
asserts.True(ok)
|
||||
asserts.Equal("vAL", val)
|
||||
}
|
||||
|
||||
func TestMemoStore_Get(t *testing.T) {
|
||||
asserts := assert.New(t)
|
||||
store := NewMemoStore()
|
||||
|
||||
// 正常情况
|
||||
{
|
||||
_ = store.Set("string", "string_val")
|
||||
val, ok := store.Get("string")
|
||||
asserts.Equal("string_val", val)
|
||||
asserts.True(ok)
|
||||
}
|
||||
|
||||
// Key不存在
|
||||
{
|
||||
val, ok := store.Get("something")
|
||||
asserts.Equal(nil, val)
|
||||
asserts.False(ok)
|
||||
}
|
||||
|
||||
// 存储struct
|
||||
{
|
||||
type testStruct struct {
|
||||
key int
|
||||
}
|
||||
test := testStruct{key: 233}
|
||||
_ = store.Set("struct", test)
|
||||
val, ok := store.Get("struct")
|
||||
asserts.True(ok)
|
||||
res, ok := val.(testStruct)
|
||||
asserts.True(ok)
|
||||
asserts.Equal(test, res)
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user