SpringCloud之gateway使用

使用

SpringCloud Gateway是为了取代Zuul而开发出来的新一代网关,采用了响应式编程。
 
新建Module GatewayServer,添加依赖:

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

<dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>

注意:不要添加web依赖。

 
 

配置application.yml:

server:
  port: 8500

spring:
  cloud:
    gateway:
      enabled: true
      routes:
        - id: Goods-Server  # 路由 id,唯一标识
          uri: http://www.baidu.com
          predicates:
              - Path=/**  # 断言,路由匹配条件,匹配 / 开头的所有 api
          filters:
              - StripPrefix=1



eureka:
  client:
    service-url:
      defaultZone: http://user:123@localhost:8761/eureka/

启动后访问http://localhost:8500/,跳转到百度首页。访问http://localhost:8500/producer/,跳转到百度首页。访问http://localhost:8500/producer/hello,报了404异常。访问路径localhost:8500后面不能超过2个子路径。

gateway怎么工作

gateway三个组件:

  • Route:网关的基本构建块。它是由一个ID、一个目标URI、一组谓词和一组筛选器定义的。如果聚合谓词为true,则匹配路由。
  • Predicate:这是一个Java 8 Predicate。输入类型为Spring Framework ServerWebExchange。这允许匹配HTTP请求中的任何内容,例如请求头或参数。
  • Filter:这些是使用特定工厂构建的GatewayFilter实例。可以在发送下游请求之前或之后修改请求和响应。
     
    SpringCloud Gateway结构图
     

客户端向Spring Cloud Gateway发出请求。如果Gateway Handler Mapping确定请求与路由匹配,则将其发送到Gateway Web Handler。此处理程序通过特定于请求的过滤器链来运行请求。过滤器被虚线分隔的原因是,过滤器可以在发送代理请求之前和之后运行逻辑。执行所有“预”过滤逻辑。然后进行代理请求。在发出代理请求后,将运行“post”过滤器逻辑。

配置方式

简短方式

spring:
  cloud:
    gateway:
      routes:
      - id: after_route
        uri: https://example.org
        predicates:
        - Cookie=mycookie,mycookievalue

使用两个参数定义Cookie路由谓词工厂,即Cookie名称是mykokie和匹配mykokievalue的值。

完全方式

spring:
  cloud:
    gateway:
      routes:
      - id: after_route
        uri: https://example.org
        predicates:
        - name: Cookie
          args:
            name: mycookie
            regexp: mycookievalue

等价于上一个例子。

posted @   shigp1  阅读(81)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
点击右上角即可分享
微信分享提示