Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Create an election manager

func NewElectionManager(zkConfig *ZookeeperConfig, isMaster chan bool) *ElectionManager {
   electionManager := &ElectionManager{
      nil,
      zkConfig,
      isMaster,
   }
​
   electionManager.initConnection()
​
   return electionManager
}
Copy the code

Creating an election manager is a simple matter of entering some configuration information, initializing the connection, and passing the initialized election manager.

Initialize the Zookeeper connection

The Zookeeper connection is initialized as follows:

func (electionManager *ElectionManager) initConnection() error { if ! electionManager.isConnected() { conn, connChan, err := zk.Connect(electionManager.ZKConfig.Servers, time.Second*5) if err ! = nil { return err } for { isConnected := false select { case connEvcent := <-connChan: If connevcent. State == zk.stateconnected {isConnected = true fmt.println (" connected ")} case _ = < time-after (time.second) * 3): return errors.New(" ZK connection timed out!" ) } if isConnected { break } } electionManager.ZKClientConn = conn } return nil }Copy the code

First, check whether Zookeeper is connected. If there is a connection problem or no connection, connect Zookeeper.

Let’s take a look at zK.Connect, which is used to establish new connections to the Zookeeper server pool. The first parameter is the server cluster address, and the second parameter is the amount of time the current session is still considered valid after the connection to the server is lost. Before the session times out, you can re-establish a connection to a different server and keep the same session. This allows you to maintain and monitor any temporary nodes.

If connChan isConnected to a zk.StateConnected ected tree, isConnected is set to true. If connChan isConnected to a zk.StateConnected tree, isConnected isConnected to a connected tree. When the connection is successful jump out of the for loop, electionManager. ZKClientConn = conn said it will get connected to the election the connection manager.

Welcome to the next section