Merge pull request #1082 from c9s/bhwu/add-mutex-to-mem-store

FIX: add mutex in memory store
This commit is contained in:
Yo-An Lin 2023-03-05 23:22:56 +08:00 committed by GitHub
commit 958e49deb4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

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
}