本文主要研究一下kingbus的startRaftPeer

startRaftPeer

kingbus/server/server.go

func (s *KingbusServer) startRaftPeer(peerURLs types.URLs) error {
    err := s.raftNode.NewPeerListener(peerURLs)
    if err != nil {
        return err
    }
    s.raftNode.SetPeerHandler()
    s.raftNode.PeerHandlerServe()
    log.Log.Infof("startRaftPeer success")
    return nil
}
  • startRaftPeer方法根据peerURLs通过s.raftNode.NewPeerListener开启listener,之后执行s.raftNode.SetPeerHandler()、s.raftNode.PeerHandlerServe()

NewPeerListener

kingbus/raft/peer_handler.go

//NewPeerListener create listener of peer
func (r *Node) NewPeerListener(peerURLs types.URLs) (err error) {
    peers := make([]*peerListener, len(peerURLs))
    defer func() {
        if err == nil {
            return
        }
        for i := range peers {
            if peers[i] != nil && peers[i].close != nil {
                log.Log.Info("stopping listening for peers on ", peerURLs.String())
                peers[i].close(context.Background())
            }
        }
    }()

    for i, u := range peerURLs {
        peers[i] = &peerListener{close: func(context.Context) error { return nil }}
        peers[i].Listener, err = rafthttp.NewListener(u, nil)
        if err != nil {
            return err
        }
        peers[i].close = func(context.Context) error {
            return peers[i].Listener.Close()
        }
        log.Log.Info("listening for peers on ", u.String())
    }
    r.PeerListener = peers
    return nil
}
  • NewPeerListener方法遍历peerURLs通过rafthttp.NewListener创建peerListener

PeerHandlerServe

kingbus/raft/peer_handler.go

//PeerHandlerServe serve
func (r *Node) PeerHandlerServe() {
    for _, peer := range r.PeerListener {
        go peer.serve()
    }
}
  • PeerHandlerServe方法则执行peer.serve()

小结

startRaftPeer方法根据peerURLs通过s.raftNode.NewPeerListener开启listener,之后执行s.raftNode.SetPeerHandler()、s.raftNode.PeerHandlerServe()

doc


codecraft
11.9k 声望2k 粉丝

当一个代码的工匠回首往事时,不因虚度年华而悔恨,也不因碌碌无为而羞愧,这样,当他老的时候,可以很自豪告诉世人,我曾经将代码注入生命去打造互联网的浪潮之巅,那是个很疯狂的时代,我在一波波的浪潮上留下...


引用和评论

0 条评论