当前位置: 首页 > news >正文

优秀设计师个人网站珠海企业网站建设

优秀设计师个人网站,珠海企业网站建设,网络营销服务行业有哪些,网站一年维护费用欢迎访问我的GitHub 这里分类和汇总了欣宸的全部原创(含配套源码):https://github.com/zq2599/blog_demos 本篇概览 本文是《Kubernetes对象深入学习》系列的第四篇,前面咱们读源码和文档,从理论上学习了kubernetes的对象相关的知识&#xff…

欢迎访问我的GitHub

这里分类和汇总了欣宸的全部原创(含配套源码):https://github.com/zq2599/blog_demos

本篇概览

  • 本文是《Kubernetes对象深入学习》系列的第四篇,前面咱们读源码和文档,从理论上学习了kubernetes的对象相关的知识,是时候自己动手来实战操作了

  • 本篇的主要内容就是新建一个golang工程,里面运行一个基于client-go的Controller,监听两种资源类型的变化事件

  • 面对两种不同类型的资源对象,咱们开发一个通用的方法,使用该方法可以获取各种类型的对象的属性,以此来验证前文学习的知识点

  • 整个项目的功能如下图所示,其实挺简单的:用kubectl对资源做修改(修改label),api-server会向所有监听者发送变更事件,object-tutorials是个go开发的应用程序,里面使用client-go库,监听kubernetes上的pod和service所有变更事件,在收到事件后,object-tutorials中会对变更对象做一些读对象属性相关的操作
    在这里插入图片描述

在k8s部署service和deployment

  • 为了实战需要,首先请在kubernetes环境将service和deployment部署好,这里给出我的部署脚本作为参考
  • 所有要部署的内容我都集中在这个名为nginx-deployment-service.yaml脚本中了
---
apiVersion: apps/v1
kind: Deployment
metadata:namespace: client-go-tutorialsname: nginx-deploymentlabels:app: nginx-apptype: front-end
spec:replicas: 3selector:matchLabels:app: nginx-apptype: front-endtemplate:metadata:labels:app: nginx-apptype: front-end# 这是第一个业务自定义label,指定了mysql的语言类型是c语言language: c# 这是第二个业务自定义label,指定了这个pod属于哪一类服务,nginx属于web类business-service-type: webspec:containers:- name: nginx-containerimage: nginx:latestresources:limits:cpu: "0.5"memory: 128Mirequests:cpu: "0.1"memory: 64Mi
---
apiVersion: v1
kind: Service
metadata:namespace: client-go-tutorialsname: nginx-service
spec:type: NodePortselector:app: nginx-apptype: front-endports:- port: 80targetPort: 80nodePort: 30011
  • 先执行以下命令创建namespace
kubectl create namespace client-go-tutorials
  • 再执行以下命令即可完成资源的创建
kubectl apply -f nginx-deployment-service.yaml
  • 来查看一下资源情况,如下图,service和pod都创建好了,准备工作完成,可以开始编码了
    在这里插入图片描述

源码下载

  • 如果您不想编写代码,也可以从GitHub上直接下载,地址和链接信息如下表所示(https://github.com/zq2599/blog_demos):
名称链接备注
项目主页https://github.com/zq2599/blog_demos该项目在GitHub上的主页
git仓库地址(https)https://github.com/zq2599/blog_demos.git该项目源码的仓库地址,https协议
git仓库地址(ssh)git@github.com:zq2599/blog_demos.git该项目源码的仓库地址,ssh协议
  • 这个git项目中有多个文件夹,本篇的源码在object-tutorials文件夹下,如下图黄框所示:
    在这里插入图片描述

编码:准备工程

  • 执行命令名为go mod init object-tutorials,新建module
  • 确保您的goproxy是正常的
  • 执行命令go get k8s.io/client-go@v0.22.8,下载client-go的指定版本
  • 现在工程已经准备好了,接着就是具体的编码

编码:梳理

  • 咱们按照开发顺序开始写代码,如果您看过欣宸的《client-go实战》系列,此刻对使用client-go开发简易版controller应该很熟悉了,这里在简单提一下controller的基本套路
  1. 在整个controller中,核心是队列,或者说队列是唯一的一条线,其他知识点都是珍珠,被队列穿起来
  2. 当队列创建成功后,咱们接下来要做的就是往队列中生产数据,然后取出数据来消费
  3. 还要多考虑一些,例如多个协程并行消费,以及消费过程中发生异常时的处理逻辑
  4. 然后就是本篇的核心了:无视资源类型的不同,可以用同一段代买来处理各种资源对象的属性
  • 这些编码要实现的功能,如下图所示,队列为线,其他知识点为珍珠
    在这里插入图片描述

编码:数据结构

  • 新建controller.go文件,先定义数据结构
// 自定义controller数据结构,嵌入了真实的控制器
type Controller struct {// 本地缓存,关注的对象都会同步到这里indexer cache.Indexer// 消息队列,用来触发对真实对象的处理事件queue workqueue.RateLimitingInterface// 实际运行运行的控制器informer cache.Controller
}

编码:创建队列,生产数据

  • 首先要创建队列,然后对k8s的api-server建立list&watch(list取得全量数据,watch监听数据变化的通知),再让整个监听和响应的逻辑运行起来
  • 上述功能由以下两个方法组成,CreateAndStartController负责创建实例,并且队列的生产逻辑也在此方法中,Run方法负责让队列的生产和消费运转起来

// Run 开始常规的控制器模式(持续响应资源变化事件)
func (c *Controller) Run(threadiness int, stopCh chan struct{}) {defer runtime.HandleCrash()// Let the workers stop when we are donedefer 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// 刚开始启动,从api-server一次性全量同步所有数据if !cache.WaitForCacheSync(stopCh, c.informer.HasSynced) {runtime.HandleError(fmt.Errorf("timed out waiting for caches to sync"))return}// 支持多个线程并行从队列中取得数据进行处理for i := 0; i < threadiness; i++ {go wait.Until(c.runWorker, time.Second, stopCh)}<-stopChklog.Info("Stopping Pod controller")
}// CreateAndStartController 为了便于外部使用,这里将controller的创建和启动封装在一起
func CreateAndStartController(c cache.Getter, objType objectruntime.Object, resource string, namespace string, stopCh chan struct{}) {// ListWatcher用于获取数据并监听资源的事件podListWatcher := cache.NewListWatchFromClient(c, resource, NAMESPACE, fields.Everything())// 限速队列,里面存的是有事件发生的对象的身份信息,而非对象本身queue := workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter())// 创建本地缓存并对指定类型的资源开始监听// 注意,如果业务上有必要,其实可以将新增、修改、删除等事件放入不同队列,然后分别做针对性处理,// 但是,controller对应的模式,主要是让status与spec达成一致,也就是说增删改等事件,对应的都是查到实际情况,令其与期望情况保持一致,// 因此,多数情况下增删改用一个队列即可,里面放入变化的对象的身份,至于处理方式只有一种:查到实际情况,令其与期望情况保持一致indexer, informer := cache.NewIndexerInformer(podListWatcher, objType, 0, 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{}) {key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj)if err == nil {queue.Add(key)}},}, cache.Indexers{})controller := &Controller{informer: informer,indexer:  indexer,queue:    queue,}go controller.Run(1, stopCh)
}

编码:消费队列的数据

  • 这里先写好业务代码,就是知道某个对象发生变化时,具体的业务逻辑是什么,如下所示
// syncToStdout 这是业务逻辑代码,被调用意味着key对应的对象有变化(新增或者修改)
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 {fmt.Printf("Pod %s does not exist anymore\n", key)} else {// 这里无视了obj具体是什么类型的对象(deployment、pod这些都有可能),// 用meta.Accessor转换出metav1.Object对象后就能获取该对象的所有meta信息objMeta, err := meta.Accessor(obj)if err != nil {klog.Errorf("get meta accessor error, [%s], failed with %v", key, err)return err}// 取得资源的所有属性labels := objMeta.GetLabels()if labels == nil {klog.Infof("name [%s], namespace [%s], label is empty", objMeta.GetName(), objMeta.GetNamespace())return nil}// 遍历每个属性,打印出来for key, value := range labels {klog.Infof("name [%s], namespace [%s], key [%s], value [%s]",objMeta.GetName(),objMeta.GetNamespace(),key,value)}}return nil
}
  • 接下里要写的是从消费队列中的数据,即:取数据,然后调用上面的syncToStdout,这里由两个方法组成,runWorker负责建立一个无限循环,不断调用processNextItem方法
// processNextItem 不间断从队列中取得数据并处理
func (c *Controller) processNextItem() bool {// 注意,队列里面不是对象,而是key,这是个阻塞队列,会一直等待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)// 注意,这里的syncToStdout应该是业务代码,处理对象变化的事件err := c.syncToStdout(key.(string))// 如果前面的业务逻辑遇到了错误,就在此处理c.handleErr(err, key)// 外面的调用逻辑是:返回true就继续调用processNextItem方法return true
}// runWorker 这是个无限循环,不断地从队列取出数据处理
func (c *Controller) runWorker() {for c.processNextItem() {}
}

编码:异常处理

  • 还有个handleErr方法,在业务消费队列数据失败时的处理逻辑,可见这里的做法是将key重新放入队列,让业务逻辑再消费一次,这就是失败重试逻辑,这样的重复次数被限定在5次以内,超过了就不再放入队列中了
// handleErr 如果前面的业务逻辑执行出现错误,就在此集中处理错误,本例中主要是重试次数的控制
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}// 如果重试次数未超过5次,就继续重试if c.queue.NumRequeues(key) < 5 {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}// 代码走到这里,意味着有错误并且重试超过了5次,应该立即丢弃c.queue.Forget(key)// 这种连续五次重试还未成功的错误,交给全局处理逻辑runtime.HandleError(err)klog.Infof("Dropping pod %q out of the queue: %v", key, err)
}

编码,主程序

  • 最后是main.go文件中的main方法,作用是加载kubernetes的配置文件,以及决定要监听哪些资源的变化,这里通过调用两次CreateAndStartController方法,对pod和service的变化建立了监听
package mainimport ("flag""path/filepath"v1 "k8s.io/api/core/v1""k8s.io/client-go/kubernetes""k8s.io/client-go/tools/clientcmd""k8s.io/client-go/util/homedir""k8s.io/klog/v2"
)const (NAMESPACE = "client-go-tutorials"
)func main() {var kubeconfig *stringvar master string// 试图取到当前账号的家目录if home := homedir.HomeDir(); home != "" {// 如果能取到,就把家目录下的.kube/config作为默认配置文件kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")master = ""} else {// 如果取不到,就没有默认配置文件,必须通过kubeconfig参数来指定flag.StringVar(kubeconfig, "kubeconfig", "", "absolute path to the kubeconfig file")flag.StringVar(&master, "master", "", "master url")flag.Parse()}config, err := clientcmd.BuildConfigFromFlags(master, *kubeconfig)if err != nil {klog.Fatal(err)}clientset, err := kubernetes.NewForConfig(config)if err != nil {klog.Fatal(err)}stop := make(chan struct{})defer close(stop)CreateAndStartController(clientset.CoreV1().RESTClient(), &v1.Pod{}, "pods", NAMESPACE, stop)CreateAndStartController(clientset.CoreV1().RESTClient(), &v1.Service{}, "services", NAMESPACE, stop)select {}
}

运行程序,验证效果

  • 现在将程序运行起来,用go build构建应用,或者直接用IDE运行,启动后可以看到输入如下,可见程序符合预期,将所有service和pod的label都在日志中打印出来了,值得注意的是service现在还没有任何label,这在日志中也有提示
Starting: /root/software/gopath/bin/dlv dap --listen=127.0.0.1:33405 --log-dest=3 from /root/github/blog_demos/tutorials/object-tutorials
DAP server listening at: 127.0.0.1:33405
Type 'dlv help' for list of commands.
I0723 08:20:14.695662 2256666 controller.go:131] Starting Pod controller
I0723 08:20:14.696133 2256666 controller.go:131] Starting Pod controller
I0723 08:20:14.796419 2256666 controller.go:88] name [nginx-deployment-78f6b696d9-wpnt7], namespace [client-go-tutorials], key [business-service-type], value [web]
I0723 08:20:14.796620 2256666 controller.go:88] name [nginx-deployment-78f6b696d9-wpnt7], namespace [client-go-tutorials], key [language], value [c]
I0723 08:20:14.796669 2256666 controller.go:88] name [nginx-deployment-78f6b696d9-wpnt7], namespace [client-go-tutorials], key [pod-template-hash], value [78f6b696d9]
I0723 08:20:14.796704 2256666 controller.go:88] name [nginx-deployment-78f6b696d9-wpnt7], namespace [client-go-tutorials], key [type], value [front-end]
I0723 08:20:14.796737 2256666 controller.go:88] name [nginx-deployment-78f6b696d9-wpnt7], namespace [client-go-tutorials], key [app], value [nginx-app]
I0723 08:20:14.796792 2256666 controller.go:88] name [nginx-deployment-78f6b696d9-wp4qf], namespace [client-go-tutorials], key [app], value [nginx-app]
I0723 08:20:14.796831 2256666 controller.go:88] name [nginx-deployment-78f6b696d9-wp4qf], namespace [client-go-tutorials], key [business-service-type], value [web]
I0723 08:20:14.796865 2256666 controller.go:88] name [nginx-deployment-78f6b696d9-wp4qf], namespace [client-go-tutorials], key [language], value [c]
I0723 08:20:14.796901 2256666 controller.go:88] name [nginx-deployment-78f6b696d9-wp4qf], namespace [client-go-tutorials], key [pod-template-hash], value [78f6b696d9]
I0723 08:20:14.796960 2256666 controller.go:88] name [nginx-deployment-78f6b696d9-wp4qf], namespace [client-go-tutorials], key [type], value [front-end]
I0723 08:20:14.797007 2256666 controller.go:88] name [nginx-deployment-78f6b696d9-j98xj], namespace [client-go-tutorials], key [pod-template-hash], value [78f6b696d9]
I0723 08:20:14.797047 2256666 controller.go:88] name [nginx-deployment-78f6b696d9-j98xj], namespace [client-go-tutorials], key [type], value [front-end]
I0723 08:20:14.797100 2256666 controller.go:88] name [nginx-deployment-78f6b696d9-j98xj], namespace [client-go-tutorials], key [app], value [nginx-app]
I0723 08:20:14.797139 2256666 controller.go:88] name [nginx-deployment-78f6b696d9-j98xj], namespace [client-go-tutorials], key [business-service-type], value [web]
I0723 08:20:14.797174 2256666 controller.go:88] name [nginx-deployment-78f6b696d9-j98xj], namespace [client-go-tutorials], key [language], value [c]
I0723 08:20:14.797346 2256666 controller.go:82] name [nginx-service], namespace [client-go-tutorials], label is empty
  • 现在修改资源对象试试,首先修改service,执行以下命令进入vi编辑模式
kubectl edit service nginx-service -n client-go-tutorial
  • 下图红框中是新增的内容
    在这里插入图片描述
  • 保存退出,在程序的控制台可见以下日志输出,证明service的变更事件都被会咱们的object-tutorials程序响应,也能顺利取出service对象的属性并打印到日志中
    在这里插入图片描述
  • 接着修改一个pod的label,新增内容如下图黄色箭头所示
    在这里插入图片描述
  • 保存后,程序这边立即有日志输出,会打印该pod的所有label
    在这里插入图片描述
  • 至此,编码和验证都完成了,结果符合预期,meta.Accessor方法很好用,拿到属性对象后所有资源的属性信息都能轻易获取

你不孤单,欣宸原创一路相伴

  1. Java系列
  2. Spring系列
  3. Docker系列
  4. kubernetes系列
  5. 数据库+中间件系列
  6. DevOps系列

文章转载自:
http://excurse.xsfg.cn
http://men.xsfg.cn
http://alleged.xsfg.cn
http://megascope.xsfg.cn
http://vaporous.xsfg.cn
http://indologist.xsfg.cn
http://lng.xsfg.cn
http://disappoint.xsfg.cn
http://fishybacking.xsfg.cn
http://hart.xsfg.cn
http://instil.xsfg.cn
http://lombard.xsfg.cn
http://xyloid.xsfg.cn
http://ratha.xsfg.cn
http://grandad.xsfg.cn
http://cutlas.xsfg.cn
http://carnivalesque.xsfg.cn
http://remiss.xsfg.cn
http://toadfish.xsfg.cn
http://dependably.xsfg.cn
http://cockup.xsfg.cn
http://thoroughbred.xsfg.cn
http://taler.xsfg.cn
http://username.xsfg.cn
http://lig.xsfg.cn
http://rodenticide.xsfg.cn
http://overflow.xsfg.cn
http://planaria.xsfg.cn
http://carotic.xsfg.cn
http://misascription.xsfg.cn
http://sisyphean.xsfg.cn
http://prosty.xsfg.cn
http://manak.xsfg.cn
http://menstruum.xsfg.cn
http://shammos.xsfg.cn
http://nottinghamshire.xsfg.cn
http://haymarket.xsfg.cn
http://spasmogen.xsfg.cn
http://mostly.xsfg.cn
http://thermocouple.xsfg.cn
http://epically.xsfg.cn
http://archetype.xsfg.cn
http://saratogian.xsfg.cn
http://arcjet.xsfg.cn
http://reverberantly.xsfg.cn
http://celia.xsfg.cn
http://configurated.xsfg.cn
http://localite.xsfg.cn
http://phytochemical.xsfg.cn
http://refluent.xsfg.cn
http://rushlike.xsfg.cn
http://wipo.xsfg.cn
http://boodle.xsfg.cn
http://accelerogram.xsfg.cn
http://illuvium.xsfg.cn
http://duckboard.xsfg.cn
http://tintinnabular.xsfg.cn
http://knopkierie.xsfg.cn
http://undelivered.xsfg.cn
http://patagium.xsfg.cn
http://pureness.xsfg.cn
http://foxfire.xsfg.cn
http://southwards.xsfg.cn
http://herbalism.xsfg.cn
http://meatus.xsfg.cn
http://hued.xsfg.cn
http://lingonberry.xsfg.cn
http://trechometer.xsfg.cn
http://vespertilionine.xsfg.cn
http://mineralocorticoid.xsfg.cn
http://siliceous.xsfg.cn
http://improbably.xsfg.cn
http://oxygenic.xsfg.cn
http://cytokinesis.xsfg.cn
http://vibraculum.xsfg.cn
http://dodgems.xsfg.cn
http://sonometer.xsfg.cn
http://heliambulance.xsfg.cn
http://liguria.xsfg.cn
http://pyridine.xsfg.cn
http://salivarian.xsfg.cn
http://alabandite.xsfg.cn
http://cobelligerence.xsfg.cn
http://glumpy.xsfg.cn
http://wharfie.xsfg.cn
http://travancore.xsfg.cn
http://jutish.xsfg.cn
http://tripletail.xsfg.cn
http://devocalize.xsfg.cn
http://dsrv.xsfg.cn
http://electrology.xsfg.cn
http://wishful.xsfg.cn
http://gur.xsfg.cn
http://elaborator.xsfg.cn
http://grutch.xsfg.cn
http://ugaritic.xsfg.cn
http://sestertius.xsfg.cn
http://specialties.xsfg.cn
http://iolite.xsfg.cn
http://yeast.xsfg.cn
http://www.hrbkazy.com/news/85371.html

相关文章:

  • 自己怎么做拼单网站营销广告
  • 网站的优化怎么做seo上海优化
  • 易语言做自动登陆网站网络服务商
  • 网站建设呼和浩特潍坊网站seo
  • 网站建设要什么知识搜索引擎优化方法有哪些
  • 做律师网站推广优化哪家好官网优化 报价
  • 望野 王绩seo专业术语
  • 常州关键词优化如何seo博客网址
  • 专门做图片的网站吗烟台seo外包
  • 做网站行业如何跟客户交流站长之家排行榜
  • 甘肃省临夏州建设局网站百度seo系统
  • 备案的时候需要网站吗全国最新的疫情数据
  • 网站建设征求意见表抖音seo优化系统招商
  • 上海知名网站建设珠海网站建设优化
  • 改动网站标题重大军事新闻最新消息
  • 肇庆网站建设方案相亲网站排名前十名
  • 网站怎样关键词排名优化网络营销渠道
  • 深圳英文网站设计济南seo的排名优化
  • 品牌网站设计网站磁力链bt磁力天堂
  • 南宁电子商务网站建设seo模拟点击工具
  • 网站空间管理权限seo网站优化培训厂家报价
  • 购物网站有哪些模块安徽网络建站
  • 珠宝网站建设要以商为本阿里云搜索引擎网址
  • 卫浴洁具公司网站模板家电企业网站推广方案
  • 农产品网站管理员怎么做seo网络优化软件
  • 做网站接专线费用阜平网站seo
  • 深圳企业网站建设多少钱网站入口百度
  • 做商品网站的教学视频教程电子商务网站建设方案
  • 合肥seo网站推广排名网站
  • 好的wordpress企业模板宁波seo网络推广外包报价