栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

spring cloud gateway+nacos 服务下线感知延迟,未及时出现503,请求依然转发到下线服务

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

spring cloud gateway+nacos 服务下线感知延迟,未及时出现503,请求依然转发到下线服务

spring cloud gateway服务下线感知延迟,未及时出现503
  • 1.场景描述
  • 2.分析
    • 2.1定位问题
  • 3.解决方案

本篇算是配合之前的一篇了。整体问题是gateway对下线服务感知延迟,之前那篇文章是从服务角度解决自身注销的问题(使用undertow,服务停止后nacos下线注销延迟问题)。本篇是解决gateway自身发现服务问题。

1.场景描述

注册中心使用的nacos,客户端版本1.4.1。
gateway版本3.0.1。
nacos服务下线(包含手动点下线和服务正常停机)gateway在短暂几秒内还回继续将流量转发到已下线的服务上导致500。过几秒之后恢复正常,响应码变成503。表面上看,应该是gateway服务没有及时发现服务的下线。

2.分析

日志级别调整到debug,发现通过netty发送的下线通知已经抵达gateway服务。这说明nacos注册中心和spring boot服务通讯和订阅是没问题的。
从转发的入口着手:ReactiveLoadBalancerClientFilter#choose 这个方法就是gateway转发时选择服务的

private Mono> choose(Request lbRequest, String serviceId,
			Set supportedLifecycleProcessors) {
		ReactorLoadBalancer loadBalancer = this.clientFactory.getInstance(serviceId,
				ReactorServiceInstanceLoadBalancer.class);
		if (loadBalancer == null) {
			throw new NotFoundException("No loadbalancer available for " + serviceId);
		}
		supportedLifecycleProcessors.forEach(lifecycle -> lifecycle.onStart(lbRequest));
		// 最后是通过ReactorLoadBalancer的实现进行选择
		return loadBalancer.choose(lbRequest);
	}

ReactorLoadBalancer是负载均衡的接口,提供了两个实现,一个随机获取,一个轮询。
默认是使用轮询实现(RoundRobinLoadBalancer)。
RoundRobinLoadBalancer中选择服务的实现逻辑

public Mono> choose(Request request) {
		ServiceInstanceListSupplier supplier = serviceInstanceListSupplierProvider
				.getIfAvailable(NoopServiceInstanceListSupplier::new);
		// 在这个get方法中返回了可选服务器的集合
		return supplier.get(request).next()
				.map(serviceInstances -> processInstanceResponse(supplier, serviceInstances));
	}

上面那个get的实现是:CachingServiceInstanceListSupplier#CachingServiceInstanceListSupplier这个类中提供的

public CachingServiceInstanceListSupplier(ServiceInstanceListSupplier delegate, CacheManager cacheManager) {
		super(delegate);
		this.serviceInstances = CacheFlux.lookup(key -> {
			// 这里发现有缓存!感觉目的地近了。
			Cache cache = cacheManager.getCache(SERVICE_INSTANCE_CACHE_NAME);
			....
				}).then());
	}
2.1定位问题

调试一下看看:

  • 服务A启动注册到nacos
  • gateway正常将/test/hello转发至服务A
  • 在nacos管理端让服务A下线
  • 立刻访问不停/test/hello
  • 最初几秒内发现gateway还是会把流量打到服务A
  • 之后正常响应503

在获取服务集群信息的地方打断点

public CachingServiceInstanceListSupplier(ServiceInstanceListSupplier delegate, CacheManager cacheManager) {
		super(delegate);
		this.serviceInstances = CacheFlux.lookup(key -> {
			// TODO: configurable cache name
			Cache cache = cacheManager.getCache(SERVICE_INSTANCE_CACHE_NAME);
			if (cache == null) {
				if (log.isErrorEnabled()) {
					log.error("Unable to find cache: " + SERVICE_INSTANCE_CACHE_NAME);
				}
				return Mono.empty();
			}
			// 在异常的时间段,这个list还是有信息。集合没内容之后开始响应503
			List list = cache.get(key, List.class);
			if (list == null || list.isEmpty()) {
				return Mono.empty();
			}
			return Flux.just(list).materialize().collectList();
		}
		...
	}

看来是这个缓存没有及时刷新的原因!后续找了一段时间,没找到刷新缓存的地方就放弃了。还是用笨方法先解决吧

3.解决方案

已经知道了问题所在,想办法解决就是了。
整体思路:在订阅nacos服务变化中进行功能拓展,刷新缓存。

三个类:
SubscribeConfig:进行订阅配置的入口
NacosSubscribe:订阅nacos的实现,用来发布订阅消息
NacosEventListener:消息处理的实现,在这里刷新缓存

SubscribeConfig:

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.NacosServiceManager;
import com.dong.server.gateway.subscribe.NacosSubscribe;
import com.dong.server.gateway.subscribe.NacosEventListener;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.cloud.loadbalancer.cache.LoadBalancerCacheManager;
import org.springframework.cloud.loadbalancer.config.LoadBalancerCacheAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;



@Configuration
@AutoConfigureAfter(LoadBalancerCacheAutoConfiguration.class)
public class SubscribeConfig {

    @Bean
    public NacosSubscribe getNacosSubscribe(NacosServiceManager nacosServiceManager, NacosDiscoveryProperties properties,LoadBalancerCacheManager loadBalancerCacheManager){
        return new NacosSubscribe(nacosServiceManager,properties,new NacosEventListener(loadBalancerCacheManager));
    }
}

NacosSubscribe

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.NacosServiceManager;
import com.alibaba.nacos.api.naming.NamingService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;

import java.net.URI;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;


@Slf4j
@AllArgsConstructor
public class NacosSubscribe implements ApplicationRunner {
    private NacosServiceManager nacosServiceManager;
    private NacosDiscoveryProperties properties;
    private NacosEventListener myEventListener;

    private Set getRouteServices(){
    	// TODO 这里返回自己要订阅的服务名称
        return new HashSet();
    }
    
@org.springframework.context.event.EventListener({RefreshRoutesEvent.class})
    public void subscribe() {
        NamingService namingService = nacosServiceManager
                .getNamingService(properties.getNacosProperties());
        try {
            Set services = getRouteServices();
            if(CollectionUtil.isNotEmpty(services)){
                for (String service : services) {
                    namingService.subscribe(service, properties.getGroup(),
                            null, myEventListener);
                }
            }
        } catch (Exception e) {
            log.error("namingService subscribe failed, properties:{}", properties, e);
        }
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        subscribe();
    }

}

NacosEventListener

import com.alibaba.cloud.nacos.discovery.NacosServiceDiscovery;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.naming.listener.Event;
import com.alibaba.nacos.api.naming.listener.EventListener;
import com.alibaba.nacos.api.naming.listener.NamingEvent;
import com.alibaba.nacos.api.naming.pojo.Instance;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.Cache;
import org.springframework.cloud.loadbalancer.cache.LoadBalancerCacheManager;
import org.springframework.cloud.loadbalancer.core.CachingServiceInstanceListSupplier;

import java.util.List;


@Slf4j
@AllArgsConstructor
public class NacosEventListener implements EventListener {

    private LoadBalancerCacheManager loadBalancerCacheManager;
    @Override
    public void onEvent(Event event) {
        try {
            if (event instanceof NamingEvent) {
                Cache cache = loadBalancerCacheManager.getCache(CachingServiceInstanceListSupplier.SERVICE_INSTANCE_CACHE_NAME);
                if(cache!=null){
                    NamingEvent namingEvent = ((NamingEvent) event);
                    String serviceName = namingEvent.getServiceName();
                    String[] split = serviceName.split(Constants.SERVICE_INFO_SPLITER);
                    String serviceId = split[1];
                    log.debug("收到更新服务消息:{}",serviceId);
                    List instances = namingEvent.getInstances();
                    cache.put(serviceId,  NacosServiceDiscovery.hostToServiceInstanceList(instances,serviceId));
                }
            }
        }catch (Exception e){
            log.error("处理nacos推送失败!",e);
        }
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/842669.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号