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

Spring Cloud Gateway详细介绍简单案例

文章目录

    • 1、Spring Cloud Gateway 详细介绍
      • 1.1. 统一入口(Single Entry Point)
      • 1.2. 请求路由(Request Routing)
      • 1.3. 负载均衡(Load Balancing)
      • 1.4. 流量控制(Rate Limiting)
      • 1.5. 身份认证(Authentication & Authorization)
      • 1.6. 协议转换(Protocol Translation)
      • 1.7. 系统监控(Monitoring & Logging)
      • 1.8. 安全防护(Security Protection)
    • 2、Spring Cloud Gateway的使用
      • 2.2. 两种gateway模式
      • 2.2. 使用案例需求
      • 2.3. 创建gateway模块
      • 2.4. 启动gateway模块
    • 3、配置路由规则
    • 4、启动多个服务进行测试

1、Spring Cloud Gateway 详细介绍

Spring Cloud Gateway 作为微服务架构的 API 网关,提供统一入口、请求路由、负载均衡、流量控制、身份认证、协议转换、系统监控、安全防护等功能,能够高效管理 API 请求流量,并提升系统的安全性和稳定性。

在这里插入图片描述

1.1. 统一入口(Single Entry Point)

微服务架构中,每个微服务都有自己的 API,直接暴露所有服务会导致维护困难、安全风险增加。

Spring Cloud Gateway 解决方案:

  • 通过单一网关,所有外部请求都必须先通过 API 网关,再路由到具体微服务。

  • 隐藏微服务细节,外部只需访问网关地址,不直接访问后端服务。

✅ 示例:配置 API 入口

spring:
  cloud:
    gateway:
      routes:
        - id: user-service
          uri: lb://user-service
          predicates:
            - Path=/user/**
        - id: order-service
          uri: lb://order-service
          predicates:
            - Path=/order/**

  • /user/** 的请求被路由到 user-service

  • /order/** 的请求被路由到 order-service

  • 客户端只需要请求 API 网关,而无需知道后端微服务的实际地址。

1.2. 请求路由(Request Routing)

需要根据路径、请求头、参数等,动态转发到不同的微服务。

Spring Cloud Gateway 解决方案:

  • 基于 Path、Header、Query 参数等规则,智能路由。

✅ 示例:多种路由规则

routes:
  - id: auth-service
    uri: lb://auth-service
    predicates:
      - Path=/auth/**          # 按路径匹配
      - Method=POST            # 按请求方法匹配
      - Header=X-Device, Mobile  # 按请求头匹配

  • 路径规则:所有 /auth/** 请求都会转发到 auth-service。

  • 请求方法:仅支持 POST 请求。

  • 请求头规则:X-Device=Mobile 时才会匹配。

1.3. 负载均衡(Load Balancing)

单个微服务实例可能会过载,需要将流量分发到多个实例,提高可用性。

Spring Cloud Gateway 解决方案:

  • 内置 Spring Cloud LoadBalancer,支持基于服务注册中心(Eureka、Consul、Nacos)自动均衡流量。

✅ 示例:开启负载均衡

uri: lb://order-service

  • lb:// 表示启用负载均衡,请求会被分发到 order-service 的多个实例。

1.4. 流量控制(Rate Limiting)

突发流量可能导致服务崩溃,需要限制单个 IP 或用户的请求速率。

Spring Cloud Gateway 解决方案:

  • 基于 Redis 令牌桶算法,支持用户级、IP 级限流。

✅ 示例:限流配置

filters:
  - name: RequestRateLimiter
    args:
      redis-rate-limiter.replenishRate: 5   # 每秒 5 个请求
      redis-rate-limiter.burstCapacity: 10  # 最大 10 个请求

  • 每秒最多 5 个请求,超过速率的请求会被拒绝。

1.5. 身份认证(Authentication & Authorization)

需要确保只有合法用户可以访问微服务,防止未授权访问。

Spring Cloud Gateway 解决方案:

  • 集成 Spring Security + OAuth2/JWT 进行身份认证。

  • TokenRelay 机制,将身份验证信息传递给下游服务。

✅ 示例:JWT 认证

filters:
  - name: TokenRelay  # 自动转发 JWT Token

  • TokenRelay 过滤器 会自动从请求中提取 JWT 令牌,并传递给后端微服务进行身份验证。

1.6. 协议转换(Protocol Translation)

有些微服务可能只支持 HTTP 或 HTTPS,但客户端请求可能是 WebSocket、gRPC 等。

Spring Cloud Gateway 解决方案:

  • 支持 WebSocket 转发

  • 支持 HTTP 转 HTTPS

✅ 示例:WebSocket 转发

routes:
  - id: ws-route
    uri: ws://localhost:9000
    predicates:
      - Path=/ws/**

  • /ws/** 开头的 WebSocket 请求会被转发到 localhost:9000。

1.7. 系统监控(Monitoring & Logging)

需要监控网关的流量情况、请求延迟、异常情况。

Spring Cloud Gateway 解决方案:

  • 结合 Spring Boot Actuator,提供健康检查、流量监控

  • 支持 Prometheus + Grafana 进行可视化监控

  • 支持 Zipkin/Jaeger 进行链路追踪

✅ 示例:开启 Actuator 监控

management:
  endpoints:
    web:
      exposure:
        include: gateway

  • 访问 /actuator/gateway/routes 可查看所有路由情况。

✅ 结合 Prometheus 进行监控

management:
  metrics:
    export:
      prometheus:
        enabled: true
  • 可在 Grafana 中展示流量数据。

1.8. 安全防护(Security Protection)

API 网关必须具备基础安全防护能力,防止恶意攻击。

Spring Cloud Gateway 解决方案:

  • 黑白名单过滤(基于 IP、用户角色)
  • 防止 SQL 注入、XSS
  • 请求加密(TLS/SSL)
  • 防止 DDoS 攻击(限流 + 认证)

示例:IP 访问控制

filters:
  - name: IpFilter
    args:
      deny-lists: 192.168.1.100  # 禁止此 IP 访问

  • 可以防止恶意 IP 访问 API 网关。
  1. 结论
功能Spring Cloud Gateway 解决方案
统一入口通过网关管理所有微服务入口
请求路由按路径、请求头、参数等匹配路由
负载均衡内置 LoadBalancer,自动分流流量
流量控制令牌桶算法限流,防止过载
身份认证支持 JWT/OAuth2 认证
协议转换WebSocket 代理,HTTPS 转换
系统监控Actuator、Prometheus、Grafana
安全防护黑白名单、DDoS 防护

2、Spring Cloud Gateway的使用

2.2. 两种gateway模式

Spring Cloud Gateway 提供了两种模式来运行 API 网关:

  • Spring Cloud Gateway Reactive Server(基于 Spring WebFlux)

  • Spring Cloud Gateway Server MVC(基于 Spring MVC)

在这里插入图片描述

推荐使用第一种模式。

2.2. 使用案例需求

需求

  • 1.客户端发送 /api/order/**转到service-order
  • 2.客户端发送 /api/product/**转到 service-product
  • 3.以上转发有负载均衡效果

在这里插入图片描述

2.3. 创建gateway模块

在这里插入图片描述
引入依赖(这里同时需要引入nacos依赖)

    <dependencies>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
    </dependencies>

创建gateway主启动类:

package com.tigerhhzz.gateway;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

/**
 * @Author tigerhhzz
 * @Date 2025 03 28 02 00
 **/
@EnableDiscoveryClient
@SpringBootApplication
public class GatewayMainApplication {

    public static void main(String[] args) {
        System.out.println("--------GatewayMainApplication---------start successful!");
        SpringApplication.run(GatewayMainApplication.class,args);
    }
}

编写配置文件:
application.yml

spring:
  application:
    name: gateway
  cloud:
    nacos:
      server-addr: 127.0.0.1:8848

server:
  port: 80

2.4. 启动gateway模块

启动gateway主启动类,查看nacoa服务中心
在这里插入图片描述

3、配置路由规则

application.yml

spring:
  profiles:
    active:
      - routes
  application:
    name: gateway
  cloud:
    nacos:
      server-addr: 127.0.0.1:8848

server:
  port: 80

application-routes.yml

spring:
  cloud:
    gateway:
      routes:
        - id: order-route
          uri: lb://service-order
          predicates:
            - Path=/api/order/**
        - id: product-route
          uri: lb://service-product
          predicates:
            - Path=/api/product/**

在每个控制器controller上加上配置文件中断言一致的路径

@RequestMapping("/api/order")

@RequestMapping("/api/product")

4、启动多个服务进行测试

在这里插入图片描述

在这里插入图片描述
发送请求到order-service的两个服务,进行了负载均衡!!!

在这里插入图片描述


别害怕付出没有回报,那些看似平淡无奇的日子,都是成长的伏笔。


http://www.dtcms.com/a/98672.html

相关文章:

  • Js 主线程和异步队列哪个先执行
  • Yolo系列之Yolov4的改进及网络框架
  • Java入门知识总结——章节(二)
  • bluecode-20240913_1_数据解码
  • 【Kafka】分布式消息队列的核心奥秘
  • 3.29前端模拟面试
  • 【区块链安全 | 第八篇】多签机制及恶意多签
  • org.apache.maven.surefire:surefire-junit-platform:jar:2.22.2 Maven打包失败
  • 逗万DareWorks|创意重构书写美学,引领新潮无界的文创革命
  • 什么是贴源库
  • unique_ptr的详细介绍
  • 量子计算与项目管理:2025年颠覆性技术将如何重构任务分解逻辑?
  • 【商城实战(103)】商城实战终章:携手共进,迈向新程
  • AI日报 - 2025年03月29日
  • 团建--树+dfs
  • MySQL的基础语法2(函数-字符串函数、数值函数、日期函数和流程函数 )
  • Linux之数据链路层
  • Vue 类与样式
  • 【数学建模】(启发式算法)模拟退火算法:原理、实现与应用
  • [c++项目]基于微服务的聊天室服务端测试
  • 基于ssm的课程辅助教学平台(全套)
  • 直流电机类型及其控制技术
  • 免费下载 | 2025年网络安全报告
  • libimobiledevice项目中各个库的作用
  • 【数据结构】二叉树的递归
  • 前端音频和视频上传预览功能的探索与总结
  • Linux 基本使用和 web 程序部署
  • 人生感悟8
  • 【测试】每日3道面试题 3/29
  • Advanced Renamer:批量文件重命名工具