第四篇 springcloud-gateway整合 (简单示例)

系列文章目录

最简单整合,后期待完善
Spring Cloud Gateway 是 Spring Cloud 新推出的网关框架,具体作用就是转发服务,接收并转发所有内外 部的客户端调用;其他常见的功能还有权限认证,限流控制等等。其功能类似前后端使用nginx做转发




一、导入jar包

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

二、配置路由

spring:
  application:
    name: cloud-gateway
  cloud:
    gateway:
      routes:
        - id: gate_route
          uri: http://127.0.0.1:8088   //
          predicates:
          - Path=/user/**   所有路由中有 user的都会转发到 http://127.0.0.1:8088 
如:http://127.0.0.1:8080/user/userBase/getUserAllList 
会转发到 
http://http://127.0.0.1:8088/user/userBase/getUserAllList

三、springcloud-gateway 介绍

1、gateWay的主要功能之一是转发请求,转发规则的定义主要包含三个部分

Route(路由)路由是网关的基本单元,由ID、URI、一组Predicate、一组Filter组成,根据Predicate进行匹配转发。
Predicate(谓语、断言)路由转发的判断条件,目前SpringCloud Gateway支持多种方式,常见如:Path、Query、Method、Header等,写法必须遵循 key=vlue的形式
Filter(过滤器)过滤器是路由转发请求时所经过的过滤逻辑,可用于修改请求、响应内容

2、转发规则(predicates)

假设 转发uri都设定为http://localhost:8088

规则实例说明
Path- Path=/gate/,/rule/当请求的路径为gate、rule开头的时,转发到http://localhost:8088服务器上
Before- Before=2021-01-20T17:42:47.789-07:00[America/Denver]在某个时间之前的请求才会被转发到 http://localhost:888服务器上
After- After=2021-05-20T17:42:47.789-07:00[America/Denver]在某个时间之后的请求才会被转发
Between- Between=2017-01-20T17:42:47.789-07:00[America/Denver],2021-05-21T17:42:47.789-07:00[America/Denver]在某个时间段之间的才会被转发
Cookie- Cookie=chocolate, ch.p名为chocolate的表单或者满足正则ch.p的表单才会被匹配到进行请求转发
Header- Header=X-Request-Id, \d+携带参数X-Request-Id或者满足\d+的请求头才会匹配
Host- Host=www.baidu.com当主机名为www.baidu.com的时候直接转发到http://localhost:8088服务器上
Method- Method=GET只有GET方法才会匹配转发请求,还可以限定POST、PUT等请求方式

3、过滤器

过滤规则实例说明
PrefixPath- PrefixPath=/app在请求路径前加上app
RewritePath- RewritePath=/test, /app/test访问localhost:9022/test,请求会转发到localhost:8001/app/test
SetPathSetPath=/app/{path}通过模板设置路径,转发的规则时会在路径前增加app,{path}表示原请求路径

1、访问/hello的请求被发送到https://example.org/mypath/hello。

spring:
  cloud:
    gateway:
      routes:
      - id: prefixpath_route
        uri: https://example.org
        filters:
        - PrefixPath=/mypath

2、重定向,配置包含重定向的返回码和地址:

spring:
  cloud:
    gateway:
      routes:
      - id: prefixpath_route
        uri: https://example.org
        filters:
        - RedirectTo=302, https://acme.org

参考:https://www.cnblogs.com/crazymakercircle/p/11704077.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值