## 添加微服务注册成功刷新nacos缓存;

This commit is contained in:
cabbage 2025-04-28 17:42:50 +08:00
parent 5190f2e471
commit 7e1492970e
1 changed files with 43 additions and 0 deletions

View File

@ -0,0 +1,43 @@
package com.hzs.listener;
import com.alibaba.nacos.client.naming.event.InstancesChangeEvent;
import com.alibaba.nacos.common.notify.NotifyCenter;
import com.alibaba.nacos.common.notify.listener.Subscriber;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cloud.loadbalancer.core.CachingServiceInstanceListSupplier;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
@Component
@Slf4j
public class NacosInstancesChangeEventListener extends Subscriber<InstancesChangeEvent> {
@Resource
private CacheManager defaultLoadBalancerCacheManager;
@PostConstruct
public void registerToNotifyCenter(){
NotifyCenter.registerSubscriber(this);
}
@Override
public void onEvent(InstancesChangeEvent event) {
log.info("scm 接收微服务刷新事件:{}, 开始刷新本地存储的微服务缓存", event.getServiceName());
Cache cache = defaultLoadBalancerCacheManager.getCache(CachingServiceInstanceListSupplier.SERVICE_INSTANCE_CACHE_NAME);
if (cache != null) {
cache.evict(event.getServiceName());
log.info("{} 微服务刷新", event.getServiceName());
}
log.info("scm 微服务缓存刷新完成");
}
@Override
public Class<? extends com.alibaba.nacos.common.notify.Event> subscribeType() {
return InstancesChangeEvent.class;
}
}