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

39
store/cache/cache.go vendored
View File

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

View File

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