Nacos服务端健康检查-篇五

Nacos服务端健康检查-篇五

🕐Nacos 客户端服务注册源码分析-篇一

🕑Nacos 客户端服务注册源码分析-篇二

🕒Nacos 客户端服务注册源码分析-篇三

🕓Nacos 服务端服务注册源码分析-篇四


上篇分析l服务端的注册服务的整个流程,探究了如何将客户端的实例信息注册变为 Client 模型实体,完成服务端 Service 与 客户端模型 Client 以及实例信息 instance 三个之间的关联的,原图点这里

请添加图片描述

长连接

在之前的第四篇以及第三篇,探究其客户端的注册实现的时候,曾分析 NamingClientProxyDelegate 代理类中 getExecuteClientProxy 关于当前通讯所实现的具体协议。

private NamingClientProxy getExecuteClientProxy(Instance instance) {
    // 临时节点,走grpc长连接;持久节点,走http短连接
            return instance.isEphemeral() ? grpcClientProxy : httpClientProxy;
        }

那么长连接与短连接之间有何异同呢?

长连接,是指一个连接只要建立,就可以发送多个数据包进行响应,如果没有数据包发送,则需要双方发送链路检测包,实时的检测当前链路的状态。

Nacos 在 2.0 之后,用 gPRC 长连接代替了原来的 Http 短连接请求。

NamingClientProxy 接口负责底层通讯,调用服务端接口。有三个实现类:

  • NamingClientProxyDelegate:代理类,对 NacosNamingService 中的方法进行代理 ,根据实际的请求情况选择 http 或 gRPC 协议请求服务端。
  • NamingGrpcClientProxy:底层通讯基于 gRPC 长连接
  • NamingHttpClientProxy: 底层通讯基于http短连接

NamingClientProxyDelegate会根据instance实例是否是临时节点而选择不同的协议

​ 临时instance:gRPC

​ 持久instance:http

健康检查

​ 在之前的1.x版本中临时实例走Distro协议内存存储,客户端向注册中心发送心跳来维持自身healthy状态,持久实例走Raft协议持久化存储,服务端定时与客户端建立tcp连接做健康检查。

​ 但是2.0版本以后持久化实例没有什么变化,但是2.0临时实例不在使用心跳,而是通过长连接是否存活来判断实例是否健康。

ConnectionManager负责管理所有客户端的长连接。

每3s检测所有超过20s没发生过通讯的客户端,向客户端发起ClientDetectionRequest探测请求,如果客户端在1s内成功响应,则检测通过,否则执行unregister方法移除Connection。

如果客户端持续与服务端通讯,服务端是不需要主动探活的

Map<String, Connection> connections = new ConcurrentHashMap<String, Connection>();
@PostConstruct
public void start() {

    // 启动不健康连接排除功能.
    RpcScheduledExecutor.COMMON_SERVER_EXECUTOR.scheduleWithFixedDelay(new Runnable() {
        @Override
        public void run() {
            try {

                int totalCount = connections.size();
                Loggers.REMOTE_DIGEST.info("Connection check task start");
                MetricsMonitor.getLongConnectionMonitor().set(totalCount);
                //统计过时(20s)连接
                Set<Map.Entry<String, Connection>> entries = connections.entrySet();
                int currentSdkClientCount = currentSdkClientCount();
                boolean isLoaderClient = loadClient >= 0;
                int currentMaxClient = isLoaderClient ? loadClient : connectionLimitRule.countLimit;
                int expelCount = currentMaxClient < 0 ? 0 : Math.max(currentSdkClientCount - currentMaxClient, 0);

                Loggers.REMOTE_DIGEST
                    .info("Total count ={}, sdkCount={},clusterCount={}, currentLimit={}, toExpelCount={}",
                          totalCount, currentSdkClientCount, (totalCount - currentSdkClientCount),
                          currentMaxClient + (isLoaderClient ? "(loaderCount)" : ""), expelCount);

                List<String> expelClient = new LinkedList<>();

                Map<String, AtomicInteger> expelForIp = new HashMap<>(16);

                //1. calculate expel count  of ip.
                for (Map.Entry<String, Connection> entry : entries) {

                    Connection client = entry.getValue();
                    String appName = client.getMetaInfo().getAppName();
                    String clientIp = client.getMetaInfo().getClientIp();
                    if (client.getMetaInfo().isSdkSource() && !expelForIp.containsKey(clientIp)) {
                        //get limit for current ip.
                        int countLimitOfIp = connectionLimitRule.getCountLimitOfIp(clientIp);
                        if (countLimitOfIp < 0) {
                            int countLimitOfApp = connectionLimitRule.getCountLimitOfApp(appName);
                            countLimitOfIp = countLimitOfApp < 0 ? countLimitOfIp : countLimitOfApp;
                        }
                        if (countLimitOfIp < 0) {
                            countLimitOfIp = connectionLimitRule.getCountLimitPerClientIpDefault();
                        }

                        if (countLimitOfIp >= 0 && connectionForClientIp.containsKey(clientIp)) {
                            AtomicInteger currentCountIp = connectionForClientIp.get(clientIp);
                            if (currentCountIp != null && currentCountIp.get() > countLimitOfIp) {
                                expelForIp.put(clientIp, new AtomicInteger(currentCountIp.get() - countLimitOfIp));
                            }
                        }
                    }
                }

                Loggers.REMOTE_DIGEST
                    .info("Check over limit for ip limit rule, over limit ip count={}", expelForIp.size());

                if (expelForIp.size() > 0) {
                    Loggers.REMOTE_DIGEST.info("Over limit ip expel info, {}", expelForIp);
                }

                Set<String> outDatedConnections = new HashSet<>();
                long now = System.currentTimeMillis();
                //2.get expel connection for ip limit.
                for (Map.Entry<String, Connection> entry : entries) {
                    Connection client = entry.getValue();
                    String clientIp = client.getMetaInfo().getClientIp();
                    AtomicInteger integer = expelForIp.get(clientIp);
                    if (integer != null && integer.intValue() > 0) {
                        integer.decrementAndGet();
                        expelClient.add(client.getMetaInfo().getConnectionId());
                        expelCount--;
                    } else if (now - client.getMetaInfo().getLastActiveTime() >= KEEP_ALIVE_TIME) {
                        outDatedConnections.add(client.getMetaInfo().getConnectionId());
                    }

                }

                //3. if total count is still over limit.
                if (expelCount > 0) {
                    for (Map.Entry<String, Connection> entry : entries) {
                        Connection client = entry.getValue();
                        if (!expelForIp.containsKey(client.getMetaInfo().clientIp) && client.getMetaInfo()
                            .isSdkSource() && expelCount > 0) {
                            expelClient.add(client.getMetaInfo().getConnectionId());
                            expelCount--;
                            outDatedConnections.remove(client.getMetaInfo().getConnectionId());
                        }
                    }
                }

                String serverIp = null;
                String serverPort = null;
                if (StringUtils.isNotBlank(redirectAddress) && redirectAddress.contains(Constants.COLON)) {
                    String[] split = redirectAddress.split(Constants.COLON);
                    serverIp = split[0];
                    serverPort = split[1];
                }

                for (String expelledClientId : expelClient) {
                    try {
                        Connection connection = getConnection(expelledClientId);
                        if (connection != null) {
                            ConnectResetRequest connectResetRequest = new ConnectResetRequest();
                            connectResetRequest.setServerIp(serverIp);
                            connectResetRequest.setServerPort(serverPort);
                            connection.asyncRequest(connectResetRequest, null);
                            Loggers.REMOTE_DIGEST
                                .info("Send connection reset request , connection id = {},recommendServerIp={}, recommendServerPort={}",
                                      expelledClientId, connectResetRequest.getServerIp(),
                                      connectResetRequest.getServerPort());
                        }

                    } catch (ConnectionAlreadyClosedException e) {
                        unregister(expelledClientId);
                    } catch (Exception e) {
                        Loggers.REMOTE_DIGEST.error("Error occurs when expel connection, expelledClientId:{}", expelledClientId, e);
                    }
                }

                //4.client active detection.
                Loggers.REMOTE_DIGEST.info("Out dated connection ,size={}", outDatedConnections.size());
                //异步请求所有需要检测的连接
                if (CollectionUtils.isNotEmpty(outDatedConnections)) {
                    Set<String> successConnections = new HashSet<>();
                    final CountDownLatch latch = new CountDownLatch(outDatedConnections.size());
                    for (String outDateConnectionId : outDatedConnections) {
                        try {
                            Connection connection = getConnection(outDateConnectionId);
                            if (connection != null) {
                                ClientDetectionRequest clientDetectionRequest = new ClientDetectionRequest();
                                connection.asyncRequest(clientDetectionRequest, new RequestCallBack() {
                                    @Override
                                    public Executor getExecutor() {
                                        return null;
                                    }

                                    @Override
                                    public long getTimeout() {
                                        return 1000L;
                                    }

                                    @Override
                                    public void onResponse(Response response) {
                                        latch.countDown();
                                        if (response != null && response.isSuccess()) {
                                            connection.freshActiveTime();
                                            successConnections.add(outDateConnectionId);
                                        }
                                    }

                                    @Override
                                    public void onException(Throwable e) {
                                        latch.countDown();
                                    }
                                });

                                Loggers.REMOTE_DIGEST
                                    .info("[{}]send connection active request ", outDateConnectionId);
                            } else {
                                latch.countDown();
                            }

                        } catch (ConnectionAlreadyClosedException e) {
                            latch.countDown();
                        } catch (Exception e) {
                            Loggers.REMOTE_DIGEST
                                .error("[{}]Error occurs when check client active detection ,error={}",
                                       outDateConnectionId, e);
                            latch.countDown();
                        }
                    }

                    latch.await(3000L, TimeUnit.MILLISECONDS);
                    Loggers.REMOTE_DIGEST
                        .info("Out dated connection check successCount={}", successConnections.size());
					// 对于没有成功响应的客户端,执行unregister移出
                    for (String outDateConnectionId : outDatedConnections) {
                        if (!successConnections.contains(outDateConnectionId)) {
                            Loggers.REMOTE_DIGEST
                                .info("[{}]Unregister Out dated connection....", outDateConnectionId);
                            unregister(outDateConnectionId);
                        }
                    }
                }

                //reset loader client

                if (isLoaderClient) {
                    loadClient = -1;
                    redirectAddress = null;
                }

                Loggers.REMOTE_DIGEST.info("Connection check task end");

            } catch (Throwable e) {
                Loggers.REMOTE.error("Error occurs during connection check... ", e);
            }
        }
    }, 1000L, 3000L, TimeUnit.MILLISECONDS);

}

//注销(移出)连接方法
public synchronized void unregister(String connectionId) {
    Connection remove = this.connections.remove(connectionId);
    if (remove != null) {
        String clientIp = remove.getMetaInfo().clientIp;
        AtomicInteger atomicInteger = connectionForClientIp.get(clientIp);
        if (atomicInteger != null) {
            int count = atomicInteger.decrementAndGet();
            if (count <= 0) {
                connectionForClientIp.remove(clientIp);
            }
        }
        remove.close();
        Loggers.REMOTE_DIGEST.info("[{}]Connection unregistered successfully. ", connectionId);
        clientConnectionEventListenerRegistry.notifyClientDisConnected(remove);
    }
}

移除connection后,继承ClientConnectionEventListener的ConnectionBasedClientManager会移除Client,发布ClientDisconnectEvent事件

@Override
public boolean clientDisconnected(String clientId) {
    Loggers.SRV_LOG.info("Client connection {} disconnect, remove instances and subscribers", clientId);
    ConnectionBasedClient client = clients.remove(clientId);
    if (null == client) {
        return true;
    }
    client.release();
    NotifyCenter.publishEvent(new ClientEvent.ClientDisconnectEvent(client));
    return true;
}

ClientDisconnectEvent会触发几个事件:

1)Distro协议:同步移除的client数据

2)清除两个索引缓存:ClientServiceIndexesManager中Service与发布Client的关系;ServiceStorage中Service与Instance的关系

3)服务订阅:ClientDisconnectEvent会间接触发ServiceChangedEvent事件,将服务变更通知客户端。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: nacos-server-2.0.2.zip是Nacos的一个版本,Nacos是阿里巴巴开源的一个动态服务发现、配置管理和服务管理平台。它为云原生应用提供了服务注册、配置管理和服务发现等功能。 nacos-server-2.0.2.zip是Nacos 2.0.2版本的压缩文件,包含了Nacos服务器的安装包。安装Nacos服务器可以帮助开发人员搭建自己的服务注册与发现平台,提供了方便的管理界面和API接口。 Nacos 2.0.2版本是Nacos的一个更新版本,相比于旧版本,它可能包含了一些新的功能、性能改进和 bug 修复。安装Nacos服务器需要将该压缩文件解压,并按照指导进行配置和启动。安装完成后,可以通过Web界面或API接口进行服务的注册、发现和配置的管理。 使用Nacos服务器可以实现微服务架构中的服务注册与发现,可以解决服务间相互调用的问题。通过Nacos的配置管理功能,可以实现动态配置的管理和更新,提供了灵活的配置选项和快速的配置变更能力。此外,Nacos还提供了服务管理相关的功能,如健康检查、多集群支持等。 总之,nacos-server-2.0.2.zip 是Nacos 2.0.2版本的安装包,安装并配置 Nacos 服务器后,可以实现服务注册、发现、配置管理和服务管理等功能,为云原生应用开发提供了方便的工具和平台。 ### 回答2: nacos-server-2.0.2.zip是Nacos服务端的一个版本。Nacos是一个开源的服务发现、配置管理和动态DNS服务的平台,用于帮助开发人员更好地构建和管理微服务架构。 Nacos-server-2.0.2.zip包是Nacos的安装包,其中包含了Nacos服务端的所有必要文件和组件。通过下载并解压该包,我们可以得到一个可用的Nacos服务端实例,可以用于搭建自己的服务发现和配置管理平台。 在Nacos-server-2.0.2.zip中,主要包含以下几个关键部分: 1. nacos-server.jar:这是Nacos服务端的核心程序,负责处理服务注册、发现、配置管理等核心功能。 2. conf目录:该目录下包含了Nacos的配置文件,可以通过修改这些配置文件来进行个性化定制,以满足具体需求。 3. bin目录:该目录下包含了Nacos服务端的启动脚本,可以通过执行这些脚本来启动、停止、重启Nacos服务。 使用Nacos-server-2.0.2.zip时,我们可以根据具体需求对Nacos进行配置和使用。首先,我们需要在conf目录下修改nacos.properties文件,配置Nacos的监听地址、数据库信息等。然后,通过执行bin目录下的startup.sh(Linux/Mac)或startup.cmd(Windows)脚本,即可启动Nacos服务。 一旦Nacos服务启动成功,我们可以通过HTTP请求或使用Nacos提供的Java SDK来进行服务注册、发现和配置管理等操作。Nacos-server-2.0.2.zip提供了一个稳定且功能齐全的Nacos服务端实例,可以满足日常开发和生产使用中的需求。 ### 回答3: nacos-server-2.0.2.zip是Nacos的一个版本。Nacos是阿里巴巴开源的一个动态服务发现、配置管理和服务管理平台。Nacos支持多种编程语言,如Java、Go、Python等,并提供了丰富的API接口,方便开发者在各种场景中使用。 Nacos-server-2.0.2.zip中包含了Nacos Server的安装包。要使用Nacos,首先需要下载并解压此压缩包。解压后,可以得到Nacos Server的所有相关文件和目录。 Nacos Server是Nacos的核心组件,它提供了服务发现、配置管理和服务管理的功能。通过Nacos Server,用户可以注册和发现服务,实现分布式系统中服务的动态发现。同时,Nacos Server还支持配置管理,可以将应用程序的配置信息集中管理,使得配置的更新和变更更加方便。 使用Nacos Server,用户可以实现微服务架构中的动态服务发现与管理,使得服务间的通信更加灵活和可靠。此外,Nacos Server还提供了一些其他的功能,如健康检查、权重调整等,用于提升系统的可用性和性能。 总之,nacos-server-2.0.2.zip提供了Nacos Server的安装包,用户可以通过安装和配置Nacos Server来实现服务发现、配置管理和服务管理等功能,帮助开发者更好地构建和管理分布式系统。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值