Пример #1
0
/*
*重连zk
 */
func (self *ZKManager) reconnect() <-chan bool {
	ch := make(chan bool, 1)
	go func() {

		reconnTimes := int64(0)
		f := func() error {
			ss, eventChan, err := zk.Connect(strings.Split(self.zkhosts, ","), 5*time.Second)
			if nil != err {
				log.Warn("连接zk失败.....%ds后重连任务重新发起...|", (reconnTimes+1)*5)
				return err
			} else {
				log.Info("重连ZK任务成功....")
				//初始化当前的状态
				self.session = ss
				self.eventChan = eventChan

				ch <- true
				close(ch)
				return nil
			}

		}
		//启动重连任务
		for !self.isClose {
			select {
			case <-time.After(time.Duration(reconnTimes * time.Second.Nanoseconds())):
				err := f()
				if nil != err {
					reconnTimes += 1
				} else {
					//重连成功则推出
					break
				}
			}
		}

		//失败
		ch <- false
		close(ch)
	}()
	return ch
}
Пример #2
0
func (self *ZKManager) Start() {
	if len(self.zkhosts) <= 0 {
		log.Warn("使用默认zkhosts!|localhost:2181\n")
		self.zkhosts = "localhost:2181"
	} else {
		log.Info("使用zkhosts:[%s]!\n", self.zkhosts)
	}

	ss, eventChan, err := zk.Connect(strings.Split(self.zkhosts, ","), 5*time.Second)
	if nil != err {
		panic("连接zk失败..." + err.Error())
		return
	}

	exist, _, err := ss.Exists(KITEQ)
	if nil != err {
		ss.Close()
		panic("无法创建KITEQ " + err.Error())

	}

	if !exist {
		resp, err := ss.Create(KITEQ, nil, zk.CreatePersistent, zk.WorldACL(zk.PermAll))
		if nil != err {
			ss.Close()
			panic("NewZKManager|CREATE ROOT PATH|FAIL|" + KITEQ + "|" + err.Error())
		} else {
			log.Info("NewZKManager|CREATE ROOT PATH|SUCC|%s", resp)
		}
	}

	self.session = ss
	self.isClose = false
	self.eventChan = eventChan
	go self.listenEvent()
}