当前位置:首页 >娱乐 >Spring Cloud Gateway + Nacos 实现服务上下线无缝切换 上无缝在删除负载均衡缓存后

Spring Cloud Gateway + Nacos 实现服务上下线无缝切换 上无缝在删除负载均衡缓存后

2024-06-29 08:07:03 [百科] 来源:避面尹邢网

Spring Cloud Gateway + Nacos 实现服务上下线无缝切换

作者:不才陈某 开发 前端 这里通过去监听 Nacos 实例刷新事件,现服下线一旦出现实例发生变化马上删除缓存。上无缝在删除负载均衡缓存后,切换Spring Cloud Gateway 在处理请求时发现没有缓存会重新拉取一遍服务列表,现服下线这样之后都是上无缝用的是最新的服务列表了,也就达到了我们动态感知上下线的切换目的。

​大家好,现服下线我是上无缝不才陈某~

最近知识星球的球友在学习星球中的《精尽Spring Cloud Alibaba》专栏提到一个问题,相信也有很多人在线上环境遇到过,切换或许也因此被批过:一个集群中有某个服务突然下线,现服下线但是上无缝网关还是会去请求这个实例,所以线上就报错了,切换报错信息如下图:

Spring Cloud Gateway + Nacos 实现服务上下线无缝切换 上无缝在删除负载均衡缓存后

图片

Spring Cloud Gateway + Nacos 实现服务上下线无缝切换 上无缝在删除负载均衡缓存后

究其原因到底为何呢?有没有一种靠谱的现服下线解决方案呢?别着急,往下看

Spring Cloud Gateway + Nacos 实现服务上下线无缝切换 上无缝在删除负载均衡缓存后

产生原因

Gateway中有个缓存 CachingRouteLocator ,上无缝而网关服务使用的切换是lb模式,服务在上线或者下线之后,未能及时刷新这个缓存,相应的源码如下:

public class CachingRouteLocator implements Ordered, RouteLocator,
ApplicationListener<RefreshRoutesEvent>, ApplicationEventPublisherAware {

private static final Log log = LogFactory.getLog(CachingRouteLocator.class);

private static final String CACHE_KEY = "routes";

private final RouteLocator delegate;

private final Flux<Route> routes;

private final Map<String, List> cache = new ConcurrentHashMap<>();

private ApplicationEventPublisher applicationEventPublisher;

public CachingRouteLocator(RouteLocator delegate) {
this.delegate = delegate;
routes = CacheFlux.lookup(cache, CACHE_KEY, Route.class)
.onCacheMissResume(this::fetch);
}

private Flux<Route> fetch() {
return this.delegate.getRoutes().sort(AnnotationAwareOrderComparator.INSTANCE);
}

@Override
public Flux<Route> getRoutes() {
return this.routes;
}

/**
* Clears the routes cache.
* @return routes flux
*/
public Flux<Route> refresh() {
this.cache.clear();
return this.routes;
}

@Override
public void onApplicationEvent(RefreshRoutesEvent event) {
try {
fetch().collect(Collectors.toList()).subscribe(list -> Flux.fromIterable(list)
.materialize().collect(Collectors.toList()).subscribe(signals -> {
applicationEventPublisher
.publishEvent(new RefreshRoutesResultEvent(this));
cache.put(CACHE_KEY, signals);
}, throwable -> handleRefreshError(throwable)));
}
catch (Throwable e) {
handleRefreshError(e);
}
}

private void handleRefreshError(Throwable throwable) {
if (log.isErrorEnabled()) {
log.error("Refresh routes error !!!", throwable);
}
applicationEventPublisher
.publishEvent(new RefreshRoutesResultEvent(this, throwable));
}

@Deprecated
/* for testing */ void handleRefresh() {
refresh();
}

@Override
public int getOrder() {
return 0;
}

@Override
public void setApplicationEventPublisher(
ApplicationEventPublisher applicationEventPublisher) {
this.applicationEventPublisher = applicationEventPublisher;
}
}

那么解决方案就自然能够想出来,只需要在服务下线时能够去实时的刷新这个缓存自然就解决了

解决方案

这里通过去监听 Nacos 实例刷新事件,一旦出现实例发生变化马上删除缓存。在删除负载均衡缓存后,Spring Cloud Gateway 在处理请求时发现没有缓存会重新拉取一遍服务列表,这样之后都是用的是最新的服务列表了,也就达到了我们动态感知上下线的目的。

代码如下:

@Component
@Slf4j
public class NacosInstancesChangeEventListener extends Subscriber<InstancesChangeEvent> {
@Resource
private CacheManager defaultLoadBalancerCacheManager;

@Override
public void onEvent(InstancesChangeEvent event) {
log.info("Spring Gateway 接收实例刷新事件:{ }, 开始刷新缓存", JacksonUtils.toJson(event));
Cache cache = defaultLoadBalancerCacheManager.getCache(SERVICE_INSTANCE_CACHE_NAME);
if (cache != null) {
cache.evict(event.getServiceName());
}
log.info("Spring Gateway 实例刷新完成");
}

@Override
public Class<? extends com.alibaba.nacos.common.notify.Event> subscribeType() {
return InstancesChangeEvent.class;
}
}

这里通过继承的方式监听 Nacos 的 InstancesChangeEvent​,在 onEvent 接收到实例刷新的信息后直接删除对应服务的负载均衡缓存,缓存的名字是定义在 Spring Gateway 的相关代码中的,直接引入即可,Cache 则是继承自 Spring Cache 接口,负载均衡缓存也继承了 Cache 接口,有了 Cache 接口就可以直接使用其接口定义的 evict 方法即可,而缓存的 key 名就则就是服务名,在 InstancesChangeEvent 中,通过 getServiceName 就可以得到服务名。

这里就不演示了,有兴趣的小伙伴可以测试一下

责任编辑:武晓燕 来源: 码猿技术专栏 Spring上下线缓存

(责任编辑:综合)

    推荐文章
    热点阅读