package main import ( "context" "flag" "log" "path/filepath" "k8s.io/client-go/informers" "k8s.io/client-go/kubernetes" "k8s.io/client-go/tools/cache" "k8s.io/client-go/tools/clientcmd" "k8s.io/client-go/util/homedir" ) func main() { var kubeconfig string flag.StringVar(&kubeconfig, "kubeconfig", filepath.Join(homedir.HomeDir(), ".kube", "config"), "(optional) absolute path to the kubeconfig file") flag.Parse() // use the current context in kubeconfig config, err := clientcmd.BuildConfigFromFlags("", kubeconfig) if err != nil { log.Fatal(err) } ctx := context.Background() AddPod := func(obj interface{}) { } DeletePod := func(obj interface{}) { } UpdatePod := func(oldObj, newObj interface{}) { } clientset := kubernetes.NewForConfigOrDie(config) // 基于GVK 操作资源,假设需要操作数十种不同资源时,我们需要为每一种资源实现各自的函数 podInformer := informers.NewSharedInformerFactory(clientset, 0). Core().V1().Pods().Informer() podInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{ AddFunc: AddPod, DeleteFunc: DeletePod, UpdateFunc: UpdatePod, }) // 启动informer podInformer.Run(ctx.Done()) cache.WaitForCacheSync(ctx.Done(), podInformer.HasSynced) // 此处没有使用workqueue,但一般都是会用workqueue 增强处理逻辑的 }