工厂方法是一种创建型设计模式,详情可参考工厂方法
如何创建一个informer
1 | // 创建对应资源的informer |
工厂方法构造
1 | // 返回一个结构体sharedInformerFactory指针,该结构体实现了接口SharedInformerFactory |
factory.Core().V1().Pods().Informer()
1.首先调用Core()方法1
2
3
4
5
6
7
8
9
10
11
12
13// Core()返回结构体group指针,group实现了V1()方法
func (f *sharedInformerFactory) Core() core.Interface {
return core.New(f, f.namespace, f.tweakListOptions)
}
type group struct {
factory internalinterfaces.SharedInformerFactory
namespace string
tweakListOptions internalinterfaces.TweakListOptionsFunc
}
func (g *group) V1() v1.Interface {
return v1.New(g.factory, g.namespace, g.tweakListOptions)
}
2.调用V1()方法1
2
3
4
5
6
7
8
9
10// V1()返回结构体version的指针,version实现了v1.Interface中的所有方法
func (g *group) V1() v1.Interface {
return v1.New(g.factory, g.namespace, g.tweakListOptions)
}
type version struct {
factory internalinterfaces.SharedInformerFactory
namespace string
tweakListOptions internalinterfaces.TweakListOptionsFunc
}
4.调用Pods()方法1
2
3
4// 返回podInformer指针,podInformer实现了Informer(),Lister()方法
func (v *version) Pods() PodInformer {
return &podInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}
}
5.最后调用Informer()方法,完成对象创建1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29// 调用InformerFor
// staging/src/k8s.io/client-go/informers/core/v1/pod.go
func (f *podInformer) Informer() cache.SharedIndexInformer {
return f.factory.InformerFor(&corev1.Pod{}, f.defaultInformer)
}
// staging/src/k8s.io/client-go/informers/factory.go
func (f *sharedInformerFactory) InformerFor(obj runtime.Object, newFunc internalinterfaces.NewInformerFunc) cache.SharedIndexInformer {
f.lock.Lock()
defer f.lock.Unlock()
informerType := reflect.TypeOf(obj)
// 此处会检查informer是否存在,如果存在则直接返回
// 复用informer,节省资源
informer, exists := f.info设计模式rmers[informerType]
if exists {
return informer
}
resyncPeriod, exists := f.customResync[informerType]
if !exists {
resyncPeriod = f.defaultResync
}
informer = newFunc(f.client, resyncPeriod)
f.informers[informerType] = informer
return informer
}
REF:
1.client-go/informers/factory.go
2.client-go/informers/core/interface.go
3.client-go/informers/core/v1/interface.go
4.client-go/informers/core/v1/pod.go