美文网首页
k8s之client-go informer使用

k8s之client-go informer使用

作者: wwq2020 | 来源:发表于2020-08-04 16:28 被阅读0次
    import (
        "fmt"
        "time"
    
        v1 "k8s.io/api/apps/v1"
        "k8s.io/apimachinery/pkg/labels"
        "k8s.io/client-go/informers"
        "k8s.io/client-go/kubernetes"
        "k8s.io/client-go/rest"
        "k8s.io/client-go/tools/cache"
    )
    
    func demo(config *rest.Config, namespace string) {
        clientset, err := kubernetes.NewForConfig(config)
        if err != nil {
            panic(err)
        }
    
        informerFactory := informers.NewSharedInformerFactory(clientset, time.Minute)
        informer := informerFactory.Apps().V1().Deployments()
        informer.Informer().AddEventHandler(
            cache.ResourceEventHandlerFuncs{
                AddFunc:    onAdd,
                UpdateFunc: onUpdate,
                DeleteFunc: onDelete,
            })
        lister := informer.Lister()
    
        stopCh := make(chan struct{})
        defer close(stopCh)
        informerFactory.Start(stopCh)
        if !cache.WaitForCacheSync(stopCh, informer.Informer().HasSynced) {
            return
        }
    
        deployments, err := lister.Deployments(namespace).List(labels.Everything())
        if err != nil {
            panic(err)
        }
        for _, deployment := range deployments {
            fmt.Printf("%s\r\n", deployment.Name)
        }
        <-stopCh
    }
    
    func onAdd(obj interface{}) {
        deployment := obj.(*v1.Deployment)
        fmt.Printf("onAdd:%s\r\n", deployment.Name)
    }
    
    func onUpdate(old, new interface{}) {
        oldDeployment := old.(*v1.Deployment)
        newDeployment := new.(*v1.Deployment)
        fmt.Printf("onUpdate:%s to %s\r\n", oldDeployment.Name, newDeployment.Name)
    }
    
    func onDelete(obj interface{}) {
        deployment := obj.(*v1.Deployment)
        fmt.Printf("onDelete:%s\r\n", deployment.Name)
    }
    
    

    相关文章

      网友评论

          本文标题:k8s之client-go informer使用

          本文链接:https://www.haomeiwen.com/subject/ywyvrktx.html