fixup store cache#

This commit is contained in:
Asim Aslam 2020-04-11 12:10:19 +01:00
parent 3f81f685df
commit 51d4f737b8
2 changed files with 31 additions and 15 deletions

37
store/cache/cache.go vendored
View File

@ -5,21 +5,34 @@ import (
"fmt"
"github.com/micro/go-micro/v2/store"
"github.com/micro/go-micro/v2/store/memory"
"github.com/pkg/errors"
)
type cache struct {
stores []store.Store
options store.Options
}
// Cache is a cpu register style cache for the store.
// It syncs between N stores in a faulting manner.
type Cache interface {
// Implements the store interface
store.Store
}
// NewCache returns a new store using the underlying stores, which must be already Init()ialised
func NewCache(stores ...store.Store) store.Store {
c := &cache{}
c.stores = make([]store.Store, len(stores))
for i, s := range stores {
c.stores[i] = s
func NewCache(stores ...store.Store) Cache {
if len(stores) == 0 {
stores = []store.Store{
memory.NewStore(),
}
}
// TODO: build in an in memory cache
c := &cache{
stores: stores,
}
return c
}
@ -27,15 +40,19 @@ func (c *cache) Close() error {
return nil
}
func (c *cache) Init(...store.Option) error {
if len(c.stores) < 2 {
return errors.New("cache requires at least 2 stores")
func (c *cache) Init(opts ...store.Option) error {
// pass to the stores
for _, store := range c.stores {
if err := store.Init(opts...); err != nil {
return err
}
}
return nil
}
func (c *cache) Options() store.Options {
return c.options
// return from first store
return c.stores[0].Options()
}
func (c *cache) String() string {

View File

@ -15,13 +15,12 @@ func TestCache(t *testing.T) {
assert := assert.New(t)
nonCache := NewCache(l0)
assert.NotNil(nonCache.Init(), "Expected a cache initialised with just 1 store to fail")
nonCache := NewCache(nil)
assert.Equal(len(nonCache.(*cache).stores), 1, "Expected a cache initialised with just 1 store to fail")
// Basic functionality
cachedStore := NewCache(l0, l1, l2)
assert.Nil(cachedStore.Init(), "Init should not error")
assert.Equal(cachedStore.Options(), store.Options{}, "Options on store/cache are nonsensical")
assert.Equal(cachedStore.Options(), l0.Options(), "Options on store/cache are nonsensical")
expectedString := "cache [memory memory memory]"
assert.Equal(cachedStore.String(), expectedString, "Cache couldn't describe itself as expected")