FIX: add mutex in memory store

This commit is contained in:
gx578007 2023-03-05 22:20:14 +08:00
parent dfba758e88
commit a5e35b4711

View File

@ -3,6 +3,7 @@ package service
import (
"reflect"
"strings"
"sync"
)
type MemoryService struct {
@ -26,14 +27,21 @@ func (s *MemoryService) NewStore(id string, subIDs ...string) Store {
type MemoryStore struct {
Key string
memory *MemoryService
mu sync.Mutex
}
func (store *MemoryStore) Save(val interface{}) error {
store.mu.Lock()
defer store.mu.Unlock()
store.memory.Slots[store.Key] = val
return nil
}
func (store *MemoryStore) Load(val interface{}) error {
store.mu.Lock()
defer store.mu.Unlock()
v := reflect.ValueOf(val)
if data, ok := store.memory.Slots[store.Key]; ok {
dataRV := reflect.ValueOf(data)
@ -46,6 +54,9 @@ func (store *MemoryStore) Load(val interface{}) error {
}
func (store *MemoryStore) Reset() error {
store.mu.Lock()
defer store.mu.Unlock()
delete(store.memory.Slots, store.Key)
return nil
}
}