Upgrade Your Microservice Gateway: Auto‑Routing and Load Balancing with Spring Cloud Gateway + Nacos
This guide walks through upgrading a Spring Cloud Gateway by integrating Nacos as a service registry and configuration center, showing how to enable automatic request forwarding, dynamic route loading, and load‑balancing with step‑by‑step code examples and configuration files.
Background
In a previous article we covered the basic usage of Spring Cloud Gateway. This continuation explores advanced features such as integrating a service registry for automatic request forwarding and a configuration center for dynamic route loading.
Integrating the Service Registry
Spring Cloud Gateway can automatically proxy all services registered in a service registry. By registering the gateway itself with the registry, it creates dynamic routes using the service name as the target URI.
Example workflow diagram (omitted).
2.1 Build the Gateway Service
Copy an existing gateway-server project to a new module named gateway-nacos and add the Nacos discovery dependency in pom.xml:
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<spring-boot.version>2.2.5.RELEASE</spring-boot.version>
<spring-cloud.version>Hoxton.SR3</spring-cloud.version>
<spring-cloud-alibaba.version>2.2.3.RELEASE</spring-cloud-alibaba.version>
</properties>
<dependencies>
<!-- Spring Cloud Gateway component -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!-- Nacos discovery -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>${spring-cloud-alibaba.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>2.2 Modify Configuration Files
Update application.yaml to enable the discovery locator and point to the Nacos server:
server:
port: 8080
spring:
application:
name: gateway-nacos
cloud:
gateway:
# GatewayProperties
discovery:
locator:
enabled: true
url-expression: "'lb://' + serviceId"
nacos:
discovery:
server-addr: 127.0.0.1:8848 nacos.discovery.server-addr: Nacos as the Spring Cloud service registry. gateway.discovery.locator.enabled: Turn on integration with the service registry (default false). gateway.discovery.locator.url-expression: Spring EL expression that builds the target URI, default 'lb://' + serviceId.
Example of url-expression with services user-service and order-service:
spring:
cloud:
gateway:
routes:
- id: ReactiveCompositeDiscoveryClient_user-service
uri: lb://user-service
predicates:
- Path=/user-service/**
filters:
- RewritePath=/user-service/(?<remaining>.*),/${remaining}
- id: ReactiveCompositeDiscoveryClient_order-service
uri: lb://order-service
predicates:
- Path=/order-service/**
filters:
- RewritePath=/order-service/(?<remaining>.*),/${remaining}The lb:// prefix indicates load‑balanced forwarding to the target service instance.
2.3 Build a Business Microservice
Create a simple Spring Boot service named user-service and add the same Nacos discovery dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>Enable discovery with @EnableDiscoveryClient and expose a test endpoint:
@EnableDiscoveryClient
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "hello,我是用户服务";
}
}Configure the service port and Nacos address in application.properties:
spring.application.name=user-service
server.port=9010
spring.cloud.nacos.discovery.server-addr=127.0.0.1:88482.4 Service Test
Start both the gateway and user-service. Access the Nacos console to verify registration. The gateway automatically proxies requests using the pattern http://gateway-host:port/{serviceId}/path. For example, http://127.0.0.1:8080/user-service/hello forwards to the
user-service /helloendpoint.
When a service runs on multiple instances, the gateway performs round‑robin load balancing.
Integrating the Configuration Center
Sometimes different services require distinct routing rules or filters, and we may not want to expose every service through the gateway. By moving route definitions to a configuration center (Nacos), the gateway can load them dynamically.
3.1 Build a New Gateway Project
Copy the previous gateway-nacos project to gateway-application and add the Nacos config dependency:
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
</dependencies>3.2 Modify Configuration Files
Nacos configuration items are only effective in bootstrap.yaml. Rename application.yaml to bootstrap.yaml and add the following:
server:
port: 8080
spring:
application:
name: gateway-application
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
config:
server-addr: 127.0.0.1:8848
namespace:
group: DEFAULT_GROUP
name: gateway-config
file-extension: yamlThis defines a dataId gateway-config in the DEFAULT_GROUP namespace.
3.3 Publish Route Configuration to Nacos
In the Nacos console, create a configuration with dataId gateway-config and content:
spring:
cloud:
gateway:
routes:
- id: user-service
uri: lb://user-service
predicates:
- Path=/user-service/**
filters:
- RewritePath=/user-service/(?<remaining>.*),/${remaining}When the gateway starts, it automatically loads these routes and refreshes them on change.
3.4 Service Test
After restarting the gateway, accessing http://127.0.0.1:8080/user-service/hello returns the same response as before, confirming dynamic loading.
Modify the route in Nacos to change the path from /user-service to /user. After publishing, the request http://127.0.0.1:8080/user/hello succeeds, demonstrating that the gateway refreshed the rule without a restart.
Conclusion
Spring Cloud Gateway is a powerful gateway component. In microservice architectures it is typically paired with a service registry and a configuration center (such as Nacos) to achieve unified request forwarding, dynamic route management, and load balancing.
References
1. https://www.iocoder.cn/Spring-Cloud/Spring-Cloud-Gateway/?self
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.
Pan Zhi's Tech Notes
Sharing frontline internet R&D technology, dedicated to premium original content.
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.
