在微服务架构中,API网关是系统的唯一入口。本文将展示如何通过Spring Cloud Gateway实现静态路由配置,采用Maven多模块管理,无需服务发现即可构建高效网关系统。
为什么选择静态路由?
动态路由依赖服务发现组件(如Nacos、Eureka),而静态路由具有以下优势:
零依赖:不依赖任何服务注册中心
高性能:减少服务发现网络开销
简单性:配置直观,易于维护
快速启动:适合中小型项目快速落地
项目结构设计
parent-project(聚合工程)
├── pom.xml
├── user-service # 用户服务(8081)
├── order-service # 订单服务(8082)
└── api-gateway # 网关服务(8080) # 核心模块
一、父模块配置(聚合工程)
pom.xml - 统一管理依赖和版本
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.dafu</groupId>
<artifactId>parent-project</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<modules>
<module>user-service</module>
<module>api-gateway</module>
<module>order-service</module>
</modules>
<properties>
<java.version>17</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<springboot.version>2.6.3</springboot.version>
</properties>
<dependencyManagement>
<dependencies>
<!-- 引入springboot依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${springboot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- Spring Cloud 依赖管理 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>2021.0.1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
</project>
二、网关模块(核心实现)
1. 依赖配置(api-gateway/pom.xml)
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.dafu</groupId>
<artifactId>parent-project</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>api-gateway</artifactId>
<properties>
<java.version>17</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- Gateway 核心依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
</dependencies>
</project>
2. 静态路由配置(application.yml)
server:
port: 8080
spring:
application:
name: api-gateway
cloud:
gateway:
routes:
# 用户服务路由
- id: user-service
uri: http://localhost:8081/
predicates:
- Path=/user-api/**
filters:
- StripPrefix=1
# 订单服务路由
- id: order-service
uri: http://localhost:8082/
predicates:
- Path=/order-api/**
filters:
- StripPrefix=1
# 配置httpclient连接池
httpclient:
pool:
max-connections: 500
acquire-timeout: 2000
3. 全局过滤器(RequestLoggingFilter.java)
package com.dafu.filter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
/**
* @author:DaFu
* @date: 2025/7/30 9:06
*/
@Component
public class RequestLoggingFilter implements GlobalFilter, Ordered {
private static final Logger logger = LoggerFactory.getLogger(RequestLoggingFilter.class);
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
logger.info("请求入口 => 方法: {}, 路径: {}, 来源: {}",
request.getMethod(),
request.getPath(),
request.getRemoteAddress());
return chain.filter(exchange);
}
@Override
public int getOrder() {
return Ordered.HIGHEST_PRECEDENCE;
}
}
4. 跨域配置(CorsConfig.java)
package com.dafu.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import java.util.Arrays;
/**
* @author:DaFu
* @date: 2025/7/30 9:18
*/
@Configuration
public class CorsConfig {
@Bean
public CorsWebFilter corsWebFilter() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(Arrays.asList("*"));
config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
config.setAllowedHeaders(Arrays.asList("*"));
config.setExposedHeaders(Arrays.asList("X-Gateway-Response", "X-Request-ID"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return new CorsWebFilter(source);
}
}
三、用户服务模块(示例服务)
1. 服务配置(application.yml)
server:
port: 8081
spring:
application:
name: user-service
2. 依赖配置(user-service/pom.xml)
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.dafu</groupId>
<artifactId>parent-project</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>user-service</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>
3. 控制器实现(UserController.java)
package com.dafu.controller;
import org.springframework.web.bind.annotation.*;
/**
* @author:DaFu
* @date: 2025/7/29 15:19
*/
@RequestMapping("/users")
@RestController
public class UserController {
@GetMapping("/{id}")
public UserResponse getUser(@PathVariable Long id) {
return new UserResponse(
id,
"用户" + id,
"user" + id + "@example.com"
);
}
public static class UserResponse {
Long id;
String name;
String email;
public UserResponse(Long id, String name, String email) {
this.id = id;
this.name = name;
this.email = email;
}
// getter and setter
}
}
三、订单服务模块(示例服务)
1. 服务配置(application.yml)
server:
port: 8082
spring:
application:
name: order-service
2. 依赖配置(user-service/pom.xml)
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.dafu</groupId>
<artifactId>parent-project</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>order-service</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>
3. 控制器实现(OrderController.java)
package com.dafu.controller;
import org.springframework.web.bind.annotation.*;
/**
* @author:DaFu
* @date: 2025/7/29 15:19
*/
@RequestMapping("/order")
@RestController
public class OrderController {
@GetMapping("/{id}")
public OrderResponse getProduct(
@PathVariable Long id) {
return new OrderResponse(
id,
"订单" + id,
99.99 + id
);
}
public static class OrderResponse {
Long id;
String name;
double price;
public OrderResponse(Long id, String name, double price) {
this.id = id;
this.name = name;
this.price = price;
}
// getter and setter
}
}
启动与测试
分别启动
api-gateway
order-service
user-service
测试网关路由
请求用户服务路由测试
curl http://localhost:8080/user-api/users/8
将被路由到
GET http://localhost:8081/users/8
响应示例:
{
"id": 8,
"name": "用户8",
"email": "user8@example.com"
}
产品服务路由测试
curl http://localhost:8080/order-api/order/99
将被路由到
http://localhost:8082/order/99
响应示例:
{
"id": 99,
"name": "订单99",
"price": 198.99
}
常见问题解决方案
路由不生效:
检查predicates路径是否正确
验证后端服务是否运行
查看网关日志中的DEBUG信息
跨域问题:
确保在网关层配置了CORS
检查响应头是否包含Access-Control-Allow-Origin
请求头丢失:
使用AddRequestHeader过滤器明确添加需要的头
检查是否有其他过滤器移除了请求头
性能瓶颈:
增加连接池大小
调整Netty工作线程数
启用响应压缩
结语
Spring Cloud Gateway作为Spring Cloud生态系统中的API网关,提供了强大而灵活的路由功能。通过本文的Maven多模块实现,您可以:
创建高效的静态路由网关
实现请求的集中管理和监控
添加全局过滤器和跨域支持
轻松扩展新的后端服务
静态网关配置虽然简单,但在中小型项目中能提供出色的性能和稳定性。当您的架构演进到需要动态服务发现时,可以平滑过渡到使用服务注册中心的动态路由方案。