watch.Interface vs. cache.NewInformer vs. cache.NewSharedIndexInformer
When monitoring resources in Kubernetes and reacting to changes, developers have various options available to them. Understanding the differences between these methods is crucial.
watch.Interface
The watch.Interface obtained through methods like rest.Request.Watch() provides a ResultChan that streams events (Added/Modified/Deleted) of resource changes. It offers a low-level abstraction and provides only the "after" state of the resource.
cache.NewInformer
The cache.NewInformer function allows you to specify a ResourceEventHandler that handles OnAdd()/OnUpdate()/OnDelete() calls. It includes a mechanism to receive both the "before" and "after" states of the resource. Internally, NewInformer utilizes watch.Interface through NewListWatchFromClient.
cache.NewSharedInformer vs. cache.NewSharedIndexInformer
These functions provide higher levels of abstraction than NewInformer. They employ a shared connection to the API server and share resources among informers. cache.NewSharedIndexInformer additionally adds indexing to the data cache.
Recommendation
For most use cases, SharedInformers are recommended over lower-level abstractions. SharedInformers share resources and provide a higher level of abstraction, simplifying many lower-level tasks. When working with a large dataset, SharedIndexInformers are preferred due to their indexing capability.
Instantiate SharedInformers from the same SharedInformerFactory to share resources efficiently. An example is shown below:
informerFactory := informers.NewSharedInformerFactory(clientset, time.Second*30) podInformer := informerFactory.Core().V1().Pods() serviceInformer := informerFactory.Core().V1().Services() podInformer.Informer().AddEventHandler( // Add event handling ) // Add event handling for serviceInformer informerFactory.Start(wait.NeverStop) informerFactory.WaitForCacheSync(wait.NeverStop)
The above is the detailed content of When Should You Use watch.Interface, cache.NewInformer, or cache.NewSharedIndexInformer in Kubernetes?. For more information, please follow other related articles on the PHP Chinese website!