一、版本介紹
Nacos: 1.3.1
SpringCloud: 2021.0.2
SpringCloud gateway: 3.1.2
二、背景
- 微服務(wù)下線(xiàn)后,網(wǎng)關(guān)存在短時(shí)間內(nèi)轉(zhuǎn)發(fā)失效服務(wù),導(dǎo)致前端訪(fǎng)問(wèn)異常
- 微服務(wù)上線(xiàn)后,網(wǎng)關(guān)沒(méi)有及時(shí)刷新本地緩存的服務(wù),導(dǎo)致前端可能找不到服務(wù)實(shí)例
- nacos的主動(dòng)推送實(shí)例變化比網(wǎng)關(guān)自己拉取要及時(shí)的多
三、網(wǎng)關(guān)增加訂閱微服務(wù)實(shí)例變化的代碼
import static org.springframework.cloud.loadbalancer.core.CachingServiceInstanceListSupplier.SERVICE_INSTANCE_CACHE_NAME;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Component;
import com.alibaba.nacos.client.naming.event.InstancesChangeEvent;
import com.alibaba.nacos.common.notify.NotifyCenter;
import com.alibaba.nacos.common.notify.listener.Subscriber;
import com.alibaba.nacos.common.utils.JacksonUtils;
import lombok.extern.slf4j.Slf4j;
/**
* 訂閱nacos通知
* 接收nacos推送的微服務(wù)上下線(xiàn)實(shí)例信息
* @author
*
*/
@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("SpringCloud Gateway 接收微服務(wù)實(shí)例刷新事件:{}, 開(kāi)始刷新本地存儲(chǔ)的微服務(wù)實(shí)例信息的緩存", JacksonUtils.toJson(event));
Cache cache = defaultLoadBalancerCacheManager.getCache(SERVICE_INSTANCE_CACHE_NAME);
if (cache != null) {
cache.evict(event.getServiceName());
}
log.info("SpringCloud Gateway 實(shí)例刷新完成");
}
@Override
public Class<? extends com.alibaba.nacos.common.notify.Event> subscribeType() {
return InstancesChangeEvent.class;
}
}
一級(jí)增加配置使訂閱事件生效
cloud:
gateway:
discovery:
locator:
enabled: true # 默認(rèn)false,開(kāi)啟后可以通過(guò)ip:port/服務(wù)名稱(chēng)/接口地址進(jìn)行服務(wù)轉(zhuǎn)發(fā)
interval: 10000 # 設(shè)置定時(shí)拉取服務(wù)信息的時(shí)間間隔為10秒
此處配置注意點(diǎn):文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-716947.html
1、如果cloud.gateway.discovery.locator.enabled 設(shè)置為false,那么訂閱程序?qū)⑹詹坏絥acas推送的消息
2、如果不需要定時(shí)拉取,可以把interval的設(shè)置去掉文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-716947.html
到了這里,關(guān)于springcloud gateway實(shí)時(shí)監(jiān)聽(tīng)nacos微服務(wù)上下線(xiàn)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!