当前位置: 首页 > 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.xdnf.cn/news/1212949.html

相关文章:

  • ‌CASE WHEN THEN ELSE END‌
  • YOLO-01目标检测基础
  • 【Rust多进程】征服CPU的艺术:Rust多进程实战指南
  • 力扣热题100-------74.搜索二维矩阵
  • SpringBoot 整合 自定义MongoDB
  • Flutter封装模板及最佳实践
  • CVAE 回顾版
  • STM32学习记录--Day3
  • gaussdb demo示例
  • 大语言模型(LLM)技术架构与工程实践:从原理到部署
  • 深入剖析 Spark Shuffle 机制:从原理到实战优化
  • 智能矿山综合管控平台
  • 非凸科技受邀出席第九届AIFOF投资创新发展论坛
  • 剧本杀系统 App 开发:科技赋能,重塑剧本杀游戏体验
  • forge篇——配置
  • SpringBoot+Three.js打造3D看房系统
  • 光伏气象监测系统:当阳光遇见科技
  • 让科技之光,温暖银龄岁月——智绅科技“智慧养老进社区”星城国际站温情纪实
  • 《CLIP改进工作串讲》论文精读笔记
  • Shopify Draggable + Vue 3 完整指南:打造现代化拖拽交互体验
  • JVM——内存布局、类加载机制及垃圾回收机制
  • Spring AI 海运管理应用
  • SpringBoot收尾+myBatis plus
  • 2025年6月数据挖掘顶刊TKDE研究热点有哪些?
  • DDD中的核心权衡:模型纯度与逻辑完整性
  • IO复用实现并发服务器
  • 【音视频】WebRTC 开发环境搭建-Web端
  • 服务器与电脑主机的区别,普通电脑可以当作服务器用吗?
  • Python 程序设计讲义(36):字符串的处理方法——去除字符串头尾字符:strip() 方法、lstrip() 方法与rstrip() 方法
  • 原生微信小程序实现语音转文字搜索---同声传译