bbgo_origin/pkg/service/memory.go

63 lines
1.1 KiB
Go
Raw Permalink Normal View History

package service
import (
"reflect"
"strings"
2023-03-05 14:20:14 +00:00
"sync"
)
type MemoryService struct {
Slots map[string]interface{}
}
func NewMemoryService() *MemoryService {
return &MemoryService{
Slots: make(map[string]interface{}),
}
}
2021-02-20 17:01:39 +00:00
func (s *MemoryService) NewStore(id string, subIDs ...string) Store {
key := strings.Join(append([]string{id}, subIDs...), ":")
return &MemoryStore{
Key: key,
memory: s,
}
}
type MemoryStore struct {
Key string
memory *MemoryService
2023-03-05 14:20:14 +00:00
mu sync.Mutex
}
func (store *MemoryStore) Save(val interface{}) error {
2023-03-05 14:20:14 +00:00
store.mu.Lock()
defer store.mu.Unlock()
store.memory.Slots[store.Key] = val
return nil
}
func (store *MemoryStore) Load(val interface{}) error {
2023-03-05 14:20:14 +00:00
store.mu.Lock()
defer store.mu.Unlock()
v := reflect.ValueOf(val)
if data, ok := store.memory.Slots[store.Key]; ok {
dataRV := reflect.ValueOf(data)
v.Elem().Set(dataRV)
} else {
return ErrPersistenceNotExists
}
return nil
}
func (store *MemoryStore) Reset() error {
2023-03-05 14:20:14 +00:00
store.mu.Lock()
defer store.mu.Unlock()
delete(store.memory.Slots, store.Key)
return nil
2023-05-25 06:01:22 +00:00
}