首页 > 其他分享 >微服务网关 —— SpringCloud Gateway

微服务网关 —— SpringCloud Gateway

时间:2023-09-02 18:24:51浏览次数:40  
标签:网关 http SpringCloud gateway cloud spring org Gateway 路由

Gateway 简介

Spring Cloud Gateway 基于 Spring 5、Spring Boot 2 和 Project Reactor 等技术,是在 Spring 生态系统之上构建的 API 网关服务,Gateway 旨在提供一种简单而有效的方式来对 API 进行路由以及提供一些强大的过滤器功能,例如熔断、限流、重试等

Spring Cloud Gateway 具有如下特性:

  • 基于 Spring Framework 5、Project Reactor 以及 Spring Boot 2.0 进行构建
  • 能够匹配任何请求属性
  • 可以对路由指定 Predicate(断言)和 Filter(过滤器)
  • 集成 Hystrix 的断路器功能
  • 集成 Spring Cloud 服务发现功能
  • 易于编写的 Predicate 和 Filter
  • 请求限流功能
  • 路径重写

Gateway 快速入门

创建项目,引入依赖

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>

在配置文件 application.yml 添加如下配置

server:
  port: 9201 # 指定运行端口

spring:
  application:
    name: gateway-service # 指定服务名称
  cloud:
    gateway:
      routes:
        - id: path_route  # 路由ID
          uri: http://localhost:8201/user/getUser  # 匹配后路由地址
          predicates: # 断言,路径相匹配的路由
            - Path=/user/getUser

也可以按如下配置

@Configuration
public class GatewayConfig {

    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
        return builder.routes()
                .route("path_route2", r -> r.path("/user/getUserInfo")
                        .uri("http://localhost:8201/user/getUserInfo"))
                .build();
    }
}

Gateway 路由工厂

Spring Cloud Gateway 包括许多内置的路由断言工厂,所有这些断言都与 HTTP 请求的不同属性匹配,多个路由断言工厂可以进行组合

1. After Route Predicate Factory

在指定时间之后的请求会匹配该路由

spring:
  cloud:
    gateway:
      routes:
        - id: after_route
          uri: http://example.org
          predicates:
            - After=2017-01-20T17:42:47.789-07:00[America/Denver]

2. Before Route Predicate Factory

在指定时间之前的请求会匹配该路由

spring:
  cloud:
    gateway:
      routes:
        - id: after_route
          uri: http://example.org
          predicates:
            - Before=2017-01-20T17:42:47.789-07:00[America/Denver]

3. Between Route Predicate Factory

在指定时间区间内的请求会匹配该路由

spring:
  cloud:
    gateway:
      routes:
        - id: after_route
          uri: http://example.org
          predicates:
            - Between=2017-01-20T17:42:47.789-07:00[America/Denver], 2017-01-21T17:42:47.789-07:00[America/Denver]

带有指定 Cookie 的请求会匹配该路由

spring:
  cloud:
    gateway:
      routes:
        - id: after_route
          uri: http://example.org
          predicates:
            - Cookie=milk, yili # cookie为milk=yili

5. Header Route Predicate Factory

带有指定请求头的请求会匹配该路由

spring:
  cloud:
    gateway:
      routes:
        - id: after_route
          uri: http://example.org
          predicates:
            - Header=X-Request-Id, 1	# 请求头为X-Request-Id=1

6. Host Route Predicate Factory

带有指定 Host 的请求会匹配该路由

spring:
  cloud:
    gateway:
      routes:
        - id: after_route
          uri: http://example.org
          predicates:
            - Host=**.somehost.org	# 请求头为Host:www.somehost.org的请求可以匹配该路由

7. Method Route Predicate Factory

发送指定方法的请求会匹配该路由

spring:
  cloud:
    gateway:
      routes:
        - id: after_route
          uri: http://example.org
          predicates:
            - Method=GET,POST

8. Path Route Predicate Factory

发送指定路径的请求会匹配该路由

spring:
  cloud:
    gateway:
      routes:
        - id: after_route
          uri: http://example.org
          predicates:
            - Path=/red/(segment],/blue/(segment) # /red/1或/blue/1路径请求可以匹配该路由

9. Query Route Predicate Factory

带指定查询参数的请求可以匹配该路由

spring:
  cloud:
    gateway:
      routes:
        - id: after_route
          uri: http://example.org
          predicates:
            - Query=green # 带green=l查询参数的请求可以匹配该路由

10. RemoteAddr Route Predicate Factory

从指定远程地址发起的请求可以匹配该路由

spring:
  cloud:
    gateway:
      routes:
        - id: after_route
          uri: http://example.org
          predicates:
            - RemoteAddr=192.168.1.1/24 # 从192.168.1.1发起请求可以匹配该路由

11. Weight Route Predicate Factory

使用权重来路由相应请求,以下代码表示有 80% 的请求会被路由到 weighthigh.org,20% 会被路由到 weightlow.org

spring:
  cloud:
    gateway:
      routes:
        - id: weight-high
          uri: http://weighthigh.org
          predicates:
            - Weight=group1, 8
        - id: weight-low
          uri: http://weightlow.org
          predicates:
            - Weight=group1, 2

可以使用 metadata 为每个 route 增加附加属性

spring:
  cloud:
    gateway:
      routes:
        - id: route-with-metadata
          uri: http://example.org
          metadata:
          	optionName: "OptionValue"
          	compositeObject:
          		name: "value"
          	iAmNumber: 1

可以从 exchange 获取所有元数据属性:

Route route = exchange.getAttribute(GATEWAY_ROUTE_ATTR);
route.getMetadata();
route.getMetadata (someKey);

Gateway 过滤器工厂

路由过滤器可用于修改进入的 HTTP 请求和返回的 HTTP 响应,Spring Cloud Gateway 内置了多种路由过滤器,由 GatewayFilter 的工厂类产生

1. AddRequestParameter GatewayFilter

AddRequestParameter GatewayFilter 是给请求添加参数的过滤器·

spring:
  cloud:
    gateway:
      routes:
        - id: add_request_parameter_route
          uri: http://example.org
          filters:
          	- AddRequestParameter=username, tom	# 对GET请求添加usemame=tom的请求参数
          predicates:
            - Method=GET

2. StripPrefixPath GatewayFilter

PrefixPath GatewayFilter 是对指定数量的路径前缓进行去除的过滤器

spring:
  cloud:
    gateway:
      routes:
        - id: strip_prefix_route
          uri: http://example.org
          filters:
          	# 把以/user-service/开头的请求的路径去除两位
          	# 相当于http://1ocalhost:9201/user-service/a/user/1
          	# 转换成http://localhost:8080/user/1
          	- StripPrefix=2 
          predicates:
            - Path=/user-service/**

3. PrefixPath GatewayFilter

与 StripPrefix 过滤器恰好相反,PrefixPath GatewayFilter 会对原有路径进行增加操作

spring:
  cloud:
    gateway:
      routes:
        - id: prefix_prefix_route
          uri: http://example.org
          filters:
          	# 对所有GET请求添加/user路径前缀
          	# 相当于http://1ocalhost:9201/get
          	# 转换成http://localhost:8080/user/get
          	- PrefixPath=/user
          predicates:
            - Method-GET

Gateway 全局过滤器

GlobalFilter 全局过滤器与普通的过滤器 GatewayFilter 具有相同的接口定义,只不过 GlobalFilter 会作用于所有路由

发起请求时,Filtering Web Handler 处理器会添加所有 GlobalFilter 实例和匹配的 GatewayFilter 实例到过滤器链中,过滤器链会使用 @Ordered 注解所指定的顺序进行排序,数值越小越靠前执行,默认 GatewayFilter 设置的 order 值为 1,如果 GatewayFilter 和 GlovalFilter 设置的 order 值一样,优先执行 GatewayFilter

@Component
public class CustomGlobalFilter implements GlobalFilter, ordered {
    
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("custom global filter");
        return chain.filter(exchange);
    }
    
    @Override
    public int getOrder() {
        return -1;
    }
}

Gateway 跨域

Gateway 是支持 CORS 的配置,可以通过不同的 URL 规则匹配不同的 CORS 策略,例如:

spring:
  cloud:
    gateway:
    	globalcors:
            corsConfiqurations:
                '[/**]':
                    allowedOrigins: "https://docs.spring.io"
                    allowedMethods:
                        - GET

在上面的示例中,对于所有 GET 请求,将允许来自 docs.spring.io 的 CORS 请求

Gateway 还提供更为详细的配置

spring:
  cloud:
    gateway:
    	globalcors:
            cors-confiqurations:
                '[/**]':
                	# 允许携带认证信息
                	allow-credentials: true
                	# 允许跨城的源(网站城名/ip),设置*为全部
                    allowed-origins: 
                    - "http://localhost:13009"
                    - "http://localhost:13010"
                    # 允许跨城请求里的head字段,设置*为全部
                    allowed-headers: "*"
                    # 允许跨城的method,默认为GET和OPTIONS,设置*为全部
                    allowed-methods: 
                    - OPTIONS
                    - GET
                    - POST
                    # 跨域允许的有效期
                    max-age: 3600
                    # 允许response的head信息
                    # 默认仅允许如下6个:
                    # Cache-Control
                    # Content-Language
                    # Content-Type
                    # Expires
                    # Last-Modified
                    # Praqma
                    # exposed-headers:

HTTP 超时配置

1. 全局超时

spring:
  cloud:
    gateway:
    	httpclient:
    		connect-timeout: 1000 # 连接超时配置,单位为毫秒
    		response-timeout: 5s # 响应超时,单位为 java.time.Duration

2. 每个路由配置

spring:
  cloud:
    gateway:
      routes:
        - id: per_route_timeouts
          uri: http://example.org
          predicates:
            - Path=/user-service/**
          metadata:
          	response-timeout: 200 # 响应超时,单位为毫秒
          	connect-timeout: 200 # 连接超时配置,单位为毫秒

TLS/SSL 设置

在 Web 服务应用中,为了数据的传输安全,会使用安全证书以及 TLS/SSL 加密,Gateway 可以通过遵循常规的 Spring 服务器配置来侦听 HTTPS 上的请求

server:
	ssl:
		# 启用ssl
		enabled: true
		# 启用证书
		key-alias: scg
		# 证书密码
		key-store-password: scg1234
		# 证书地址
		key-store: classpath:scg-keystore.pl2
		# 证书类型
		key-store-type: PKCS12

可以使用以下配置为 Gateway 配置一组可信任的已知证书

spring:
  cloud:
    gateway:
    	httpclient:
    		ssl:
    			trustedX509Certificates:
                - certl.pem
                - cert2.pem

标签:网关,http,SpringCloud,gateway,cloud,spring,org,Gateway,路由
From: https://www.cnblogs.com/Yee-Q/p/17673998.html

相关文章

  • 硬件管理平台-硬件网关-插件模块-集成(下)
    硬件管理平台-硬件网关-插件模块-集成(下)简介通过以上的几篇文章说明了xml的相关配置信息和配置项,我们可以对插件模块的剩余部分进行说明了。当网关服务加载了本地的硬件插件后就产生了硬件类型的实例,通过该实例就可以去调用下位机了。而去调用哪个下位机,我们就需要通过xml的配置......
  • 微服务网关-Spring Cloud Gateway
    为什么需要服务网关:1、什么是服务网关:微服务架构中将一个系统拆分成多个微服务,如果没有网关,客户端只能在本地记录每个微服务的调用地址,当需要调用的微服务数量很多时,它需要了解每个服务的接口,这个工作量很大。那有了网关之后,能够起到怎样的改善呢?网关作为系统的唯一流量入口,封装内......
  • 24 路由器,交换机,IP,DNS,子网掩码,网关
    昨天有同志遇到了电脑连接问题,他是在一个大型局域网中,他们的网络交换机没打开自动分配IP的功能,所以IP地址都是手动配置,期间遇到了子网掩码,IP地址,网关,DNS服务器等概念,逐一记录,希望能让所有人看懂。一、交换机主要功能为端口拓展,让你有更多网络端口,扩大局域网接入点。。工作在TCPI......
  • Gateway跨域请求配置
    importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.http.HttpHeaders;importorg.springframework.http.HttpMethod;importorg.springframework.http.HttpStatus;importor......
  • 5G工业网关常见应用场景介绍
    5G工业网关是指基于5G网络技术的工业物联网网关设备,用于连接和管理工业设备和各个物联网子系统。它可以实现数据采集、远程监控、远程控制和数据传输等功能,广泛应用于工业自动化、智能制造、智能交通等领域。以下是一些5G工业网关的应用场景:  1、工业自动化:5G工业网关可以与......
  • 视频云存储/安防监控/AI视频智能分析网关V3:工服检测功能详解
    在一些工地、后厨、化工、电力等特定的场景中,工服的穿戴是必不可少的。这不仅是安全制度的要求,更能降低工作风险、提高工作效率。TSINGSEE青犀AI边缘计算网关硬件——智能分析网关可以通过实时监测和识别工人的工装穿戴情况,确保他们符合安全要求。只需在施工场地等监控区域内对......
  • NAT网关有什么功能(局域网内多个IP设备通过同一个公共IP地址来访问Internet)
    网络地址转换(NAT)是一种能够将私有IP地址转换为公共IP地址以访问互联网的技术。其原因在于IPv4地址资源基本开发完全,通过NAT技术可以实现多台设备在局域网内使用相同的公共IP地址访问互联网,或是通过互联网访问到这些局域网内的设备。NAT网关(网段隔离器)是专用于私有IP地址和公共IP地......
  • SpringCloud 支持 超大上G,多附件上传
    ​ 这里只写后端的代码,基本的思想就是,前端将文件分片,然后每次访问上传接口的时候,向后端传入参数:当前为第几块文件,和分片总数下面直接贴代码吧,一些难懂的我大部分都加上注释了:上传文件实体类:看得出来,实体类中已经有很多我们需要的功能了,还有实用的属性。如MD5秒传的信息。pub......
  • springcloud 跨域问题解决
    问题原因跨域本质是浏览器基于同源策略的一种安全手段同源策略(Sameoriginpolicy),是一种约定,它是浏览器最核心也最基本的安全功能所谓同源(即指在同一个域)具有以下三个相同点协议相同(protocol)主机相同(host)端口相同(port)反之非同源请求,也就是协议、端口、主机其中一项不相同的......
  • 基于AI智能分析网关EasyCVR视频汇聚平台关于能源行业一体化监控平台可实施应用方案
    随着数字经济时代的到来,实体经济和数字技术深度融合已成为经济发展的主流思路。传统能源行业在运营管理方面也迎来了新的考验和机遇。许多大型能源企业已开始抓住机遇,逐步将视频监控、云计算、大数据和人工智能技术广泛应用于生产、维护、运输、配送等环节,实现数据采集、业务监控......