生产级 Spring Cloud Alibaba 网关最佳实践指南
liuian 2025-09-13 04:03 2 浏览
Spring Boot + Spring Cloud Gateway + Nacos + Sentinel 网关最佳实践指南
在微服务架构中,API 网关是流量的统一入口。本文将结合 Spring Boot、Spring Cloud Gateway 与 Spring Cloud Alibaba(Nacos、Sentinel),为你构建一个高性能、可扩展、可观测的网关解决方案。
一、为什么是这套组合?
- Spring Cloud Gateway(Spring 官方)
基于响应式 WebFlux 的高性能 API 网关,支持路由、负载均衡、过滤器链等。 - Nacos(Spring Cloud Alibaba 提供)
服务发现 + 配置中心。Gateway 可从 Nacos 动态获取服务实例和路由配置。 - Sentinel(Spring Cloud Alibaba 提供)
提供流量控制、熔断降级、系统保护,保护下游服务。
因此典型组合是:
Gateway (Spring) + Nacos (注册/配置中心) + Sentinel (流控保护)
二、项目初始化
1. pom.xml 依赖
<properties>
<java.version>17</java.version>
<spring-boot.version>3.2.4</spring-boot.version>
<spring-cloud.version>2023.0.1</spring-cloud.version>
<spring-cloud-alibaba.version>2023.0.1.0</spring-cloud-alibaba.version>
</properties>
<dependencyManagement>
<dependencies>
<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>
<dependencies>
<!-- Spring Cloud Gateway -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!-- Nacos 服务发现 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- Sentinel 网关流控 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<!-- Sentinel 持久化到 Nacos(可选) -->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-nacos</artifactId>
</dependency>
</dependencies>
三、配置文件 application.yml
server:
port: 8080
spring:
application:
name: api-gateway
cloud:
nacos:
discovery:
server-addr: 192.168.1.100:8848
namespace: public
group: DEFAULT_GROUP
gateway:
discovery:
locator:
enabled: false # 推荐关闭自动发现,使用自定义路由
routes:
- id: user-service-route
uri: lb://user-service
predicates:
- Path=/api/users/**
filters:
- StripPrefix=1
- id: order-service-route
uri: lb://order-service
predicates:
- Path=/api/orders/**
filters:
- StripPrefix=1
sentinel:
eager: true
transport:
dashboard: localhost:8088
datasource:
ds1:
nacos:
server-addr: ${spring.cloud.nacos.discovery.server-addr}
dataId: ${spring.application.name}-gateway-flow-rules
groupId: SENTINEL_GROUP
rule-type: gw-flow
四、主启动类
@SpringBootApplication
@EnableDiscoveryClient
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
}
五、接入 Sentinel
- 启动 Sentinel Dashboard:
java -Dserver.port=8088 -Dcsp.sentinel.dashboard.server=localhost:8088 -jar sentinel-dashboard.jar
- 访问 http://localhost:8088,默认账号密码 sentinel/sentinel
- 触发路由后,控制台会出现 api-gateway 应用
- 在控制台上配置网关 流控规则,并可持久化到 Nacos
六、自定义全局过滤器(鉴权)
@Component
@Slf4j
public class AuthGlobalFilter implements GlobalFilter, Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
String token = exchange.getRequest().getHeaders().getFirst("Authorization");
if (token == null) {
exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
return exchange.getResponse().setComplete();
}
return chain.filter(exchange.mutate()
.request(builder -> builder.header("X-User-Id", "123"))
.build());
}
@Override
public int getOrder() {
return 0;
}
}
七、生产环境优化建议
- 路由动态刷新
- 使用 Nacos 配置中心托管 spring.cloud.gateway.routes,实现无重启动态更新。
- 灰度发布
- 使用自定义 Filter,根据 Header、版本号、用户ID 等进行灰度流量路由。
- 统一鉴权
- 建议集成 JWT 校验,支持单点登录(SSO)或 OAuth2。
- 监控与日志
- 接入 Prometheus + Grafana,结合 Sleuth/Zipkin 实现全链路追踪。
- Sentinel 最佳实践
- 规则持久化到 Nacos,避免重启丢失。常用规则:
- API 分组限流
- 服务粒度限流
- 熔断降级
- Nacos 高可用
- 至少 3 节点集群,配置 MySQL 存储,防止单点故障。
八、整体架构图
┌───────────┐
│ Client │
└─────▲─────┘
│
▼
┌──────────────────────┐
│ Spring Cloud Gateway │ ← 全局入口,鉴权、限流、路由
└───▲───────────────┘
│ ▲
│ │
▼ │
┌────────┐ │ ┌──────────┐
│ Nacos │──┘ │ Sentinel │
│服务注册│ │ 流量控制 │
└────────┘ └──────────┘
│
▼
┌───────────┐ ┌───────────┐
│ user-svc │ │ order-svc │ ← 微服务
└───────────┘ └───────────┘
九、总结
- Spring Cloud Gateway:核心流量入口,负责路由、过滤器链
- Nacos:服务发现 + 配置中心,支撑动态路由和服务注册
- Sentinel:网关限流、熔断、系统保护
- 优化实践:动态路由、灰度发布、统一鉴权、全链路监控、持久化规则
这套组合已经成为国内 Java 微服务最主流、最成熟的网关解决方案。
完整代码仓库结构 整理出来,包含 gateway、user-service、order-service 三个服务,搭建一个最小可运行的 Spring Cloud Alibaba 网关示例。
示例项目结构
sca-gateway-demo/
├── gateway/ # Spring Cloud Gateway 网关服务
│ ├── pom.xml
│ └── src/main/java/com/example/gateway/
│ ├── GatewayApplication.java
│ └── filter/
│ └── AuthGlobalFilter.java
│ └── src/main/resources/
│ └── application.yml
│
├── user-service/ # 用户服务
│ ├── pom.xml
│ └── src/main/java/com/example/user/
│ ├── UserServiceApplication.java
│ └── controller/
│ └── UserController.java
│ └── src/main/resources/
│ └── application.yml
│
├── order-service/ # 订单服务
│ ├── pom.xml
│ └── src/main/java/com/example/order/
│ ├── OrderServiceApplication.java
│ └── controller/
│ └── OrderController.java
│ └── src/main/resources/
│ └── application.yml
│
└── pom.xml # 父 POM,统一依赖管理
父项目 pom.xml
<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.example</groupId>
<artifactId>sca-gateway-demo</artifactId>
<version>1.0.0</version>
<packaging>pom</packaging>
<modules>
<module>gateway</module>
<module>user-service</module>
<module>order-service</module>
</modules>
<properties>
<java.version>17</java.version>
<spring-boot.version>3.2.4</spring-boot.version>
<spring-cloud.version>2023.0.1</spring-cloud.version>
<spring-cloud-alibaba.version>2023.0.1.0</spring-cloud-alibaba.version>
</properties>
<dependencyManagement>
<dependencies>
<!-- Spring Boot -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- Spring Cloud -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- Spring Cloud Alibaba -->
<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>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
Gateway 服务
GatewayApplication.java
@SpringBootApplication
@EnableDiscoveryClient
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
}
AuthGlobalFilter.java
@Component
@Slf4j
public class AuthGlobalFilter implements GlobalFilter, Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
String token = exchange.getRequest().getHeaders().getFirst("Authorization");
if (token == null) {
exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
return exchange.getResponse().setComplete();
}
return chain.filter(exchange.mutate()
.request(builder -> builder.header("X-User-Id", "123"))
.build());
}
@Override
public int getOrder() {
return 0;
}
}
application.yml
server:
port: 8080
spring:
application:
name: api-gateway
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
gateway:
routes:
- id: user-service
uri: lb://user-service
predicates:
- Path=/api/users/**
filters:
- StripPrefix=1
- id: order-service
uri: lb://order-service
predicates:
- Path=/api/orders/**
filters:
- StripPrefix=1
User Service
UserServiceApplication.java
@SpringBootApplication
@EnableDiscoveryClient
@RestController
@RequestMapping("/users")
public class UserServiceApplication {
public static void main(String[] args) {
SpringApplication.run(UserServiceApplication.class, args);
}
@GetMapping("/{id}")
public String getUser(@PathVariable String id) {
return "User-" + id;
}
}
application.yml
server:
port: 8081
spring:
application:
name: user-service
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
Order Service
OrderServiceApplication.java
@SpringBootApplication
@EnableDiscoveryClient
@RestController
@RequestMapping("/orders")
public class OrderServiceApplication {
public static void main(String[] args) {
SpringApplication.run(OrderServiceApplication.class, args);
}
@GetMapping("/{id}")
public String getOrder(@PathVariable String id) {
return "Order-" + id;
}
}
application.yml
server:
port: 8082
spring:
application:
name: order-service
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
启动步骤
- 启动 Nacos
sh startup.sh -m standalone
默认地址
http://127.0.0.1:8848/nacos
- 启动三个服务
- user-service(端口 8081)
- order-service(端口 8082)
- gateway(端口 8080)
- 测试访问
- http://localhost:8080/api/users/1 → 通过网关访问 user-service
- http://localhost:8080/api/orders/99 → 通过网关访问 order-service
相关推荐
- Python 中 必须掌握的 20 个核心函数——items()函数
-
items()是Python字典对象的方法,用于返回字典中所有键值对的视图对象。它提供了对字典完整内容的高效访问和操作。一、items()的基本用法1.1方法签名dict.items()返回:字典键...
- Python字典:键值对的艺术_python字典的用法
-
字典(dict)是Python的核心数据结构之一,与列表同属可变序列,但采用完全不同的存储方式:定义方式:使用花括号{}(列表使用方括号[])存储结构:以键值对(key-valuepair)...
- python字典中如何添加键值对_python怎么往字典里添加键
-
添加键值对首先定义一个空字典1>>>dic={}直接对字典中不存在的key进行赋值来添加123>>>dic['name']='zhangsan'>>...
- Spring Boot @ConfigurationProperties 详解与 Nacos 配置中心集成
-
本文将深入探讨SpringBoot中@ConfigurationProperties的详细用法,包括其语法细节、类型转换、复合类型处理、数据校验,以及与Nacos配置中心的集成方式。通过...
- Dubbo概述_dubbo工作原理和机制
-
什么是RPCRPC是RemoteProcedureCall的缩写翻译为:远程过程调用目标是为了实现两台(多台)计算机\服务器,互相调用方法\通信的解决方案RPC的概念主要定义了两部分内容序列化协...
- 再见 Feign!推荐一款微服务间调用神器,跟 SpringCloud 绝配
-
在微服务项目中,如果我们想实现服务间调用,一般会选择Feign。之前介绍过一款HTTP客户端工具Retrofit,配合SpringBoot非常好用!其实Retrofit不仅支持普通的HTTP调用,还能...
- SpringGateway 网关_spring 网关的作用
-
奈非框架简介早期(2020年前)奈非提供的微服务组件和框架受到了很多开发者的欢迎这些框架和SpringCloudAlibaba的对应关系我们要知道Nacos对应Eureka都是注册中心Dubbo...
- Sentinel 限流详解-Sentinel与OpenFeign服务熔断那些事
-
SentinelResource我们使用到过这个注解,我们需要了解的是其中两个属性:value:资源名称,必填且唯一。@SentinelResource(value="test/get...
- 超详细MPLS学习指南 手把手带你实现IP与二层网络的无缝融合
-
大家晚上好,我是小老虎,今天的文章有点长,但是都是干货,耐心看下去,不会让你失望的哦!随着ASIC技术的发展,路由查找速度已经不是阻碍网络发展的瓶颈。这使得MPLS在提高转发速度方面不再具备明显的优势...
- Cisco 尝试配置MPLS-V.P.N从开始到放弃
-
本人第一次接触这个协议,所以打算分两篇进行学习和记录,本文枯燥预警,配置命令在下一篇全为定义,其也是算我毕业设计的一个小挑战。新概念重点备注为什么选择该协议IPSecVPN都属于传统VPN传统VP...
- MFC -- 网络通信编程_mfc编程教程
-
要买东西的时候,店家常常说,你要是真心买的,还能给你便宜,你看真心就是不怎么值钱。。。----网易云热评一、创建服务端1、新建一个控制台应用程序,添加源文件server2、添加代码框架#includ...
- 35W快充?2TB存储?iPhone14爆料汇总,不要再漫天吹15了
-
iPhone14都还没发布,关于iPhone15的消息却已经漫天飞,故加紧整理了关于iPhone14目前已爆出的消息。本文将从机型、刘海、屏幕、存储、芯片、拍照、信号、机身材质、充电口、快充、配色、价...
- SpringCloud Alibaba(四) - Nacos 配置中心
-
1、环境搭建1.1依赖<!--nacos注册中心注解@EnableDiscoveryClient--><dependency><groupI...
- Nacos注册中心最全详解(图文全面总结)
-
Nacos注册中心是微服务的核心组件,也是大厂经常考察的内容,下面我就重点来详解Nacos注册中心@mikechen本篇已收于mikechen原创超30万字《阿里架构师进阶专题合集》里面。微服务注册中...
- 网络技术领域端口号备忘录,受益匪浅 !
-
你好,这里是网络技术联盟站,我是瑞哥。网络端口是计算机网络中用于区分不同应用程序和服务的标识符。每个端口号都是一个16位的数字,范围从0到65535。网络端口的主要功能是帮助网络设备(如计算机和服务器...
- 一周热门
-
-
【验证码逆向专栏】vaptcha 手势验证码逆向分析
-
Python实现人事自动打卡,再也不会被批评
-
Psutil + Flask + Pyecharts + Bootstrap 开发动态可视化系统监控
-
一个解决支持HTML/CSS/JS网页转PDF(高质量)的终极解决方案
-
再见Swagger UI 国人开源了一款超好用的 API 文档生成框架,真香
-
网页转成pdf文件的经验分享 网页转成pdf文件的经验分享怎么弄
-
C++ std::vector 简介
-
飞牛OS入门安装遇到问题,如何解决?
-
系统C盘清理:微信PC端文件清理,扩大C盘可用空间步骤
-
10款高性能NAS丨双十一必看,轻松搞定虚拟机、Docker、软路由
-
- 最近发表
-
- Python 中 必须掌握的 20 个核心函数——items()函数
- Python字典:键值对的艺术_python字典的用法
- python字典中如何添加键值对_python怎么往字典里添加键
- Spring Boot @ConfigurationProperties 详解与 Nacos 配置中心集成
- Dubbo概述_dubbo工作原理和机制
- 再见 Feign!推荐一款微服务间调用神器,跟 SpringCloud 绝配
- SpringGateway 网关_spring 网关的作用
- Sentinel 限流详解-Sentinel与OpenFeign服务熔断那些事
- 超详细MPLS学习指南 手把手带你实现IP与二层网络的无缝融合
- Cisco 尝试配置MPLS-V.P.N从开始到放弃
- 标签列表
-
- python判断字典是否为空 (50)
- crontab每周一执行 (48)
- aes和des区别 (43)
- bash脚本和shell脚本的区别 (35)
- canvas库 (33)
- dataframe筛选满足条件的行 (35)
- gitlab日志 (33)
- lua xpcall (36)
- blob转json (33)
- python判断是否在列表中 (34)
- python html转pdf (36)
- 安装指定版本npm (37)
- idea搜索jar包内容 (33)
- css鼠标悬停出现隐藏的文字 (34)
- linux nacos启动命令 (33)
- gitlab 日志 (36)
- adb pull (37)
- python判断元素在不在列表里 (34)
- python 字典删除元素 (34)
- vscode切换git分支 (35)
- python bytes转16进制 (35)
- grep前后几行 (34)
- hashmap转list (35)
- c++ 字符串查找 (35)
- mysql刷新权限 (34)