When Should You Use watch.Interface, cache.NewInformer, or cache.NewSharedIndexInformer in Kubernetes?

Linda Hamilton
Release: 2024-11-11 19:56:03
Original
576 people have browsed it

When Should You Use watch.Interface, cache.NewInformer, or cache.NewSharedIndexInformer in Kubernetes?

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)
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template