client-go创建完资源后不是立刻更新本地缓存
klog.InitFlags(nil)
flag.Parse()
defer klog.Flush()
cfg, err := clientcmd.BuildConfigFromFlags("", "/root/.kube/config")
cfg.QPS = 10000
cfg.Burst = 20000
if err != nil {
klog.Fatalf("Error building kubeconfig: %s", err.Error())
}
kubeClient, err := kubernetes.NewForConfig(cfg)
if err != nil {
klog.Fatalf("Error building kubernetes clientset: %s", err.Error())
}
informerFactory := informers.NewSharedInformerFactoryWithOptions(kubeClient, 0)
defer informerFactory.Shutdown()
hasSynced := informerFactory.Core().V1().Namespaces().Informer().HasSynced
namespaceLister := informerFactory.Core().V1().Namespaces().Lister()
go informerFactory.Start(stopCh)
klog.Infof("begin to wait cache sync")
if ok := cache.WaitForCacheSync(stopCh, hasSynced); !ok {
klog.Fatalf("failed to wait for caches to sync")
}
klog.Infof("wait cache sync end")
var namespace corev1.Namespace
namespace.Name = "test"
if _, err := kubeClient.CoreV1().Namespaces().Create(context.Background(), &namespace, metav1.CreateOptions{}); err != nil {
klog.Errorf("create namespace test failed, err is %v", err)
} else {
klog.Infof("create namespace test success")
}
for i := 0; i < 100; i++ {
if _, err := namespaceLister.Get("test"); errors.IsNotFound(err) {
klog.Errorf("namespace test in lister not exist")
} else if err == nil {
klog.Infof("get namespace test from lister success")
break
}
time.Sleep(time.Millisecond)
}
等待22ms后本地缓存才有刚创建的namespace。