Zuul implements dynamic routing and related source code analysis

Regarding how zuul implements dynamic routing, the great god has written a blog to explain it in detail. I will not repeat it here. The article address: Spring Cloud Zuul implements dynamic routing. Let's start with the last question of this article. The author implements dynamic refresh routing at the end. The rules say: Why not manually reload Locator.dorefresh yourself? Do you have to use events to refresh? This involves the workflow of the internal zuul components, not just a variable of the Locator itself, but you have to look at the source code for details. Let's analyze the source code of zuul to see why we do this?

To explain zuul's event-driven model clearly, you have to know spring's event-driven model, because the implementation of zuul is realized by using spring's event-driven model. Let's take a look at the event model diagram provided by spring:

There is such a listener ZuulRefreshListener that implements ApplicationListener in zuul. The code is as follows:

private static class ZuulRefreshListener implements ApplicationListener<ApplicationEvent> {

 

        @Autowired

        private ZuulHandlerMapping zuulHandlerMapping;

 

        private HeartbeatMonitor heartbeatMonitor = new HeartbeatMonitor();

 

        @Override

        public void onApplicationEvent(ApplicationEvent event) {

            if (event instanceof ContextRefreshedEvent

                    || event instanceof RefreshScopeRefreshedEvent

                    || event instanceof RoutesRefreshedEvent) {

                this.zuulHandlerMapping.setDirty(true);

            }

            else if (event instanceof HeartbeatEvent) {

                if (this.heartbeatMonitor.update(((HeartbeatEvent) event).getValue())) {

                    this.zuulHandlerMapping.setDirty(true);

                }

            }

        }

 

    }

It can be seen that this.zuulHandlerMapping.setDirty(true) will be executed when the ContextRefreshedEvent and RoutesRefreshedEvent events occur;

public void setDirty(boolean dirty) {

        this.dirty = dirty;

        if (this.routeLocator instanceof RefreshableRouteLocator) {

            ((RefreshableRouteLocator) this.routeLocator).refresh();

        }

    }

In this way, the routing rules are refreshed after the spring container is started. Therefore, if we want to actively refresh the routing rules, we only need to publish a RoutesRefreshedEvent event, the code is as follows

 

public void refreshRoute() {

        RoutesRefreshedEvent routesRefreshedEvent = new RoutesRefreshedEvent(routeLocator);

        this.publisher.publishEvent(routesRefreshedEvent);

        logger.info("刷新了路由规则......");

    }

 

 

http://blog.csdn.net/bigkylin/article/details/72626506

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326993601&siteId=291194637