Spring Cloud Gateway 教程
2024-08-07 19:47:56作者:裴锟轩Denise
1. 项目介绍
Spring Cloud Gateway 是一款由 Pivotal 开发的微服务网关组件,它旨在成为 Spring Cloud 生态系统中的新一代 API 网关。该项目基于 Spring Framework 5 和 Project Reactor 提供了一个高度可配置的框架,用于构建和管理 API 路由。Spring Cloud Gateway 提供了以下核心功能:
- 动态路由:能够将请求映射到不同的微服务。
- 断言过滤器链:允许在请求经过路由之前添加预处理步骤,如认证、限流等。
- 自动负载均衡:通过与服务发现组件(如 Eureka、Consul 或 Nacos)集成,能够自动发现和路由到可用的微服务实例。
2. 项目快速启动
2.1 添加依赖
在 pom.xml 文件中添加 Spring Cloud Gateway 和相关依赖:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.x</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>2020.0.2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
2.2 启动配置
创建一个名为 application.yml 的配置文件,添加以下内容以配置路由:
server:
port: 8080
spring:
cloud:
gateway:
routes:
- id: example-route
uri: lb://example-service # 使用服务发现
predicates:
- Path=/example/**
2.3 主类
创建主类 Application.java,启用 Spring Boot 和 Gateway:
package com.example.gateway;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
@EnableEurekaClient
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
2.4 启动应用
运行 Application 类,Spring Cloud Gateway 将启动并在指定端口监听,并根据配置将 /example/* 的请求路由到名为 example-service 的微服务。
3. 应用案例和最佳实践
3.1 身份验证
利用过滤器添加 JWT 认证:
@Bean
GlobalFilter jwtAuthenticationFilter(JwtUtils jwtUtils) {
return (exchange, chain) -> {
ServerHttpRequest request = exchange.getRequest();
if (!request.getHeaders().containsKey("Authorization")) {
return chain.filter(exchange);
}
// 验证并处理 JWT token...
return chain.filter(exchange.mutate().request(request).build());
};
}
3.2 日志监控
使用 Zipkin 或 Sleuth 追踪请求:
spring:
cloud:
gateway:
globalcors:
cors-configurations:
'[/**]':
allowedOrigins: "*"
allowedMethods: "*"
allowedHeaders: "*"
sleuth:
trace-id-generator:
name: random
zipkin:
base-url: http://localhost:9411/
3.3 限流
整合 Sentinel 进行流量控制:
spring:
cloud:
sentinel:
transport:
dashboard: localhost:8080
在配置文件中定义限流策略,并使用 @SentinelResource 注解标记业务方法。
4. 典型生态项目
- Spring Cloud Netflix Eureka: 服务发现组件,用于定位集群中的微服务实例。
- Spring Cloud OpenFeign: 用于声明式的 Web 服务客户端。
- Spring Cloud Consul: 另一种服务发现解决方案。
- Spring Cloud Config: 提供配置管理工具。
- Spring Cloud Bus: 实现事件和消息总线,通常与配置中心一起使用以实时刷新配置。
- Spring Cloud LoadBalancer: 提供了一种负载均衡机制,与 Spring Cloud Gateway 结合使用可以实现更灵活的服务调用。
欲了解更多详情,可以参考官方文档:https://github.com/spring-cloud/spring-cloud-gateway/blob/master/README.adoc
完成这些步骤后,您将拥有一个基础的 Spring Cloud Gateway 实例,可以继续根据项目需求进行定制和扩展。
登录后查看全文
热门项目推荐
相关项目推荐
atomcodeClaude Code 的开源替代方案。连接任意大模型,编辑代码,运行命令,自动验证 — 全自动执行。用 Rust 构建,极致性能。 | An open-source alternative to Claude Code. Connect any LLM, edit code, run commands, and verify changes — autonomously. Built in Rust for speed. Get StartedRust0218
cann-learning-hubCANN 学习中心仓,支持在线互动运行、边学边练,提供教程、示例与优化方案,一站式助力昇腾开发者快速上手。Jupyter Notebook0139
uni-appA cross-platform framework using Vue.jsJavaScript09
GLM-5.2智谱开源 GLM-5.2,这是针对长文本任务的最新旗舰模型。相较于前代产品 GLM-5.1,它在长文本任务处理能力上实现了显著飞跃,并且首次在稳定的 100 万 token 上下文中提供这一能力。Jinja00
SwanLab⚡️SwanLab - an open-source, modern-design AI training tracking and visualization tool. Supports Cloud / Self-hosted use. Integrated with PyTorch / Transformers / LLaMA Factory / veRL/ Swift / Ultralytics / MMEngine / Keras etc.Python00
tiny-universe《大模型白盒子构建指南》:一个全手搓的Tiny-UniverseJupyter Notebook03
热门内容推荐
项目优选
收起
deepin linux kernel
C
32
16
openEuler内核是openEuler操作系统的核心,既是系统性能与稳定性的基石,也是连接处理器、设备与服务的桥梁。
C
471
465
Ascend Extension for PyTorch
Python
758
968
昇腾LLM分布式训练框架
Python
186
231
本项目是CANN提供的神经网络类计算算子库,实现网络在NPU上加速计算。
C++
700
1.4 K
本项目是CANN提供的transformer类大模型算子库,实现网络在NPU上加速计算。
C++
880
2.03 K
暂无描述
Dockerfile
780
5.08 K
🔥LeetCode solutions in any programming language | 多种编程语言实现 LeetCode、《剑指 Offer(第 2 版)》、《程序员面试金典(第 6 版)》题解
Java
70
22
本仓库是 Flutter SDK 与 Flutter Engine 的 OpenHarmony 适配版本,由 CPF-Flutter 团队维护。开发者可使用熟悉的 Flutter 技术栈开发 OpenHarmony 应用,3.35.7 及以后的适配版本可基于本仓库源码构建支持 OpenHarmony 的 Flutter Engine。
Dart
1.04 K
271
Claude Code 的开源替代方案。连接任意大模型,编辑代码,运行命令,自动验证 — 全自动执行。用 Rust 构建,极致性能。 | An open-source alternative to Claude Code. Connect any LLM, edit code, run commands, and verify changes — autonomously. Built in Rust for speed.
Get Started
Rust
2.09 K
218