上一篇文章里,我们主要介绍了和资源索引相关的一系列对象,其中包括了 indexer 对象,index 对象,以及 indices 对象等等。在本篇文章里我们主要来介绍和对象存储相关的组件 ThreadSafeStore 接口以及其实现。
ThreadSafeStore 接口
ThreadSafeStore 是接口,图解和源码如下:
//k8s.io/client-go/tools/cache/thread_safe_store.go
type ThreadSafeStore interface {
Add(key string, obj interface{})
Update(key string, obj interface{})
Delete(key string)
Get(key string) (item interface{}, exists bool)
List() []interface{}
ListKeys() []string
Replace(map[string]interface{}, string)
Index(indexName string, obj interface{}) ([]interface{}, error)
IndexKeys(indexName, indexKey string) ([]string, error)
ListIndexFuncValues(name string) []string
ByIndex(indexName, indexKey string) ([]interface{}, error)
GetIndexers() Indexers
// AddIndexers adds more indexers to this store. If you call this after you already have data
// in the store, the results are undefined.
AddIndexers(newIndexers Indexers) error
// Resync is a no-op and is deprecated
Resync() error
}
该接口定义了对于资源增删改查的方法,例如 Add/Update/Delete/Get/List 等操作。
该接口定义了对于资源进行索引相关的方法,例如 Index/IndexKeys/ByIndex 等系列操作。
threadSafeMap 结构体
threadSafeMap 是一个结构体,该结构体实现了上面介绍的接口 ThreadSafeStore,其相关的图解和源码如下:
//k8s.io/client-go/tools/cache/thread_safe_store.go
type threadSafeMap struct {
lock sync.RWMutex
items map[string]interface{}
// indexers maps a name to an IndexFunc
indexers Indexers
// indices maps a name to an Index
indices Indices
}
func (c *threadSafeMap) Add(key string, obj interface{}) {
c.Update(key, obj)
}
func (c *threadSafeMap) Update(key string, obj interface{}){...}
func (c *threadSafeMap) Delete(key string) {...}
func (c *threadSafeMap) Get(key string) (item interface{}, exists bool){...}
func (c *threadSafeMap) List() []interface{...}
func (c *threadSafeMap) ListKeys() []string {...}
func (c *threadSafeMap) Replace(items map[string]interface{}, resourceVersion string) {...}
func (c *threadSafeMap) Index(indexName string, obj interface{}) ([]interface{}, error) {...} {...}
func (c *threadSafeMap) ByIndex(indexName, indexedValue string) ([]interface{}, error) {...}
func (c *threadSafeMap) IndexKeys(indexName, indexedValue string) ([]string, error) {...}
func (c *threadSafeMap) ListIndexFuncValues(indexName string) []string {...}
.......
该结构体中有名为 items 的 map 属性,其中存储了资源对象的 key 和资源对象本身。
该结构体中上一篇文章中介绍的 Indexer 对象,存储了相应的命名索引函数。
该结构体中上一篇文章中介绍的 Iidices 对象,存储了相应的命名索引。
该结构体实现了 ThreadSafeStore 接口中对于资源进行增删改查相关的方法,例如 Add/Update/Delete/Get/List 等等。
该结构体实现了 ThreadSafeStore 接口中对于资源进行索引操作相关的方法,例如 Index/IndexKeys/ByIndex 等等。
对于该结构体实现的方法都有 Mutex 锁操作,所以是并发安全的。
目前我们先写到这里,在下一篇文章中我们继续介绍 Store 组件。