2023-09-15
原文作者:王伟王胖胖 原文地址: https://blog.csdn.net/wangwei19871103/article/details/105847025

nacos数据一致性服务执行流程

202309152319018461.png

RaftController的onPublish过半响应

最终响应还是调用了RaftConsistencyServiceImplonPut。然后返回ok

         @PostMapping("/datum/commit")
        public String onPublish(HttpServletRequest request, HttpServletResponse response) throws Exception {
    
            response.setHeader("Content-Type", "application/json; charset=" + getAcceptEncoding(request));
            response.setHeader("Cache-Control", "no-cache");
            response.setHeader("Content-Encode", "gzip");
    
            String entity = IoUtils.toString(request.getInputStream(), "UTF-8");
            String value = URLDecoder.decode(entity, "UTF-8");
            JSONObject jsonObject = JSON.parseObject(value);
            String key = "key";
    
            RaftPeer source = JSON.parseObject(jsonObject.getString("source"), RaftPeer.class);
            JSONObject datumJson = jsonObject.getJSONObject("datum");
    
            Datum datum = null;
            if (KeyBuilder.matchInstanceListKey(datumJson.getString(key))) {
                datum = JSON.parseObject(jsonObject.getString("datum"), new TypeReference<Datum<Instances>>() {
                });
            } else if (KeyBuilder.matchSwitchKey(datumJson.getString(key))) {
                datum = JSON.parseObject(jsonObject.getString("datum"), new TypeReference<Datum<SwitchDomain>>() {
                });
            } else if (KeyBuilder.matchServiceMetaKey(datumJson.getString(key))) {
                datum = JSON.parseObject(jsonObject.getString("datum"), new TypeReference<Datum<Service>>() {
                });
            }
    
            raftConsistencyService.onPut(datum, source);
            return "ok";
        }

RaftConsistencyServiceImpl的onPut

调用了RaftCoreonPublish,用来同步服务数据。

        public void onPut(Datum datum, RaftPeer source) throws NacosException {
            try {
                raftCore.onPublish(datum, source);
            } catch (Exception e) {
                Loggers.RAFT.error("Raft onPut failed.", e);
                throw new NacosException(NacosException.SERVER_ERROR, "Raft onPut failed, datum:" + datum + ", source: " + source, e);
            }
        }

至此强一致性的数据同步也说完了,其实就是过半机制,所以nacos的数据同步是可以APCP混用的。

一些问题

出现了两个一样的类,但是逻辑基本是一样的,挺奇怪,不过仔细一看,还有不一样的,RaftCore的通知器还有前缀为com.alibaba.nacos.naming.domains.meta.的监听器,不止是Service,还有ServiceManager

202309152319025662.png

202309152319035223.png
其他的细节只能有时间慢慢看了,接下去说下CP的选举问题。

好了,今天就到这里了,希望对学习理解有帮助,大神看见勿喷,仅为自己的学习理解,能力有限,请多包涵。

阅读全文