Introduction
When monitoring Kubernetes resources and reacting to changes, developers can choose from various options in the Kubernetes client-go package. This article aims to clarify the differences between watch.Interface, cache.NewInformer, cache.NewSharedInformer, and cache.NewSharedIndexInformer.
watch.Interface
watch.Interface is a low-level abstraction that allows you to monitor changes to Kubernetes resources through a ResultChan(). It provides Added/Modified/Deleted events, giving you visibility into resource changes. However, it only includes the "after" state of the resource.
cache.NewInformer
cache.NewInformer introduces a higher level of abstraction. It includes a watcher, lister, and in-memory cache. By implementing a cache.ResourceEventHandler, you can receive OnAdd()/OnUpdate()/OnDelete() calls. This provides you with both the "before" and "after" states of the resource, making it more convenient for change handling.
cache.NewSharedInformer
cache.NewSharedInformer shares the connection with the API server and other resources between your informers. This optimizes resource usage and improves performance. It is recommended over cache.NewInformer unless you have specific requirements for isolation.
cache.NewSharedIndexInformer
cache.NewSharedIndexInformer adds an index to the data cache. This is particularly useful if you are working with a large dataset and need efficient indexing for quick lookup and filtering. It is the most feature-rich option but also the most complex to implement.
Recommendation
In most use cases, it is recommended to use SharedInformers instead of the lower level abstractions. SharedInformers provide performance benefits and simplify resource management. Instantiate new SharedInformers from the same SharedInformerFactory for optimal resource use.
The above is the detailed content of When to Use watch.Interface, cache.NewInformer, cache.NewSharedInformer, and cache.NewSharedIndexInformer?. For more information, please follow other related articles on the PHP Chinese website!