All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.taotao.cloud.openfeign.loadbalancer.ServiceChangeNotifier Maven / Gradle / Ivy

There is a newer version: 2025.01
Show newest version
/*
 * Copyright (c) 2020-2030, Shuigedeng ([email protected] & https://blog.taotaocloud.top/).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.taotao.cloud.openfeign.loadbalancer;

import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.client.naming.event.InstancesChangeEvent;
import com.alibaba.nacos.common.notify.Event;
import com.alibaba.nacos.common.notify.NotifyCenter;
import com.alibaba.nacos.common.notify.listener.Subscriber;
import com.taotao.cloud.common.utils.log.LogUtils;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import org.springframework.cache.Cache;
import org.springframework.cloud.loadbalancer.cache.LoadBalancerCacheManager;
import org.springframework.cloud.loadbalancer.core.CachingServiceInstanceListSupplier;
import org.springframework.stereotype.Component;

/**
 * 服务变更监听
 *
 * 在使用 SpringCloud Gateway + Nacos的时候有没有遇到过服务刚上线偶尔会出现一段时间的503 Service Unavailable,
 * 或者服务下线后,下线服务仍然被调用的问题。而以上问题都是由于Ribbon或者LoadBalancer的默认处理策略有关,
 * 其中Ribbon默认是 30s 更新一次服务信息,LoadBalancer则是默认 35s 更新一次缓存。
 * 接下来本文讲解则如何通过监听Nacos 的服务变更事件来实时进行相关服务的更新,以实现服务的平滑上下线。
 */
@Component
public class ServiceChangeNotifier extends Subscriber {

    /**
     * 由于会有多个类型的 CacheManager bean, 这里的 defaultLoadBalancerCacheManager 名称不可修改
     */
    @Resource
    private LoadBalancerCacheManager defaultLoadBalancerCacheManager;

    @PostConstruct
    public void init() {
        // 注册当前自定义的订阅者以获取通知
        NotifyCenter.registerSubscriber(this);
    }

    @Override
    public void onEvent(InstancesChangeEvent event) {
        String serviceName = event.getServiceName();
        // 使用 dubbo 时包含 rpc 服务类会注册以 providers: 或者 consumers: 开头的服务
        // 由于不是正式的服务, 这里需要进行排除, 如果未使用 dubbo 则不需要该处理
        if (serviceName.contains(":")) {
            return;
        }
        // serviceName 格式为 groupName@@name
        String split = Constants.SERVICE_INFO_SPLITER;
        if (serviceName.contains(split)) {
            serviceName = serviceName.substring(serviceName.indexOf(split) + split.length());
        }
        LogUtils.info("服务上下线: {}", serviceName);
        // 手动更新服务列表
        Cache cache = defaultLoadBalancerCacheManager.getCache(
                CachingServiceInstanceListSupplier.SERVICE_INSTANCE_CACHE_NAME);
        if (cache != null) {
            cache.evictIfPresent(serviceName);
        }
    }

    @Override
    public Class subscribeType() {
        return InstancesChangeEvent.class;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy