首页
/ Spring Cloud Gateway 教程

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 实例,可以继续根据项目需求进行定制和扩展。

登录后查看全文
热门项目推荐
相关项目推荐

项目优选

收起
kernelkernel
deepin linux kernel
C
24
7
nop-entropynop-entropy
Nop Platform 2.0是基于可逆计算理论实现的采用面向语言编程范式的新一代低代码开发平台,包含基于全新原理从零开始研发的GraphQL引擎、ORM引擎、工作流引擎、报表引擎、规则引擎、批处理引引擎等完整设计。nop-entropy是它的后端部分,采用java语言实现,可选择集成Spring框架或者Quarkus框架。中小企业可以免费商用
Java
9
1
Cangjie-ExamplesCangjie-Examples
本仓将收集和展示高质量的仓颉示例代码,欢迎大家投稿,让全世界看到您的妙趣设计,也让更多人通过您的编码理解和喜爱仓颉语言。
Cangjie
376
3.31 K
flutter_flutterflutter_flutter
暂无简介
Dart
622
140
leetcodeleetcode
🔥LeetCode solutions in any programming language | 多种编程语言实现 LeetCode、《剑指 Offer(第 2 版)》、《程序员面试金典(第 6 版)》题解
Java
62
20
openHiTLSopenHiTLS
旨在打造算法先进、性能卓越、高效敏捷、安全可靠的密码套件,通过轻量级、可剪裁的软件技术架构满足各行业不同场景的多样化要求,让密码技术应用更简单,同时探索后量子等先进算法创新实践,构建密码前沿技术底座!
C
1.03 K
479
ops-mathops-math
本项目是CANN提供的数学类基础计算算子库,实现网络在NPU上加速计算。
C++
648
263
RuoYi-Vue3RuoYi-Vue3
🎉 (RuoYi)官方仓库 基于SpringBoot,Spring Security,JWT,Vue3 & Vite、Element Plus 的前后端分离权限管理系统
Vue
1.1 K
620
giteagitea
喝着茶写代码!最易用的自托管一站式代码托管平台,包含Git托管,代码审查,团队协作,软件包和CI/CD。
Go
23
0
cherry-studiocherry-studio
🍒 Cherry Studio 是一款支持多个 LLM 提供商的桌面客户端
TypeScript
794
77