k8s怎么监听自定义资源的变更?(2)

上一篇当生成下面代码之后怎么去使用呢?
image.png

1.生成crd文件

这里我们通过kubebuilder的一个子项目 controller-gen 来生成crd文件
https://github.com/kubernetes-sigs/controller-tools

curl -L -o https://github.com/kubernetes-sigs/controller-tools;
go install controller-tools/cmd/controller-gen;
controller-gen crd paths=./pkg/apis/... output:crd:dir=config/crd

image.png
可以看到已经生成成功了。

apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  annotations:
    controller-gen.kubebuilder.io/version: (devel)
  name: foos.core.bigbird0101
spec:
  group: core.bigbird0101
  names:
    kind: Foo
    listKind: FooList
    plural: foos
    singular: foo
  scope: Namespaced
  versions:
  - name: v1
    schema:
      openAPIV3Schema:
        description: Foo is a specification for a Foo resource
        properties:
          apiVersion:
            description: |-
              APIVersion defines the versioned schema of this representation of an object.
              Servers should convert recognized schemas to the latest internal value, and
              may reject unrecognized values.
              More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
            type: string
          kind:
            description: |-
              Kind is a string value representing the REST resource this object represents.
              Servers may infer this from the endpoint the client submits requests to.
              Cannot be updated.
              In CamelCase.
              More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
            type: string
          metadata:
            type: object
          spec:
            description: FooSpec is the spec for a Foo resource
            properties:
              deploymentName:
                type: string
              replicas:
                format: int32
                type: integer
            required:
            - deploymentName
            - replicas
            type: object
          status:
            description: FooStatus is the status for a Foo resource
            properties:
              availableReplicas:
                format: int32
                type: integer
            required:
            - availableReplicas
            type: object
        required:
        - spec
        - status
        type: object
    served: true
    storage: true

在 k8s当中执行一下这个yaml,可以看到已经成功
image.png

apiVersion: core.bigbird0101/v1
kind: Foo
metadata:
  name: test-foo
spec:
    deploymentName: "test-foo"
    replicas: 1
status:     
    availableReplicas: 1

再去执行 可以看到已经成功
image.png

2.写监听代码

package main

import (
	v1 "bigbird0101/crd-test/pkg/apis/core/v1"
	"bigbird0101/crd-test/pkg/generated/clientset/versioned"
	"bigbird0101/crd-test/pkg/generated/informers/externalversions"
	"context"
	"fmt"
	"k8s.io/client-go/tools/cache"
	"k8s.io/client-go/tools/clientcmd"
)

func main() {
	flags, _ := clientcmd.BuildConfigFromFlags("", clientcmd.RecommendedHomeFile)
	client, _ := versioned.NewForConfig(flags)
	factory := externalversions.NewSharedInformerFactoryWithOptions(client, 0,externalversions.WithNamespace("default"))
	informer := factory.Core().V1().Foos().Informer()
	_, err := informer.AddEventHandler(cache.ResourceEventHandlerFuncs{
		AddFunc: func(obj interface{}) {
			foo := obj.(*v1.Foo)
			fmt.Printf("foo added: %v\n", foo)
		},
		UpdateFunc: func(oldObj, newObj interface{}) {
			foo := oldObj.(*v1.Foo)
			fmt.Printf("foo UpdateFunc: %v\n", foo)
			foo2 := newObj.(*v1.Foo)
			fmt.Printf("foo UpdateFunc: %v\n", foo2)
		},
		DeleteFunc: func(obj interface{}) {
			foo := obj.(*v1.Foo)
			fmt.Printf("foo Deleted: %v\n", foo)
		},
	})
	if err != nil {
		fmt.Println(err)
		return
	}
	informer.Run(context.Background().Done())
}

可以代码测试
删除资源和创建资源 可以看到都收到了通知
image.png
image.png

相关推荐

  1. K8s: Kubernetes扩展之定义资源

    2024-06-06 11:38:02       7 阅读
  2. k8s配置资源管理

    2024-06-06 11:38:02       25 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-06-06 11:38:02       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-06-06 11:38:02       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-06-06 11:38:02       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-06-06 11:38:02       20 阅读

热门阅读

  1. 前端想学习后端需要下载那些东西

    2024-06-06 11:38:02       7 阅读
  2. Python Spark环境:深度解析与高效搭建指南

    2024-06-06 11:38:02       6 阅读
  3. Linux 程序守护脚本

    2024-06-06 11:38:02       6 阅读
  4. C#-for循环语句

    2024-06-06 11:38:02       8 阅读
  5. 2024速通python之python面向对象

    2024-06-06 11:38:02       8 阅读
  6. zigbee浅谈

    2024-06-06 11:38:02       6 阅读
  7. Leetcode373.查找和最小的 K 对数字

    2024-06-06 11:38:02       6 阅读
  8. oracle的bitmap索引是什么

    2024-06-06 11:38:02       7 阅读