Gateway服务网关

什么是服务网关

服务网关 = 路由转发 + 过滤器

1、路由转发:接收一切外界请求,转发到后端的微服务上去;

2、过滤器:在服务网关中可以完成一系列的横切功能,例如权限校验、限流以及监控等,

这些都可以通过过滤器完成(其实路由转发也是通过过滤器实现的)。

服务网关的基本功能:

Spring Cloud Gateway 网关的搭建:

1、添加依赖

java 复制代码
 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-webflux</artifactId>
 </dependency>
 <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-gateway</artifactId>
      <version>2.2.2.RELEASE</version>
</dependency>

注意:一定要排除掉 spring-boot-starter-web 依赖,否则启动报错

2、添加配置

首先你要有一个应用名称为httpbin,然后在配置中配置

复制代码
spring:
  application:
    name: gateway-app
  cloud:
    gateway:
      routes:
        - id: httpbin
          uri: https://httpbin.org
          order: 1
          predicates:
            - Path=/abc/**
#           - Query=id,\d+
#           - Method=GET
#           - Cookie=JSESSIONID,123456
#           - Header=X-Request-Id, \d+
          filters:
            ##在请求目标uri之前,截取路径上面的占位路径的个数
            - StripPrefix=1
            - AddRequestHeader=token,123
            - AddRequestParameter=color,green
        - id: nacos-a
          uri: http://127.0.0.1:3777
          predicates:
            - Path=/nacos-a/**
          filters:

            - StripPrefix=1
            - AddRequestHeader=token,123
            - AddResponseHeader=compay,xingqijiu.com

好了,网关项目搭建完成,其实就添加这么一个依赖,再加上配置,就可以验证了.

Spring Cloud Gateway 配置项的说明:

在介绍 Spring Cloud Gateway 的配置项之前,我们先了解几个 Spring Cloud Gateway 的核心术语:
1.路由(route):由ID、目标URI、断言集合和过滤器集合组成。如果聚合断言结果为真,则转发到该路由。
2.断言(Predicate): 参照 Java8 的新特性Predicate,允许开发人员匹配 HTTP 请求中的任何内容,比如请求头、请求参数或请求路径,最后根据匹配结果返回一个布尔值。

3.过滤器(filter):可以在返回请求之前或之后修改请求和响应的内容

路由 Route:

Route 主要由 路由id、目标uri、断言集合和过滤器集合组成,那我们简单看看这些属性到底有什么作用。

(1)id:路由标识,要求唯一,名称任意(默认值 uuid,一般不用,需要自定义)

(2)uri:请求最终被转发到的目标地址

(3)order: 路由优先级,数字越小,优先级越高

(4)predicates:断言数组,即判断条件,如果返回值是true,则转发请求到 uri 属性指定的服务中

(5)filters:过滤器数组,在请求传递过程中,对请求做一些修改或对返回做一些修改
断言 Predicate:

重要的两个断言

复制代码
spring:
  cloud:
    gateway:
      routes:
        - predicates:
            #PathRoutePredicate
            - Path: /orderservice/**
            # QueryRoutePredicate
            - Query: version,v1
相关推荐
码点滴3 小时前
私有 Gateway 接入企业 IM:从消息路由到多租户隔离——Hermes Agent 工程实战
人工智能·架构·gateway·prompt·智能体·hermes
代码写到35岁5 小时前
Gateway+OpenFeign 踩坑总结
gateway
invicinble6 小时前
对于gateway信息量沉淀
gateway
郝开1 天前
Spring Cloud Gateway 3.5.14 使用手册
java·数据库·spring boot·gateway
Ribou2 天前
Kubernetes v1.35.2 基于 Cilium Gateway API 的服务访问架构
架构·kubernetes·gateway
huipeng9263 天前
GateWay使用详解
java·spring boot·spring cloud·微服务·gateway
随风,奔跑7 天前
Spring Cloud Alibaba(四)---Spring Cloud Gateway
后端·spring·gateway
jiayong237 天前
Hermes Agent 的 Skills、Plugins、Gateway 深度解析
ai·gateway·agent·hermes agent·hermes
鬼蛟7 天前
Gateway
gateway
武超杰7 天前
Spring Cloud Gateway 从入门到实战
spring cloud·gateway