cp 和 ap 的使用场景:

 

 如果只有一个 nacos 节点,可以直接以单机模式启动,naming 功能是完全正常的。

也可以以集群模式启动,配置文件中只配一个节点即可。但是,因为此时 nacos 的 raft 实现中,一个节点是选不了主的,所以 cp 模式的 raft 协议就不可用,即持久化的服务是无法注册的。但是,临时服务是可以注册的。

com.alibaba.nacos.naming.consistency.persistent.raft.RaftCore.MasterElection#sendVote

拉票

public void sendVote() {

        RaftPeer local = peers.get(NetUtils.localServer());
        Loggers.RAFT.info("leader timeout, start voting,leader: {}, term: {}",
            JSON.toJSONString(getLeader()), local.term);

        peers.reset();

        local.term.incrementAndGet();
        local.voteFor = local.ip;
        local.state = RaftPeer.State.CANDIDATE;

        Map<String, String> params = new HashMap<String, String>(1);
        params.put("vote", JSON.toJSONString(local));
        for (final String server : peers.allServersWithoutMySelf()) {
            final String url = buildURL(server, API_VOTE);
            try {
                HttpClient.asyncHttpPost(url, null, params, new AsyncCompletionHandler<Integer>() {
                    @Override
                    public Integer onCompleted(Response response) throws Exception {
                        if (response.getStatusCode() != HttpURLConnection.HTTP_OK) {
                            Loggers.RAFT.error("NACOS-RAFT vote failed: {}, url: {}", response.getResponseBody(), url);
                            return 1;
                        }

                        RaftPeer peer = JSON.parseObject(response.getResponseBody(), RaftPeer.class);

                        Loggers.RAFT.info("received approve from peer: {}", JSON.toJSONString(peer));

                        peers.decideLeader(peer);

                        return 0;
                    }
                });
            } catch (Exception e) {
                Loggers.RAFT.warn("error while sending vote to server: {}", server);
            }
        }
    }
}

 

posted on 2019-06-18 11:40  偶尔发呆  阅读(9706)  评论(0编辑  收藏  举报