当前位置: 首页 > news >正文

Spring Cloud Gateway静态路由实战:Maven多模块高效配置指南

在微服务架构中,API网关是系统的唯一入口。本文将展示如何通过Spring Cloud Gateway实现静态路由配置,采用Maven多模块管理,无需服务发现即可构建高效网关系统。

为什么选择静态路由?

动态路由依赖服务发现组件(如Nacos、Eureka),而静态路由具有以下优势:

  1. 零依赖:不依赖任何服务注册中心

  2. 高性能:减少服务发现网络开销

  3. 简单性:配置直观,易于维护

  4. 快速启动:适合中小型项目快速落地

项目结构设计

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: 8080spring:application:name: api-gatewaycloud:gateway:routes:# 用户服务路由- id: user-serviceuri: http://localhost:8081/predicates:- Path=/user-api/**filters:- StripPrefix=1# 订单服务路由- id: order-serviceuri: http://localhost:8082/predicates:- Path=/order-api/**filters:- StripPrefix=1# 配置httpclient连接池httpclient:pool:max-connections: 500acquire-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);@Overridepublic Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {ServerHttpRequest request = exchange.getRequest();logger.info("请求入口 => 方法: {}, 路径: {}, 来源: {}",request.getMethod(),request.getPath(),request.getRemoteAddress());return chain.filter(exchange);}@Overridepublic 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 {@Beanpublic 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: 8081spring: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: 8082spring: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
}

常见问题解决方案

  1. 路由不生效

    • 检查predicates路径是否正确

    • 验证后端服务是否运行

    • 查看网关日志中的DEBUG信息

  2. 跨域问题

    • 确保在网关层配置了CORS

    • 检查响应头是否包含Access-Control-Allow-Origin

  3. 请求头丢失

    • 使用AddRequestHeader过滤器明确添加需要的头

    • 检查是否有其他过滤器移除了请求头

  4. 性能瓶颈

    • 增加连接池大小

    • 调整Netty工作线程数

    • 启用响应压缩

结语

Spring Cloud Gateway作为Spring Cloud生态系统中的API网关,提供了强大而灵活的路由功能。通过本文的Maven多模块实现,您可以:

  1. 创建高效的静态路由网关

  2. 实现请求的集中管理和监控

  3. 添加全局过滤器和跨域支持

  4. 轻松扩展新的后端服务

静态网关配置虽然简单,但在中小型项目中能提供出色的性能和稳定性。当您的架构演进到需要动态服务发现时,可以平滑过渡到使用服务注册中心的动态路由方案。

http://www.lryc.cn/news/604543.html

相关文章:

  • 安全和AI方向的学习路线
  • docker常用命令集(6)
  • Shopify Draggable + Vue 3 完整指南:打造现代化拖拽交互体验
  • Apache Ignite 与 Spring Data 集成
  • 人工智能与安全:智能安防的创新与伦理边界
  • 把Java程序部署到本地Docker
  • 常见CMS
  • NVIDIA Isaac平台推动医疗AI机器人发展研究
  • Hyperchain 的分级权限体系如何应对潜在的安全威胁和攻击?
  • 关于Docker【常见问题解决方案】
  • 【问题未解决-寻求帮助】VS Code 中使用 Conda 环境,运行 Python 后 PowerShell 终端输出内容立即消失
  • 随笔之TDengine基准测试示例
  • 【开源】一款开源、跨平台的.NET WPF 通用权限开发框架 (ABP) ,功能全面、界面美观
  • 基于 Flask 和 MySQL 的期货数据分析系统
  • 【NLP舆情分析】基于python微博舆情分析可视化系统(flask+pandas+echarts) 视频教程 - 微博评论IP地图可视化分析实现
  • Vue + Flask 管理系统开发方案
  • 【Flask 基础 ①】 | 路由、参数与模板渲染
  • [Agent开发平台] API网关 | 业务领域 | DTO格式 | 分页令牌
  • FPGA实现CameraLink视频解码转SRIO与DSP交互,FPGA+DSP多核异构图像处理架构,提供2套工程源码和技术支持
  • 分布式搜索和分析引擎Elasticsearch实战指南
  • 图像处理中级篇 [1]—— 彩色照相机的效果与预处理
  • RAG实战指南 Day 28:RAG系统缓存与性能优化
  • 大模型对比评测:Qwen2.5 VS Gemini 2.0谁更能打?
  • 线性代数常见的解题方法
  • Apache Ignite中分布式信号量(Distributed Semaphore)的说明和使用示例
  • GitPython03-项目setup编译
  • Directory Opus 使用优化
  • CouchDB 从入门到精通:构建高效的分布式文档数据库
  • 2025年ESWA SCI1区TOP,强化学习多目标灰狼算法MOGWO-RL+分布式混合流水车间调度,深度解析+性能实测
  • C++与AI工具(土木工程)高效编程实战