dashboard/pkg/dadis/dadis.go

79 lines
1.2 KiB
Go

package dadis
import (
"context"
"dashboard/pkg/observe"
"sync"
"time"
)
type Dadis struct {
mu sync.Mutex
store map[string]*item
observe *observe.AsyncEventBus
}
type item struct {
value interface{}
expire int64
}
func NewDadis() *Dadis {
return &Dadis{
store: make(map[string]*item),
observe: observe.NewAsyncEventBus(),
}
}
func (d *Dadis) Set(key string, value interface{}, expire time.Duration) {
d.mu.Lock()
defer d.mu.Unlock()
var exp int64
if expire != 0 {
exp = time.Now().Add(expire).UnixNano()
}
d.store[key] = &item{
value: value,
expire: exp,
}
e := &observe.Event{
Key: key,
Value: value,
}
_ = d.observe.Publish(context.Background(), e)
}
func (d *Dadis) Get(key string) (interface{}, bool) {
d.mu.Lock()
defer d.mu.Unlock()
if item, ok := d.store[key]; ok {
if item.expire != 0 && (time.Now().UnixNano() > item.expire) {
delete(d.store, key)
return nil, false
}
return item.value, true
}
return nil, false
}
func (d *Dadis) Sub(key string, ob observe.Observer) {
d.mu.Lock()
defer d.mu.Unlock()
d.observe.Subscribe(key, ob)
}
func (d *Dadis) Del(key string) {
d.mu.Lock()
defer d.mu.Unlock()
delete(d.store, key)
}