How to Dynamically Configure Routes in Spring Cloud Gateway with Zuul and Nacos
This guide explains how to locate and customize route locators in Spring Cloud Gateway by examining ZuulServerAutoConfiguration and SimpleRouteLocator, then shows how to implement a custom route locator using Nacos as a configuration center, including code examples and necessary YAML settings.
First, locate the routing code in the source.
1. Auto-configuration class: ZuulServerAutoConfiguration.java
This class contains the following code:
@Bean
@ConditionalOnMissingBean(SimpleRouteLocator.class)
public SimpleRouteLocator simpleRouteLocator() {
return new SimpleRouteLocator(this.server.getServlet().getContextPath(), this.zuulProperties);
}RouteLocator is the routing locator. If the system does not provide one, the built‑in SimpleRouteLocator is used.
2. Next, examine SimpleRouteLocator.java, which includes the method:
/**
* Compute a map of path pattern to route. The default is just a static map from the
* {@link ZuulProperties}, but subclasses can add dynamic calculations.
* @return map of Zuul routes
*/
protected Map<String, ZuulRoute> locateRoutes() {
LinkedHashMap<String, ZuulRoute> routesMap = new LinkedHashMap<>();
for (ZuulRoute route : this.properties.getRoutes().values()) {
routesMap.put(route.getPath(), route);
}
return routesMap;
}This method assembles the route information configured in the configuration file. By overriding locateRoutes, you can load routes dynamically.
3. Create a custom route locator, e.g., CustomizeRouteLocator.java (illustrated below).
4. Implement a concrete class that reads routing information from Nacos, the configuration center (illustrated below).
5. Define a custom bean to receive the route information stored in Nacos.
6. Add the necessary settings to bootstrap.yml:
spring:
application:
name: cloud-gateway
---
spring:
profiles:
active:
- devHere we configure the address of the Nacos service.
7. In Nacos, create a configuration file whose dataId follows the pattern
{spring.application.name}-{spring.profiles.active}.{fileExtension}, for example:
After these steps, the dynamic routing configuration is complete.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Spring Full-Stack Practical Cases
Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
