Nacos源码系列—订阅机制的前因后果(下)

本文深入探讨Nacos的订阅机制,包括DefaultPublisher如何发布事件,以及本地缓存和故障处理的实现。DefaultPublisher作为事件发布者,使用阻塞队列进行事件传递。在故障处理中,ServiceInfoHolder负责服务信息处理,FailoverReactor进行故障恢复,通过定时任务写入磁盘备份。理解这些核心流程有助于更好地掌握Nacos的工作原理。
摘要由CSDN通过智能技术生成

事件发布

在上一节中我们讲解了在NotifyCenter中维护了事件名称和事件发布者的关系,而默认的事件发布者为DefaultPublisher,今天我们就来讲一下DefaultPublisher的事件发布的具体逻辑

首先我们来看一下DefaultPublisher的源码:

public class DefaultPublisher extends Thread implements EventPublisher {
    @Override
    public void init(Class<? extends Event> type, int bufferSize) {
        //守护线程
        setDaemon(true);
        //设置线程名
        setName("nacos.publisher-" + type.getName());
        this.eventType = type;
        this.queueMaxSize = bufferSize;
        //阻塞队列初始化
        this.queue = new ArrayBlockingQueue<>(bufferSize);
        //启动线程
        start();
    }
    
    @Override
    public synchronized void start() {
        if (!initialized) {
            // start just called once
            //启动run方法
            super.start();
            if (queueMaxSize == -1) {
                queueMaxSize = ringBufferSize;
            }
            initialized = true;
        }
    }
}

我们可以看到这个类继承自Thread,说明他是一个线程类,同时实现了EventPublisher说明他也是一个发布者,在init()中,是以守护线程的方式运作的,同时初始化了一个阻塞队列,最后调用start()启动线程。

在start()里面,其实就是启动run():

@Override
public void run() {
    openEventHandler();
}

   void openEventHandler() {
    try {

        // This variable is defined to resolve the problem which message overstock in the queue.
        int waitTimes = 60;
        // To ensure that messages are not lost, enable EventHandler when
        // waiting for the first Subscriber to register
        //死循环遍历,线程启动设置最大延迟60秒,用来解决消息积压问题
        for (; ; ) {
            if (shutdown || hasSubscriber() || waitTimes <= 0) {
                break;
            }
            ThreadUtils.sleep(1000L);
            waitTimes--;
        }
        //死循环从队列中取出event对象,同时通知订阅者(subscriber)执行event对象
        for (; ; ) {
            if (shutdown) {
                break;
            }
            final Event event = queue.take();
            receiveEvent(event);
            UPDATER.compareAndSet(this, lastEventSequence, Math.max(lastEventSequence, event.sequence()));
        }
    } catch (Throwable ex) {
        LOGGER.error("Event listener exception : ", ex);
    }
}

在上述代码中我们可以看到for (; ; )这个循环出现了两次,这个就是循环遍历(死循环),第一个死循环我们可以理解成延时效果,里面最大延时60秒,每隔一秒运行一次,判断(当前线程是否关闭、是否有订阅者、是否超过60秒)只要满足其中任意一个条件,跳出循环

第二个死循环,是我们业务逻辑处理,用来消费,从队列中取出event事件,然后通过receiveEvent()执行。

那么我们可以从队列中取出事件,那么这个事件又在哪一步注入进去的呢,我们还是在当前类里面,找到一个叫publish()的方法

@Override
public boolean publish(Event event) {
    checkIsStart();
    //向队列中插入元素
    boolean success = this.queue.offer(event);
    //判断是否插入成功
    if (!success) {
        LOGGER.warn("Unable to plug in due to interruption, synchronize sending time, event : {}", event);
        //失败直接执行
        receiveEvent(event);
        return true;
    }
    return true;
}

这个方法其实就是发布事件调用了publish往阻塞队列中存入事件,如果失败那么立即执行receiveEvent(),不在继续走队列方法

void receiveEvent(Event event) {
    final long currentEventSequence = event.sequence();

    if (!hasSubscriber()) {
        LOGGER.warn("[NotifyCenter] the {} is lost, because there is no subscriber.", event);
        return;
    }

    // Notification single event listener
    //循环遍历subscribers对象
    for (Subscriber subscriber : subscribers) {
        // Whether to ignore expiration events
        if (subscriber.ignoreExpireEvent() && lastEventSequence > currentEventSequence) {
            LOGGER.debug("[NotifyCenter] the {} is unacceptable to this subscriber, because had expire",
                    event.getClass());
            continue;
        }

        // Because unifying smartSubscriber and subscriber, so here need to think of compatibility.
        // Remove original judge part of codes.
        //通知订阅者执行event
        notifySubscriber(subscriber, event);
    }
}

而在receiveEvent()方法中,这里其实就是遍历的subscribers集合(订阅者),然后通过notifySubscriber() 通知订阅者方法,而这个subscribers集合就是在我们之前讲到的NacosN

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值