链接地址:https://github.com/kubernetes/client-go

[root@wangjq examples]# tree
.
├── create-update-delete-deployment
│   ├── main.go
│   └── README.md
├── dynamic-create-update-delete-deployment
│   ├── main.go
│   └── README.md
├── fake-client
│   ├── doc.go
│   ├── main_test.go
│   └── README.md
├── in-cluster-client-configuration
│   ├── Dockerfile
│   ├── main.go
│   └── README.md
├── leader-election
│   ├── main.go
│   └── README.md
├── out-of-cluster-client-configuration
│   ├── main.go
│   └── README.md
├── README.md
└── workqueue
├── main.go
└── README.md

demo1

[root@wangjq workqueue]# cat main.go
/*
Copyright 2017 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/ package main import (
"flag"
"fmt"
"time" "k8s.io/klog" v1 "k8s.io/api/core/v1"
meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/util/workqueue"
) type Controller struct {
indexer cache.Indexer
queue workqueue.RateLimitingInterface
informer cache.Controller
} func NewController(queue workqueue.RateLimitingInterface, indexer cache.Indexer, informer cache.Controller) *Controller {
return &Controller{
informer: informer,
indexer: indexer,
queue: queue,
}
} func (c *Controller) processNextItem() bool {
// Wait until there is a new item in the working queue
key, quit := c.queue.Get()
if quit {
return false
}
// Tell the queue that we are done with processing this key. This unblocks the key for other workers
// This allows safe parallel processing because two pods with the same key are never processed in
// parallel.
defer c.queue.Done(key) // Invoke the method containing the business logic
err := c.syncToStdout(key.(string))
// Handle the error if something went wrong during the execution of the business logic
c.handleErr(err, key)
return true
} // syncToStdout is the business logic of the controller. In this controller it simply prints
// information about the pod to stdout. In case an error happened, it has to simply return the error.
// The retry logic should not be part of the business logic.
func (c *Controller) syncToStdout(key string) error {
obj, exists, err := c.indexer.GetByKey(key)
if err != nil {
klog.Errorf("Fetching object with key %s from store failed with %v", key, err)
return err
} if !exists {
// Below we will warm up our cache with a Pod, so that we will see a delete for one pod
fmt.Printf("Pod %s does not exist anymore\n", key)
} else {
// Note that you also have to check the uid if you have a local controlled resource, which
// is dependent on the actual instance, to detect that a Pod was recreated with the same name
fmt.Printf("Sync/Add/Update for Pod %s\n", obj.(*v1.Pod).GetName())
}
return nil
} // handleErr checks if an error happened and makes sure we will retry later.
func (c *Controller) handleErr(err error, key interface{}) {
if err == nil {
// Forget about the #AddRateLimited history of the key on every successful synchronization.
// This ensures that future processing of updates for this key is not delayed because of
// an outdated error history.
c.queue.Forget(key)
return
} // This controller retries 5 times if something goes wrong. After that, it stops trying.
if c.queue.NumRequeues(key) < {
klog.Infof("Error syncing pod %v: %v", key, err) // Re-enqueue the key rate limited. Based on the rate limiter on the
// queue and the re-enqueue history, the key will be processed later again.
c.queue.AddRateLimited(key)
return
} c.queue.Forget(key)
// Report to an external entity that, even after several retries, we could not successfully process this key
runtime.HandleError(err)
klog.Infof("Dropping pod %q out of the queue: %v", key, err)
} func (c *Controller) Run(threadiness int, stopCh chan struct{}) {
defer runtime.HandleCrash() // Let the workers stop when we are done
defer c.queue.ShutDown()
klog.Info("Starting Pod controller") go c.informer.Run(stopCh) // Wait for all involved caches to be synced, before processing items from the queue is started
if !cache.WaitForCacheSync(stopCh, c.informer.HasSynced) {
runtime.HandleError(fmt.Errorf("Timed out waiting for caches to sync"))
return
} for i := ; i < threadiness; i++ {
go wait.Until(c.runWorker, time.Second, stopCh)
} <-stopCh
klog.Info("Stopping Pod controller")
} func (c *Controller) runWorker() {
for c.processNextItem() {
}
} func main() {
var kubeconfig string
var master string flag.StringVar(&kubeconfig, "kubeconfig", "", "absolute path to the kubeconfig file")
flag.StringVar(&master, "master", "", "master url")
flag.Parse() // creates the connection
config, err := clientcmd.BuildConfigFromFlags(master, kubeconfig)
if err != nil {
klog.Fatal(err)
} // creates the clientset
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
klog.Fatal(err)
} // create the pod watcher
podListWatcher := cache.NewListWatchFromClient(clientset.CoreV1().RESTClient(), "pods", v1.NamespaceDefault, fields.Everything()) // create the workqueue
queue := workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter()) // Bind the workqueue to a cache with the help of an informer. This way we make sure that
// whenever the cache is updated, the pod key is added to the workqueue.
// Note that when we finally process the item from the workqueue, we might see a newer version
// of the Pod than the version which was responsible for triggering the update.
indexer, informer := cache.NewIndexerInformer(podListWatcher, &v1.Pod{}, , cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
key, err := cache.MetaNamespaceKeyFunc(obj)
if err == nil {
queue.Add(key)
}
},
UpdateFunc: func(old interface{}, new interface{}) {
key, err := cache.MetaNamespaceKeyFunc(new)
if err == nil {
queue.Add(key)
}
},
DeleteFunc: func(obj interface{}) {
// IndexerInformer uses a delta queue, therefore for deletes we have to use this
// key function.
key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj)
if err == nil {
queue.Add(key)
}
},
}, cache.Indexers{}) controller := NewController(queue, indexer, informer) // We can now warm up the cache for initial synchronization.
// Let's suppose that we knew about a pod "mypod" on our last run, therefore add it to the cache.
// If this pod is not there anymore, the controller will be notified about the removal after the
// cache has synchronized.
indexer.Add(&v1.Pod{
ObjectMeta: meta_v1.ObjectMeta{
Name: "mypod",
Namespace: v1.NamespaceDefault,
},
}) // Now let's start the controller
stop := make(chan struct{})
defer close(stop)
go controller.Run(, stop) // Wait forever
select {}
}

demo2:

package main

import (
"flag"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/util/workqueue"
"k8s.io/sample-controller/pkg/signals"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/clientcmd"
"github.com/golang/glog"
"k8s.io/apimachinery/pkg/watch"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
apiv1 "k8s.io/api/core/v1"
"fmt"
"k8s.io/apimachinery/pkg/util/wait"
"time"
) /* 控制器 */
type Controller struct {
// 此控制器使用的客户端
clientset kubernetes.Interface
// 此控制器使用的工作队列
queue workqueue.RateLimitingInterface
// 此控制器使用的共享Informer,SharedIndexInformer可以维护缓存中对象的索引
informer cache.SharedIndexInformer
} /* 主函数 */
var (
// 参数变量
masterURL string
kubeconfig string
)
// 启动控制器
func (c *Controller) Run(stopCh <-chan struct{}) {
// 捕获应用程序崩溃并打印日志
defer utilruntime.HandleCrash()
// 关闭队列,从而导致Worker结束
defer c.queue.ShutDown() glog.Info("启动控制器……") // 运行Informer
go c.informer.Run(stopCh) // 在启动Worker之前,等待缓存同步完成
if !cache.WaitForCacheSync(stopCh, c.informer.HasSynced) {
utilruntime.HandleError(fmt.Errorf("同步缓存超时"))
return
} glog.Info("缓存已经同步,准备启动Worker")
// 循环执行Worker,直到TERM
wait.Until(c.runWorker, time.Second, stopCh)
} // 启动Worker
func (c *Controller) runWorker() {
for c.processNextItem() {
}
} // Worker的逻辑框架
func (c *Controller) processNextItem() bool {
// 最大重试次数
maxRetries := // 获取下一个元素,第2个出参提示队列是否已经关闭
key, quit := c.queue.Get()
if quit {
return false
} // 总是移除Key
defer c.queue.Done(key) // 处理Key
err := c.processItem(key.(string)) if err == nil {
// 处理成功,提示队列不再跟踪事件历史
c.queue.Forget(key)
} else if c.queue.NumRequeues(key) < maxRetries {
glog.Errorf("处理%s事件失败,准备重试: %v", key, err)
c.queue.AddRateLimited(key)
} else {
glog.Errorf("处理%s事件失败,放弃: %v", key, err)
c.queue.Forget(key)
utilruntime.HandleError(err)
}
return true
} // Worker核心逻辑
func (c *Controller) processItem(key string) error {
glog.Infof("开始处理事件%s", key)
// 根据Key获取对象
obj, exists, err := c.informer.GetIndexer().GetByKey(key)
if err != nil {
return fmt.Errorf("获取对象%s失败: %v", key, err)
}
fmt.Print(obj)
if !exists {
// 在这里处理对象删除事件
} else {
// 在这里处理对象创建事件
}
// 因为不进行Resync,不会有更新事件
return nil
} func main() {
// 解析参数,存入上述变量
flag.Parse()
cfg, err := clientcmd.BuildConfigFromFlags(masterURL, kubeconfig)
if err != nil {
glog.Fatalf("构建kubeconfig失败: %s", err.Error())
}
// 创建客户端,Clientset是一系列K8S API的集合
clientset, err := kubernetes.NewForConfig(cfg)
if err != nil {
glog.Fatalf("构建clientset失败: %s", err.Error())
}
// 信号处理通道,当进程接收到信号后,此通道可读
stopCh := signals.SetupSignalHandler() queue := workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter()) informer := cache.NewSharedIndexInformer(
&cache.ListWatch{
ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
// 仅仅列出所有命名空间的Pod
return clientset.CoreV1().Pods(metav1.NamespaceAll).List(options)
},
WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
return clientset.CoreV1().Pods(metav1.NamespaceAll).Watch(options)
},
},
&apiv1.Pod{},
, // 不进行relist
cache.Indexers{}, // map[string]IndexFunc
) // 添加事件处理回调,仅仅是简单的入队
informer.AddEventHandler(cache.ResourceEventHandlerFuncs{// 此结构实现ResourceEventHandler
AddFunc: func(obj interface{}) {
// 从对象中抽取Key
key, err := cache.MetaNamespaceKeyFunc(obj)
if err == nil {
queue.Add(key)
}
},
DeleteFunc: func(obj interface{}) {
key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj)
if err == nil {
queue.Add(key)
}
},
}) // 构建控制器对象
ctrl := Controller{
clientset,
queue,
informer,
} // 启动
ctrl.Run(stopCh)
}

client-go workqueue demo的更多相关文章

  1. Axis2创建WebService服务端接口+SoupUI以及Client端demo测试调用

    第一步:引入axis2相关jar包,如果是pom项目,直接在pom文件中引入依赖就好 <dependency> <groupId>org.apache.axis2</gr ...

  2. jersey client上传下载文件

    jersey client上传文件demo File file = new File("/tmp/test.jpg"); System.out.println(file.exist ...

  3. 2.spring cloud eureka client配置

    红色加粗内容表示修改部分 1.把server项目打成jar包并启动 在项目根目录cmd执行  mvn clean package -Dmaven.test.skip=true mavne仓库地址建议 ...

  4. SpringCloud IDEA 教学 (三) Eureka Client

    写在前头 本篇继续介绍基于Eureka的SpringCloud微服务搭建,回顾一下搭建过程, 第一步:建立一个服务注册中心: 第二步:建立微服务并注入到注册中心: 第三步:建立client端来访问微服 ...

  5. Linux socket program Demo1(client & server)

    client  and  server Demo of socket. client send data to server. server send data to client. // this ...

  6. Demo客户端相关规范 v1.0

    目录 开发环境 开发工具 代码管理 项目代码 分支管理 名称管理 打包管理 存储路径 存储结构 测试包 正式包 名称管理 依赖组件 内部组件 外部组件 解决方案结构 解决方案命名 解决方案文件夹 项目 ...

  7. 【SpringCloud】04.SpringCloud Eureka Server与Client的创建

    Eureka是Netflix开发的服务发现框架,本身是一个基于REST的服务,主要用于定位运行在AWS域中的中间层服务,以达到负载均衡和中间层服务故障转移的目的.SpringCloud将它集成在其子项 ...

  8. RPC 的概念模型与实现解析

    今天分布式应用.云计算.微服务大行其道,作为其技术基石之一的 RPC 你了解多少?一篇 RPC 的技术总结文章,数了下 5k+ 字,略长,可能也不适合休闲的碎片化时间阅读,可以先收藏抽空再细读:) 全 ...

  9. Spring中配置和读取多个Properties文件--转

    public class PropertiesFactoryBeanextends PropertiesLoaderSupportimplements FactoryBean, Initializin ...

随机推荐

  1. expect使用技巧

    1) 获取命令行参数,例如通过./abc.exp a1 a2执行expect脚本 set 变量名1 [lindex $argv 0] 获取第1个参数a1 set 变量名2 [lindex $argv ...

  2. kafka笔记——入门介绍

    中文文档 目录 kafka的优势 首先几个概念 kafka的四大核心API kafka的基本术语 主题和日志(Topic和Log) 每个分区都是一个顺序的,不可变的队列,并且可以持续的添加,分区中的每 ...

  3. vue“欺骗”ueditor,实现图片上传

    一.环境介绍 @vue/cli 4.3.1 webpack 4.43.0 ueditor1.4.3.3 jsp版 二.springboot集成ueditor,实现分布式图片上传 参考我的另一篇博客,& ...

  4. Python 变量类型及变量赋值

    在 Python 中,变量不一定占用内存变量.变量就像是对某一处内存的引用,可以通过变量访问到其所指向的内存中的值,并且可以让变量指向其他的内存.在 Python 中,变量不需要声明,但是使用变量之前 ...

  5. PHP xml_set_notation_decl_handler() 函数

    定义和用法 xml_set_notation_decl_handler() 函数规定当解析器在 XML 文档中找到符号声明时被调用的函数. 如果成功,该函数则返回 TRUE.如果失败,则返回 FALS ...

  6. 还分不清 Cookie、Session、Token、JWT?一篇文章讲清楚

    还分不清 Cookie.Session.Token.JWT?一篇文章讲清楚 转载来源 公众号:前端加加 作者:秋天不落叶 什么是认证(Authentication) 通俗地讲就是验证当前用户的身份,证 ...

  7. python3.1for循环及应用

    #给定范围,进行循环for i in range (0,5): print(i) #对序列进行遍历list1=[1,2,3,4,5]for i in list1: print(i+1) #对元组进行遍 ...

  8. 007_对go语言中的自定义排序sort的小练习

    在go语言基础知识中,有个知识点是go语言的自定义排序,我在学习完之后,自己做了一些小练习和总结. 首先按照惯例,还是呈上代码演示: package main import "fmt&quo ...

  9. C语言学习笔记之输出缓冲

    在c语言中经常用到输出函数printf,当我们像往常一样在输出函数中输入我们的想要的输出的东西后加\n换行 验证结果如我们输出的一样 如果我们在后面加入死循环会不会出现这些语句呢 结果卡死了,可还是输 ...

  10. 2、Java 基础语法标识符、修饰符、变量、 数组、枚举、关键字

    Java 基础语法 一个 Java 程序可以认为是一系列对象的集合,而这些对象通过调用彼此的方法来协同工作.下面简要介绍下类.对象.方法和实例变量的概念. 对象:对象是类的一个实例,有状态和行为.例如 ...