micro/store/memory/memory.go

130 lines
2.0 KiB
Go
Raw Normal View History

2019-06-12 09:46:20 +03:00
// Package memory is a in-memory store store
2019-06-11 19:49:34 +03:00
package memory
import (
"sync"
"time"
"github.com/micro/go-micro/store"
2019-06-11 19:49:34 +03:00
)
2019-06-12 09:46:20 +03:00
type memoryStore struct {
2019-12-16 17:38:51 +03:00
options store.Options
2019-06-11 19:49:34 +03:00
sync.RWMutex
values map[string]*memoryRecord
}
type memoryRecord struct {
2019-06-12 09:46:20 +03:00
r *store.Record
2019-06-11 19:49:34 +03:00
c time.Time
}
func (m *memoryStore) Init(opts ...store.Option) error {
for _, o := range opts {
o(&m.options)
}
return nil
}
2019-10-24 00:05:39 +03:00
func (m *memoryStore) List() ([]*store.Record, error) {
2019-06-11 19:49:34 +03:00
m.RLock()
defer m.RUnlock()
//nolint:prealloc
2019-06-12 09:46:20 +03:00
var values []*store.Record
2019-06-11 19:49:34 +03:00
for _, v := range m.values {
// get expiry
d := v.r.Expiry
t := time.Since(v.c)
2019-07-11 07:58:20 +03:00
if d > time.Duration(0) {
2019-07-11 09:13:58 +03:00
// expired
if t > d {
continue
}
// update expiry
2019-07-11 07:58:20 +03:00
v.r.Expiry -= t
v.c = time.Now()
}
2019-06-11 19:49:34 +03:00
values = append(values, v.r)
}
return values, nil
}
2019-10-11 16:08:50 +03:00
func (m *memoryStore) Read(keys ...string) ([]*store.Record, error) {
2019-06-11 19:49:34 +03:00
m.RLock()
defer m.RUnlock()
//nolint:prealloc
2019-10-11 16:08:50 +03:00
var records []*store.Record
2019-06-11 19:49:34 +03:00
2019-10-11 16:08:50 +03:00
for _, key := range keys {
v, ok := m.values[key]
if !ok {
2019-07-11 09:13:58 +03:00
return nil, store.ErrNotFound
}
2019-10-11 16:08:50 +03:00
// get expiry
d := v.r.Expiry
t := time.Since(v.c)
// expired
if d > time.Duration(0) {
if t > d {
return nil, store.ErrNotFound
}
// update expiry
v.r.Expiry -= t
v.c = time.Now()
}
records = append(records, v.r)
2019-07-11 07:58:20 +03:00
}
2019-10-11 16:08:50 +03:00
return records, nil
2019-06-11 19:49:34 +03:00
}
2019-10-11 16:08:50 +03:00
func (m *memoryStore) Write(records ...*store.Record) error {
2019-06-11 19:49:34 +03:00
m.Lock()
defer m.Unlock()
2019-10-11 16:08:50 +03:00
for _, r := range records {
// set the record
m.values[r.Key] = &memoryRecord{
r: r,
c: time.Now(),
}
2019-06-11 19:49:34 +03:00
}
return nil
}
2019-10-11 16:08:50 +03:00
func (m *memoryStore) Delete(keys ...string) error {
2019-06-11 19:49:34 +03:00
m.Lock()
defer m.Unlock()
2019-10-11 16:08:50 +03:00
for _, key := range keys {
// delete the value
delete(m.values, key)
}
2019-06-11 19:49:34 +03:00
return nil
}
2019-06-12 09:46:20 +03:00
// NewStore returns a new store.Store
2019-12-16 17:38:51 +03:00
func NewStore(opts ...store.Option) store.Store {
var options store.Options
for _, o := range opts {
o(&options)
}
2019-06-11 19:49:34 +03:00
2019-06-12 09:46:20 +03:00
return &memoryStore{
2019-12-16 17:38:51 +03:00
options: options,
2019-06-11 19:49:34 +03:00
values: make(map[string]*memoryRecord),
}
}