springcloud heartbeat executor 是每个微服务向注册中心定时发送自己的一些信息

Springcloud微服务的启动日志中会出现
2020-03-04 10:19:24.215 INFO 15128 — [ main] com.netflix.discovery.DiscoveryClient : Starting heartbeat executor: renew interval is: 30

heartbeat executor 是每个微服务向注册中心定时发送自己的一些信息

启动过程

启动类上面加注解@DiscoveryClient
启动的时候会执行DiscoveryClient类中,下面的构造方法

@Inject
DiscoveryClient(ApplicationInfoManager applicationInfoManager, EurekaClientConfig config, AbstractDiscoveryClientOptionalArgs args, Provider<BackupRegistry> backupRegistryProvider, EndpointRandomizer endpointRandomizer) {.......................}

在这个构造方法中会创建一个发送心跳的线程池,就是以下代码

this.heartbeatExecutor = new ThreadPoolExecutor(1, this.clientConfig.getHeartbeatExecutorThreadPoolSize(), 0L, TimeUnit.SECONDS, new SynchronousQueue(), (new ThreadFactoryBuilder()).setNameFormat("DiscoveryClient-HeartbeatExecutor-%d").setDaemon(true).build());

this.clientConfig.getHeartbeatExecutorThreadPoolSize() 这个值默认是2,可以通过EurekaClientConfigBean 这个类查看默认值

同样是这个方法里面有一段代码,初始化调度任务
this.initScheduledTasks();

private void initScheduledTasks() {
    int renewalIntervalInSecs;
    int expBackOffBound;
    if (this.clientConfig.shouldFetchRegistry()) {
	//默认30s,可以从LeaseInfo类中查看默认值
        renewalIntervalInSecs = this.clientConfig.getRegistryFetchIntervalSeconds();         expBackOffBound = this.clientConfig.getCacheRefreshExecutorExponentialBackOffBound();
        this.scheduler.schedule(new TimedSupervisorTask("cacheRefresh", this.scheduler, this.cacheRefreshExecutor, renewalIntervalInSecs, TimeUnit.SECONDS, expBackOffBound, new DiscoveryClient.CacheRefreshThread()), (long)renewalIntervalInSecs, TimeUnit.SECONDS);
    }

    if (this.clientConfig.shouldRegisterWithEureka()) {
        renewalIntervalInSecs = this.instanceInfo.getLeaseInfo().getRenewalIntervalInSecs();
        expBackOffBound = this.clientConfig.getHeartbeatExecutorExponentialBackOffBound();
//输出日志        
logger.info("Starting heartbeat executor: renew interval is: {}", renewalIntervalInSecs);
//启动定时任务
        this.scheduler.schedule(new TimedSupervisorTask("heartbeat", this.scheduler, this.heartbeatExecutor, renewalIntervalInSecs, TimeUnit.SECONDS, expBackOffBound, new DiscoveryClient.HeartbeatThread()), (long)renewalIntervalInSecs, TimeUnit.SECONDS);
        this.instanceInfoReplicator = new InstanceInfoReplicator(this, this.instanceInfo, this.clientConfig.getInstanceInfoReplicationIntervalSeconds(), 2);
        this.statusChangeListener = new StatusChangeListener() {
            public String getId() {
                return "statusChangeListener";
            }

            public void notify(StatusChangeEvent statusChangeEvent) {
                if (InstanceStatus.DOWN != statusChangeEvent.getStatus() && InstanceStatus.DOWN != statusChangeEvent.getPreviousStatus()) {
                    DiscoveryClient.logger.info("Saw local status change event {}", statusChangeEvent);
                } else {
                    DiscoveryClient.logger.warn("Saw local status change event {}", statusChangeEvent);
                }

                DiscoveryClient.this.instanceInfoReplicator.onDemandUpdate();
            }
        };
        if (this.clientConfig.shouldOnDemandUpdateStatusChange()) {
            this.applicationInfoManager.registerStatusChangeListener(this.statusChangeListener);
        }

        this.instanceInfoReplicator.start(this.clientConfig.getInitialInstanceInfoReplicationIntervalSeconds());
    } else {
        logger.info("Not registering with Eureka server per configuration");
    }

}

定时通过DiscoveryClient类中的下面 renew()发送信息

boolean renew() {
    try {
        EurekaHttpResponse<InstanceInfo> httpResponse = this.eurekaTransport.registrationClient.sendHeartBeat(this.instanceInfo.getAppName(), this.instanceInfo.getId(), this.instanceInfo, (InstanceStatus)null);
        logger.debug("DiscoveryClient_{} - Heartbeat status: {}", this.appPathIdentifier, httpResponse.getStatusCode());
        if (httpResponse.getStatusCode() == Status.NOT_FOUND.getStatusCode()) {
            this.REREGISTER_COUNTER.increment();
            logger.info("DiscoveryClient_{} - Re-registering apps/{}", this.appPathIdentifier, this.instanceInfo.getAppName());
            long timestamp = this.instanceInfo.setIsDirtyWithTime();
            boolean success = this.register();
            if (success) {
                this.instanceInfo.unsetIsDirty(timestamp);
            }

            return success;
        } else {
            return httpResponse.getStatusCode() == Status.OK.getStatusCode();
        }
    } catch (Throwable var5) {
        logger.error("DiscoveryClient_{} - was unable to send heartbeat!", this.appPathIdentifier, var5);
        return false;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个简单的Qt代码示例,可以实现定时向12个服务端发送UDP心跳包数据,并检测服务端是否能够通讯。 ``` #include <QtNetwork> const int HEARTBEAT_INTERVAL = 1000; // 心跳包发送间隔,单位为毫秒 const int SERVER_PORT = 1234; // 服务端的端口号 class HeartbeatSender : public QObject { Q_OBJECT public: HeartbeatSender(QObject *parent = nullptr) : QObject(parent), m_udpSocket(this), m_timer(this) { // 绑定本地端口 m_udpSocket.bind(QHostAddress::AnyIPv4, 0); // 设置定时器 m_timer.setInterval(HEARTBEAT_INTERVAL); connect(&m_timer, &QTimer::timeout, this, &HeartbeatSender::sendHeartbeat); // 启动定时器 m_timer.start(); } private: QUdpSocket m_udpSocket; // UDP套接字 QTimer m_timer; // 定时器 void sendHeartbeat() { static quint16 seqNum = 0; // 发送序列号,每次递增1 QByteArray datagram; // 心跳包数据 QDataStream out(&datagram, QIODevice::WriteOnly); // 添加标识符和序列号到心跳包数据中 out << QString("Heartbeat") << seqNum++; // 发送心跳包数据到12个服务端 for (int i = 1; i <= 12; ++i) { QHostAddress serverAddr(QString("192.168.1.%1").arg(i)); m_udpSocket.writeDatagram(datagram, serverAddr, SERVER_PORT); // 等待服务端的响应,超时时间为1秒 if (m_udpSocket.waitForReadyRead(1000)) { // 收到服务端的响应,表示服务端能够通讯 qDebug() << "Received response from server" << serverAddr.toString(); } else { // 没有收到服务端的响应,表示服务端不能通讯 qDebug() << "Failed to receive response from server" << serverAddr.toString(); } } } }; int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); HeartbeatSender sender; return a.exec(); } #include "main.moc" ``` 在上面的代码中,我们定义了一个名为HeartbeatSender的类,用于发送UDP心跳包数据。在类的构造函数中,我们创建了一个QUdpSocket对象和一个QTimer对象,并将QTimer对象的timeout()信号连接到了sendHeartbeat()槽函数,以便定时发送UDP心跳包数据。 在sendHeartbeat()槽函数中,我们首先创建了一个QByteArray对象,并使用QDataStream将标识符和序列号添加到心跳包数据中。然后,我们使用QUdpSocket的writeDatagram()函数向12个服务端发送心跳包数据,并使用waitForReadyRead()函数等待服务端的响应。如果收到服务端的响应,则表示服务端能够通讯,否则表示服务端不能通讯。最后,我们在日志中记录服务端的IP地址和端口号。 在main()函数中,我们创建了一个HeartbeatSender对象,并启动Qt事件循环,以便处理事件和信号。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值