forked from k8s-club/k8s-club
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinformer_practice_test.go
49 lines (42 loc) · 1.42 KB
/
informer_practice_test.go
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package informer
import (
"K8s_demo/demo/examples/client"
"fmt"
v1 "k8s.io/api/core/v1"
"k8s.io/client-go/informers"
"k8s.io/client-go/tools/cache"
"testing"
)
func InformerPractice() {
client := client.ClientSet.Client
factory := informers.NewSharedInformerFactoryWithOptions(client, 0, informers.WithNamespace("default"))
// 不同informer可直接在 factory中同时监听。注意:需要创建eventHandler。
podInformer := factory.Core().V1().Pods().Informer()
//jobInformer := factory.Batch().V1().Jobs().Informer()
//serviceInformer := factory.Core().V1().Services().Informer()
//deploymentInformer := factory.Apps().V1().Deployments().Informer()
//statefulSetInformer := factory.Apps().V1().StatefulSets().Informer()
podInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
pod := obj.(*v1.Pod)
fmt.Println("add new pod:", pod.GetName())
},
UpdateFunc: func(oldObj, newObj interface{}) {
oldPod := oldObj.(*v1.Pod)
newPod := newObj.(*v1.Pod)
fmt.Printf("update old pod name:%s to new pod name:%s \n", oldPod.GetName(), newPod.GetName())
},
DeleteFunc: func(obj interface{}) {
pod := obj.(*v1.Pod)
fmt.Println("delete pod:", pod.GetName())
},
})
stopC := make(chan struct{})
defer close(stopC)
fmt.Println("------开始使用informer监听------------")
factory.Start(stopC)
<-stopC
}
func TestInformer(t *testing.T) {
InformerPractice()
}