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

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

热门内容推荐

最新内容推荐

项目优选

收起
ohos_react_nativeohos_react_native
React Native鸿蒙化仓库
C++
176
261
RuoYi-Vue3RuoYi-Vue3
🎉 (RuoYi)官方仓库 基于SpringBoot,Spring Security,JWT,Vue3 & Vite、Element Plus 的前后端分离权限管理系统
Vue
858
511
openGauss-serveropenGauss-server
openGauss kernel ~ openGauss is an open source relational database management system
C++
129
182
openHiTLSopenHiTLS
旨在打造算法先进、性能卓越、高效敏捷、安全可靠的密码套件,通过轻量级、可剪裁的软件技术架构满足各行业不同场景的多样化要求,让密码技术应用更简单,同时探索后量子等先进算法创新实践,构建密码前沿技术底座!
C
258
298
ShopXO开源商城ShopXO开源商城
🔥🔥🔥ShopXO企业级免费开源商城系统,可视化DIY拖拽装修、包含PC、H5、多端小程序(微信+支付宝+百度+头条&抖音+QQ+快手)、APP、多仓库、多商户、多门店、IM客服、进销存,遵循MIT开源协议发布、基于ThinkPHP8框架研发
JavaScript
93
15
Cangjie-ExamplesCangjie-Examples
本仓将收集和展示高质量的仓颉示例代码,欢迎大家投稿,让全世界看到您的妙趣设计,也让更多人通过您的编码理解和喜爱仓颉语言。
Cangjie
332
1.08 K
HarmonyOS-ExamplesHarmonyOS-Examples
本仓将收集和展示仓颉鸿蒙应用示例代码,欢迎大家投稿,在仓颉鸿蒙社区展现你的妙趣设计!
Cangjie
398
371
note-gennote-gen
一款跨平台的 Markdown AI 笔记软件,致力于使用 AI 建立记录和写作的桥梁。
TSX
83
4
CangjieCommunityCangjieCommunity
为仓颉编程语言开发者打造活跃、开放、高质量的社区环境
Markdown
1.07 K
0
kernelkernel
deepin linux kernel
C
22
5