k8s leaderelection

13 篇文章 0 订阅
const (
	LEASELOCKNAME      = "tes"
	LEASELOCKNAMESPACE = "kube-system"
)

func main () {
      	LeaseLockID = uuid.New().String()
		client.InitClientSet()

		run := func(ctx context.Context) {
			// 添加运行逻辑代码
			klog.Info("Controller loop...")
			select{}
		}

		ctx, cancel := context.WithCancel(context.Background())
		defer cancel()

		ch := make(chan os.Signal, 1)
		signal.Notify(ch, os.Interrupt, syscall.SIGTERM)
		go func() {
			<-ch
			klog.Info("Received termination, signaling shutdown")
			cancel()
		}()

		// 指定锁的资源对象,这里使用了Lease资源,还支持configmap,endpoint,或者multilock(即多种配合使用)
		lock := &resourcelock.LeaseLock{
			LeaseMeta: metav1.ObjectMeta{
				Name:      conf.LEASELOCKNAME,
				Namespace: conf.LEASELOCKNAMESPACE,
			},
			Client: client.K8sClientSet.CoordinationV1(),
			LockConfig: resourcelock.ResourceLockConfig{
				Identity: LeaseLockID,
			},
		}

		leaderelection.RunOrDie(ctx, leaderelection.LeaderElectionConfig{
			Lock:            lock,
			ReleaseOnCancel: true,
			LeaseDuration:   30 * time.Second, //租约时间
			RenewDeadline:   15 * time.Second, //更新租约的
			RetryPeriod:     5 * time.Second,  //非leader节点重试时间
			Callbacks: leaderelection.LeaderCallbacks{
				OnStartedLeading: func(ctx context.Context) {
					//变为leader执行的业务代码
					run(ctx)
				},
				OnStoppedLeading: func() {
					// 进程退出
					klog.Infof("leader lost: %s", LeaseLockID)
					os.Exit(0)
				},
				OnNewLeader: func(identity string) {
					//当产生新的leader后执行的方法
					if identity == LeaseLockID {
						klog.Infof("i am leader now: %s", identity)
						return
					}
					klog.Infof("new leader elected: %s, wait...", identity)
				},
			},
		})

}

参考:跳转中...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值