In Kubernetes, monitoring changes to services is crucial for maintaining application health. This article demonstrates how to implement event watching for Kubernetes services using the client-go library.
To start, establish a Kubernetes configuration by creating a config object using clientcmd.BuildConfigFromFlags():
import ( "k8s.io/client-go/tools/clientcmd" ) // ... config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig) if err != nil { panic(err.Error()) }
Use the configuration to create a new Kubernetes client:
import ( "k8s.io/client-go/kubernetes" ) // ... clientset, err := kubernetes.NewForConfig(config)
Create a watchlist representing the services you wish to monitor:
import ( "k8s.io/client-go/tools/cache" v1 "k8s.io/client-go/pkg/api/v1" ) // ... watchlist := cache.NewListWatchFromClient(clientset.Core().RESTClient(), "services", v1.NamespaceDefault, fields.Everything())
Establish an informer to handle incoming events:
informer := cache.NewInformer( watchlist, &v1.Service{}, time.Second * 0, cache.ResourceEventHandlerFuncs{ AddFunc: func(obj interface{}) { fmt.Printf("service added: %s \n", obj) }, DeleteFunc: func(obj interface{}) { fmt.Printf("service deleted: %s \n", obj) }, UpdateFunc: func(oldObj, newObj interface{}) { fmt.Printf("service changed \n") }, }, )
Run the informer to start monitoring for events:
stop := make(chan struct{}) go informer.Run(stop)
Keep the program running indefinitely to continue monitoring for service events:
for { time.Sleep(time.Second) }
The above is the detailed content of How to Use Go Client-go to Watch Kubernetes Service Events?. For more information, please follow other related articles on the PHP Chinese website!