一、现象
发布新服务,然后在数据库配置了路由,使用服务路径访问404。然后重新发布新的服务,就可以继续访问得到
(1)配置了路由第一次访问
(2)重新发布后访问
二、分析
(1)查找RefreshableRouteLocator .refresh方法
@Component
public class NacosRouteLocator extends SimpleRouteLocator implements RefreshableRouteLocator {public NacosRouteLocator(ServerProperties serverProperties, ZuulProperties properties) {super(serverProperties.getServlet().getContextPath(), properties);}@Overridepublic void refresh() {doRefresh();}@Overrideprotected Map<String, ZuulProperties.ZuulRoute> locateRoutes() {//默认从配置文件中加载路由信息//return super.locateRoutes());//定制路由, 可以使用db的配置管理进行路由Map<String, ZuulProperties.ZuulRoute> routesMap = DbUtils.loadRoutes();return routesMap;}}
(2)ZuulHandlerMapping.setDirty方法
public class ZuulHandlerMapping extends AbstractUrlHandlerMapping {public void setDirty(boolean dirty) {this.dirty = dirty;if (this.routeLocator instanceof RefreshableRouteLocator) {((RefreshableRouteLocator) this.routeLocator).refresh();}}
}
(3)ZuulRefreshListener.reset方法
private static class ZuulRefreshListenerimplements ApplicationListener<ApplicationEvent> {@Autowiredprivate ZuulHandlerMapping zuulHandlerMapping;private HeartbeatMonitor heartbeatMonitor = new HeartbeatMonitor();@Overridepublic void onApplicationEvent(ApplicationEvent event) {if (event instanceof ContextRefreshedEvent|| event instanceof RefreshScopeRefreshedEvent|| event instanceof RoutesRefreshedEvent|| event instanceof InstanceRegisteredEvent) {reset();}else if (event instanceof ParentHeartbeatEvent) {ParentHeartbeatEvent e = (ParentHeartbeatEvent) event;resetIfNeeded(e.getValue());}else if (event instanceof HeartbeatEvent) {HeartbeatEvent e = (HeartbeatEvent) event;resetIfNeeded(e.getValue());}}private void resetIfNeeded(Object value) {if (this.heartbeatMonitor.update(value)) {reset();}}private void reset() {this.zuulHandlerMapping.setDirty(true);}}
(4)发现ApplicationEvent
@Overridepublic void onApplicationEvent(ApplicationEvent event) {if (event instanceof ContextRefreshedEvent|| event instanceof RefreshScopeRefreshedEvent|| event instanceof RoutesRefreshedEvent|| event instanceof InstanceRegisteredEvent) {reset();}else if (event instanceof ParentHeartbeatEvent) {ParentHeartbeatEvent e = (ParentHeartbeatEvent) event;resetIfNeeded(e.getValue());}else if (event instanceof HeartbeatEvent) {HeartbeatEvent e = (HeartbeatEvent) event;resetIfNeeded(e.getValue());}}
其中的实例注册事件InstanceRegisteredEvent会触发刷新路由。