一、Gateway 工作原理
我们来看一下官网的一个示例图
客户端向 Spring Cloud Gateway 发出请求。
第一步:请求要先到 Gateway Handler Mapping,这里将这个路由先做匹配处理。
第二步:路径匹配之后,请求接着来到 Gateway Web Handler,而这个是通过特定于请求的过滤器链运行请求。过滤器链它也分两种,请求进来的时候要走前置过滤器,在业务完成后,再通过后置过滤器出去。
二、Gateway HelloWorld
之前我们已经弄了两个业务模块,一个是商品模块,一个是订单模块。这里我们需要单独给网关引入一个模块。
模块名称:microservice-gateway-7200
pom 依赖
<!-- Gateway -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!-- 热部署 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
application.yml
server:
port: 7200
servlet:
context-path: /
tomcat:
uri-encoding: UTF-8
spring:
application:
name: gateway-server
cloud:
gateway:
routes: # 路由规则定义
- id: service-commodity # 商品模块的路由 id
uri: http://localhost:1002/ # 路由地址
predicates: # 断言规则
- Path=/commodity/**
- id: service-orders # 订单模块的路由 id
uri: http://localhost:1001/ # 路由地址
predicates: # 断言规则
- Path=/orders/**
这里我们网关用 7200,下面的话是两个 Gateway 路由配置,下面我们会说,先这么写上。
启动类
@SpringBootApplication
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
}
三、测试
启动 Eureka Server 集群,1001 订单模块,1002 商品模块(一定要启动这两个,不然上面的 Gateway 配置白弄了)
首先通过普通的方式我们添加一个订单。
这个肯定是没有问题的。
然后我们用 Gateway 网关进行请求测试。
可以看到,我们通过请求 Gateway 网关,直接可以访问到我们的订单服务。(同理,商品的也可以进行访问,自己去试试看)
四、Gateway 配置说明
spring:
cloud:
gateway:
routes: # 路由规则定义
- id: service-commodity # 商品模块的路由 id
uri: http://localhost:1002/ # 路由地址
predicates: # 断言规则
- Path=/commodity/**
- id: service-orders # 订单模块的路由 id
uri: http://localhost:1001/ # 路由地址
predicates: # 断言规则
- Path=/orders/**
1. routes:这个是路由规则定义,可以定义一个,或者多个,它这里是支持数组。每一个规则需要包含 id、uri、predicates 这些。
2. id 是指的路由规则的 id,而且在一个路由规则里面,这个 id 一定是唯一的!!!
接着是 uri,这个就是路由匹配之后,要请求的路由地址。
最后是 predicates,它的话是路由断言,我们就是根据这些断言来进行匹配路由的,我们上面的这个使用的是:路径路由,也就是说,只要请求是 /commodity/xxxx... 或者是 /orders/xxx... ,我们都可以匹配到。
Gateway 给我们提供了很多的断言,详细可以去看官网说明:Spring Cloud Gateway,或者看我下一篇博客~~
这一讲就讲到这里,有问题可以联系我:QQ 2100363119,欢迎大家访问我的个人网站:https://www.lemon1234.com
最近网站已经做好,并且已经上线,欢迎各位留言~~