package main
import (
"context"
"test/signals"
"time"
core_v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/discovery"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
klog "k8s.io/klog/v2"
)
func addListWatchCfgAndClient(stopCh <-chan struct{}) {
cfg1, err := clientcmd.BuildConfigFromFlags("", "/root/.kube/config")
if err != nil {
klog.Fatalf("Error building kubeconfig: %s", err.Error())
}
kubeClient, err := kubernetes.NewForConfig(cfg1)
if err != nil {
klog.Fatalf("Error building kubernetes clientset: %v", err)
}
cfg2, err := clientcmd.BuildConfigFromFlags("", "/root/.kube/config")
if err != nil {
klog.Fatalf("Error building kubeconfig: %s", err.Error())
}
discoveryClient, err := discovery.NewDiscoveryClientForConfig(cfg2)
if err != nil {
klog.Fatalf("Error building kubernetes discoveryclient: %v", err)
}
_, err = discoveryClient.ServerResourcesForGroupVersion("v1")
if err != nil {
klog.Errorf("get groups and resources failed")
} else {
klog.Infof("get groups and resources ok")
}
ns := &core_v1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: "test",
},
}
if _, err := kubeClient.CoreV1().Namespaces().Create(context.Background(), ns, metav1.CreateOptions{}); err != nil {
klog.Infof("create ns test failed, err is %v", err)
} else {
klog.Infof("create ns test success")
}
select {
case <-stopCh:
return
case <-time.After(time.Hour):
}
}
func main() {
stopCh := signals.SetupSignalHandler()
addListWatchCfgAndClient(stopCh)
}
基于相同kubeconfig路径,创建2个不同kubeconfig对象,对应启动2个不同client,最后只有1条长连接。
标签:DiscoveryClient,连接数,v1,client,io,go,k8s From: https://www.cnblogs.com/WJQ2017/p/18508605