Go-Kubernetes-Client-go编程从Pod管理到CRD开发

Go-Kubernetes-Client-go编程从Pod管理到CRD开发

文章导语

Client-go是Kubernetes官方的Go客户端库,用于与K8s API Server交互。本文深入Client-go的核心组件:Informer、WorkQueue、Lister,实现从基础CRUD到自定义Controller。

一、Client-go基础操作

go 复制代码
func NewClientSet() (*kubernetes.Clientset, error) {
    config, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
    if err != nil {
        return nil, err
    }
    return kubernetes.NewForConfig(config)
}

// List Pods
func ListPods(clientset *kubernetes.Clientset, namespace string) {
    pods, err := clientset.CoreV1().Pods(namespace).List(context.TODO(), metav1.ListOptions{})
    for _, pod := range pods.Items {
        fmt.Printf("Pod: %s, Status: %s\n", pod.Name, pod.Status.Phase)
    }
}

二、Informer机制

go 复制代码
func WatchPods(clientset *kubernetes.Clientset) {
    factory := informers.NewSharedInformerFactory(clientset, 30*time.Second)
    podInformer := factory.Core().V1().Pods()
    
    podInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
        AddFunc: func(obj interface{}) {
            pod := obj.(*corev1.Pod)
            fmt.Printf("Pod Added: %s\n", pod.Name)
        },
        UpdateFunc: func(oldObj, newObj interface{}) {
            fmt.Println("Pod Updated")
        },
        DeleteFunc: func(obj interface{}) {
            fmt.Println("Pod Deleted")
        },
    })
    
    stopCh := make(chan struct{})
    defer close(stopCh)
    factory.Start(stopCh)
    factory.WaitForCacheSync(stopCh)
    <-stopCh
}

三、全文总结

  1. Client-go是K8s生态的核心Go库
  2. Informer实现本地缓存+事件通知
  3. WorkQueue限流+去重处理事件
  4. CRD+Controller扩展K8s能力

参考文献

  1. Client-go官方文档
  2. K8s Sample Controller
  3. Kubebuilder框架文档
相关推荐
紧跟先前的步伐1 天前
Go AI Agent 实战 06|JSON 结构化输出与 Go 后端校验
人工智能·ai·golang
紧跟先前的步伐2 天前
Go AI Agent 实战 08|HTTP 模型 API 的工作原理与请求流程
人工智能·http·ai·golang
紧跟先前的步伐2 天前
Go AI Agent 实战 07|模型幻觉、能力边界与成本控制
大数据·人工智能·golang
利威尔xu2 天前
Go GMP 调度器 10 个高频追问:3 个线上故障让 P99 从 80ms 飙到 2s、10 万 goroutine 泄漏
开发语言·后端·面试·性能优化·golang
FfHUCisI2 天前
无锁 Reactor 网络模型与 gnet / evio 架构拆解
服务器·开发语言·后端·golang
紧跟先前的步伐2 天前
Go AI Agent 实战 05|Temperature 与生成参数:让模型输出可控
java·人工智能·golang
浮尘笔记3 天前
我用 Go 写了个手机端「远程 AI 开发控制台」(开源)
人工智能·智能手机·golang
microrain3 天前
专业版守核心,企业版做增量:SagooIoT 的跨模块能力出口
物联网·架构·golang·sagooiot
紧跟先前的步伐3 天前
Go AI Agent 实战 04|Prompt 与消息角色:System、User、Assistant
人工智能·golang·prompt
念何架构之路3 天前
go-grpc逻辑架构图
开发语言·后端·golang