当前位置: 首页 > article >正文

Spring Cloud Alibaba学习 4- Spring Cloud Gateway入门使用

Spring Cloud Alibaba学习 4- Spring Cloud Gateway入门使用

中文文档Spring Cloud Gateway 中文文档

一. 基本使用

1. Predicate配置

1.1 配置参数介绍

直接通过官方给的application.yml介绍,这里就不介绍简写方式了,直接介绍完整方式

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

    ​ 可以配置多个需要管理的的路由规则 route

  • route:

配置了route就必须配置predicate!!

详细写法:

- id: 路由的编号
  uri: 需要转发的目的URI
  predicates: 断言,只有完全匹配断言规则的才可以对请求进行处理,同一个断言下的配置的路由规则是与的关系
  - name: 路由规则名
  	args:
        name: 参数的名称
        value: 参数的值
 

简单写法:

  - id: 路由的编号
    uri: 需要转发的目的URI
    predicates: #断言
    - Cookie=chocolate, ch.p #路由规则名=参数名, 参数值
  • 路由规则名

下面是官方给出的一些例子

name说明举例例子解释
After在这个时间后的请求才转发(时间类型得是ZonedDateTime)- After=2017-01-20T17:42:47.789-07:00[America/Denver]北美山区时间(丹佛)2017年1月20日17:42之后发出的任何请求相匹配。
Before在这个时间前的请求才转发(时间类型得是ZonedDateTime)- Before=2017-01-20T17:42:47.789-07:00[America/Denver]北美山区时间2017年1月20日17:42(丹佛)之前发出的任何请求相匹配
Between在这两个时间之间的请求(时间类型得是ZonedDateTime)- Between=2017-01-20T17:42:47.789-07:00[America/Denver], 2017-01-21T17:42:47.789-07:00[America/Denver]匹配2017年1月20日山区时间(丹佛)17:42之后和2017年1月21日山区时间(丹佛)17:42之前的任何请求
Cookie匹配具有给定名称且其值符合正则表达式cookie- Cookie=chocolate, ch.p匹配有一个名为 chocolate 的cookie,其值符合 ch.p 正则表达式的请求
Header匹配具有给定名称且其值符合正则表达式请求头- Header=X-Request-Id, \d+X-Request-Id 的header,其值与 \d+ 正则表达式相匹配
Host匹配请求的Host- Host=**.somehost.org,**.anotherhost.org请求的 Host 值为 www.somehost.orgbeta.somehost.orgwww.anotherhost.org则匹配
Method匹配请求的方式- Method=GET,POST请求方式是 GETPOST则匹配
Path匹配对应值的路径(支持通配符**和占位符{segment})- Path=/red/{segment},/blue/{segment}如果请求路径是 /red/1/red/1//red/blue/blue/green,则该路由匹配
Query匹配具有给定名称且其值符合正则表达式方法参数- Query=green请求中包含一个 red 的查询参数,其值与 gree. 表达式相匹配,那么路由就会匹配
RemoteAddr匹配远程地址(IPv4或IPv6)- RemoteAddr=192.168.1.1/24如果请求的远程地址 192.168.1.10,则该路由匹配
Weight
XForwarded Remote Addr
1.2 使用
1.2.1 引入依赖

注意要和 Spring Boot 版本匹配,否则启动会报错

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
    <version>4.1.2</version>
</dependency>
1.2.2 配置路由规则

以下的规则代表,如果有请求发送到路由所在的服务上,如果是GET请求,那么就会转发到 http://localhost:8081

application.yml

spring:
  application:
    name: gateway
  cloud:
    gateway:
      routes:
        - id: checkParam
          uri: http://localhost:8081
          predicates:
            - name: Method
              args:
                name: path
                value: GET
1.2.3 测试

运行一个在8081端口上的服务 orderService,orderController如下:

@RestController
@RequestMapping("/order")
@Slf4j
@RefreshScope
public class OrderController {
 	@GetMapping("/testGetGateWay")
    public String testGetGateWay() {
        return "你好";
    }
    @PostMapping("/testPostGateWay")
    public String testPostGateWay() {
        return "你好";
    }
}

运行的服务如下:

在这里插入图片描述

发送GET请求,能成功转发到orderservice上

GET http://localhost:8080/order/testGetGateWay

在这里插入图片描述

发送POST请求,转发失败,因为我们只允许GET请求转发,显示404

在这里插入图片描述

2. Filter配置

参数很多,见官方文档,用法和上面Predicate基本相同,这里不做过多介绍

下面这个例子表示,如果请求带有param参数,则转发请求并带上X-Request-Token: 123作为请求头

spring:
    cloud:
    gateway:
      routes:
        - id: after_route
          uri: http://localhost:8081
          predicates:
            - Query=param
          filters:
            - AddRequestHeader=X-Request-Token, 123

OrderController的方法如下:

@GetMapping("/testGetGateWay")
public String testGetGateWay(HttpServletRequest req) {
    Enumeration<String> headers = req.getHeaderNames();
        while (headers.hasMoreElements()) {
            String name = headers.nextElement();
            String value = req.getHeader(name);
            log.info(name + ": " + value);
        }
     return "你好";
}
GET http://localhost:8080/order/testGetGateWay?param=1

结果:

在这里插入图片描述

二. 进阶使用

1. 全局CORS配置

解决跨域问题

写一个html文件给发送上述请求http://localhost:8080/order/testGetGateWay?param=1

test.html

<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<head>
  <title>测试网页</title>
</head>
<body>
  <button style="height: 50px; width: 50px;">导出</button>
</body>

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
   axios.get('http://localhost:8080/order/testGetGateWay?param=1').then(x => {
      console.log(x)
   }).catch(x => {
      console.log(x);
   })
</script>
</html>

报错:

在这里插入图片描述

配置127.0.0.1:8083允许跨域

application.yml

spring:
  application:
    name: gateway
  cloud:
    gateway:
      globalcors:
        cors-configurations:
          '[/**]': #任意请求
            allowedOrigins: "http://127.0.0.1:8083" #允许http://127.0.0.1:8083跨域
            allowedMethods: #请求的方式
              - "*" #允许所有请求方式,记住是要双引号而不是单引号

结果:

在这里插入图片描述


http://www.kler.cn/a/572483.html

相关文章:

  • 湖仓一体概述
  • React封装通用Table组件,支持搜索(多条件)、筛选、自动序号、数据量统计等功能。未采用二次封装调整灵活,包含使用文档
  • leetcode日记(77)子集Ⅱ
  • Apache IoTDB 树表双模型直播回顾(上)
  • pytest中pytest.ini文件的使用
  • python八皇后游戏
  • Java 第十一章 GUI编程(2)
  • 游戏引擎学习第135天
  • AI×电商数据API接口:深度融合,引领未来电商行业浪潮
  • docker默认网段和宿主机环境冲突时的处理
  • pytorch获取模型性能
  • 【GPU使用】如何在物理机和Docker中指定GPU进行推理和训练
  • 一、docker初识
  • 【在线用户监控】在线用户查询、强退用户
  • Java利用JSch进行SFTP进行SSH连接远程服务器进行目录创建与上传文件,ChannelSftp
  • 学单片机能从事什么工作?
  • 【华为OD机考】华为OD笔试真题解析(20)--投篮大赛
  • 安卓广播的使用
  • Elasticsearch:简化大数据分析,使用Elasticsearch进行高效数据聚合
  • LeetCode hot 100—轮转数组