Backend Development 8 min read

How to Dynamically Manage Spring Cloud Gateway Routes with Nacos

This tutorial explains how to configure Spring Cloud Gateway, set up static routes, and then use Nacos for dynamic route management by adding dependencies, configuring bootstrap.yml, defining JSON route data, and implementing a listener bean to refresh routes without restarting the service.

Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
How to Dynamically Manage Spring Cloud Gateway Routes with Nacos

1. Introduction

Spring Cloud Gateway is a gateway server built on Spring Framework 5, Spring Boot 2 and Project Reactor. It provides routing, load balancing, security, rate limiting, fallback, and other features with high performance, high throughput and low latency.

Key features include a reactive programming model, multiple routing predicates (path, request parameters, headers, host), global and local filters, integration with Spring Cloud Security, and dynamic route and filter configuration.

What is Nacos?

Nacos is an open‑source platform for dynamic service discovery, configuration management and service management, designed to help users discover, configure and manage microservices. It supports service discovery, health monitoring, dynamic configuration, DNS, and metadata management.

2. Environment Configuration

Dependency Management

<code>&lt;properties&gt;
  &lt;java.version&gt;17&lt;/java.version&gt;
  &lt;spring-cloud.version&gt;2021.0.7&lt;/spring-cloud.version&gt;
  &lt;spring-cloud-alibaba.version&gt;2021.0.4.0&lt;/spring-cloud-alibaba.version&gt;
&lt;/properties&gt;
&lt;dependencies&gt;
  &lt;dependency&gt;
    &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
    &lt;artifactId&gt;spring-cloud-starter-gateway&lt;/artifactId&gt;
  &lt;/dependency&gt;
&lt;/dependencies&gt;
</code>

After adding the spring-cloud-starter-gateway dependency, static routes can be configured in the application.yml file.

3. Static Routing

<code>spring:
  cloud:
    gateway:
      metrics:
        enabled: true
      enabled: true
      discovery:
        locator:
          enabled: false
          lowerCaseServiceId: true
      default-filters:
      - StripPrefix=1
      routes:
      - id: rt-001
        uri: http://www.baidu.com
        predicates:
        - Path=/api-x/**
</code>

Accessing http://localhost:8188/api-x/ redirects to Baidu. Static routes require a restart to take effect, so dynamic management is needed.

4. Dynamic Routing with Nacos

Add Nacos‑related dependencies:

<code>&lt;dependency&gt;
  &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
  &lt;artifactId&gt;spring-cloud-loadbalancer&lt;/artifactId&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
  &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
  &lt;artifactId&gt;spring-cloud-starter-circuitbreaker-reactor-resilience4j&lt;/artifactId&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
  &lt;groupId&gt;com.alibaba.cloud&lt;/groupId&gt;
  &lt;artifactId&gt;spring-cloud-starter-alibaba-nacos-discovery&lt;/artifactId&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
  &lt;groupId&gt;com.alibaba.cloud&lt;/groupId&gt;
  &lt;artifactId&gt;spring-cloud-starter-alibaba-nacos-config&lt;/artifactId&gt;
&lt;/dependency&gt;
</code>

Create bootstrap.yml to configure Nacos connection and discovery:

<code>spring:
  application:
    name: cloud-gateway
---
spring:
  cloud:
    nacos:
      server-addr: localhost:8848
      username: nacos
      password: nacos
      discovery:
        enabled: true
        group: cloudApp
      config:
        file-extension: yaml
        group: cloudApp
</code>

Define route information as a JSON array (e.g., shared-routes.json ) in Nacos and add a bean to listen for configuration changes:

<code>@Component
public class DynamicRouteComponent {
  @Resource
  private InMemoryRouteDefinitionRepository routeDefinitionRepository;
  @Resource
  private ApplicationEventMulticaster multicaster;

  @PostConstruct
  public void init() throws Exception {
    ConfigService cs = this.ncm.getConfigService();
    cs.addListener("shared-routes.json", "CAPP", new Listener() {
      @Override
      public void receiveConfigInfo(String configInfo) {
        routeDefinitionRepository.getRouteDefinitions()
          .doOnNext(def -> routeDefinitionRepository.delete(Mono.just(def.getId())).subscribe())
          .subscribe();
        ObjectMapper mapper = new ObjectMapper();
        TypeReference<List<RouteDefinition>> ref = new TypeReference<>() {};
        try {
          List<RouteDefinition> routeDefinitions = mapper.readValue(configInfo, ref);
          routeDefinitions.forEach(rd -> routeDefinitionRepository.save(Mono.just(rd)).subscribe());
          multicaster.multicastEvent(new RefreshRoutesEvent(routeDefinitions));
        } catch (Exception e) {
          // handle parsing errors
        }
      }

      @Override
      public Executor getExecutor() {
        return new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
      }
    });
  }
}
</code>

The bean listens to changes in shared-routes.json and refreshes routes immediately; otherwise Nacos refreshes every 30 seconds by default.

With these steps, Spring Cloud Gateway routes can be managed dynamically through Nacos without restarting the service.

Nacos configuration screenshot
Nacos configuration screenshot
MicroservicesNacosSpring BootDynamic RoutingSpring Cloud Gateway
Spring Full-Stack Practical Cases
Written by

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.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.