上一篇文章里,我们主要介绍了和对象存储相关的组件 ThreadSafeStore 接口以及它的实现结构体 threadSafeMap,本质上来说该接口是并发安全的资源对象存储数据结构。在本篇文章里我们主要来介绍 Store 和 Indexer ,它们同样也是资源对象存储组件。
Store 接口
Store 是接口,图解和源码如下:
//k8s.io/client-go/tools/cache/store.go
type Store interface {
Add(obj interface{}) error
Update(obj interface{}) error
Delete(obj interface{}) error
List() []interface{}
ListKeys() []string
Get(obj interface{}) (item interface{}, exists bool, err error)
GetByKey(key string) (item interface{}, exists bool, err error)
Replace([]interface{}, string) error
Resync() error
}
Indexer 接口
Indexer 是接口,图解和源码如下:
//k8s.io/client-go/tools/cache/store.go
type Indexer interface {
Store
Index(indexName string, obj interface{}) ([]interface{}, error)
IndexKeys(indexName, indexedValue string) ([]string, error)
ListIndexFuncValues(indexName string) []string
ByIndex(indexName, indexedValue string) ([]interface{}, error)
GetIndexers() Indexers
AddIndexers(newIndexers Indexers) error
}
cache 结构体
cache 是一个结构体,该结构体实现了上面介绍的 Indexer 接口,其相关图解和源码如下:
//k8s.io/client-go/tools/cache/store.go
type KeyFunc func(obj interface{}) (string, error)
type cache struct {
cacheStorage ThreadSafeStore
keyFunc KeyFunc
}
func (c *cache) Add(obj interface{}) error {
key, err := c.keyFunc(obj)
if err != nil {
return KeyError{obj, err}
}
c.cacheStorage.Add(key, obj)
return nil
}
func (c *cache) Update(obj interface{}) error
func (c *cache) Delete(obj interface{}) error
func (c *cache) List() []interface{}
func (c *cache) ListKeys() []string
func (c *cache) GetIndexers() Indexers
func (c *cache) Index(indexName string, obj interface{}) ([]interface{}, error)
func (c *cache) IndexKeys(indexName, indexKey string) ([]string, error)
func (c *cache) ListIndexFuncValues(indexName string) []string
func (c *cache) ByIndex(indexName, indexKey string) ([]interface{}, error)
func (c *cache) AddIndexers(newIndexers Indexers) error
.......
cache 结构体的创建
cache 结构体创建的源码如下:
//k8s.io/client-go/tools/cache/store.go
func NewStore(keyFunc KeyFunc) Store {
return &cache{
cacheStorage: NewThreadSafeStore(Indexers{}, Indices{}),
keyFunc: keyFunc,
}
}
// NewIndexer returns an Indexer implemented simply with a map and a lock.
func NewIndexer(keyFunc KeyFunc, indexers Indexers) Indexer {
return &cache{
cacheStorage: NewThreadSafeStore(indexers, Indices{}),
keyFunc: keyFunc,
}
}
目前我们先写到这里,在下一篇文章中我们继续介绍 Queue 组件以及 DeltaFIFO 组件。