1、何为网关
spring cloud gateway是spring全家桶里面的网关组件,再介绍gateway之前,先说一下网关的作用。
网关本来是网络中的概念,可以简单的理解为是进入一个网络的入口。在微服务中,网关的作用也与此类似。
众所周知,单体应用拆成多个微服务后,每个微服务都有自己独立的地址,如果微服务很多,面对众多地址,调用方无法分辨,会给调用方带来使用上的困扰。此时,我们可以在微服务前面加上网关,所有对微服务的调用都通过网关转发,服务调用方始终只能看到一个地址,也就是网关的地址。
2、网关作用
网关是所有服务的入口,可以完成以下功能:
- 服务路由,负载均衡;
- 安全控制;
- 流量控制,熔断;
- 日志监控;
- 数据统计;
- 请求过滤;
3、快速上手
gateway上手特别简单,只需要引入相关依赖,配置文件里面配置好规则,就可以了。
3.1 项目依赖
pom文件如下:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.7.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>gateway_demo</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Hoxton.SR12</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
</dependencies>
3.2 配置文件
gateway使用配置文件指定网关规则,包括路由规则、拦截哪些URL等。
下面是一个简单的配置规则:
server:
port: 7000 # gateway服务端口
spring:
application:
name: gateway-demo # 应用名称
main:
web-application-type: reactive # gateway使用响应式web,如果使用非响应式,启动报错
cloud:
gateway:
# 路由规则
routes:
- id: route-demo # 路由ID,唯一
uri: http://localhost:8079 # 目标URI,路由到微服务的地址
predicates: # 断言(判断条件)
- Path=/** # 匹配对应URL的请求,将匹配到的请求追加在目标URI之后,这里拦截了所有请求
3.3 测试
在8079端口上,提供了一个echo服务,比如:
当启动了spring cloud gateway之后,gateway可以将所有请求路由到8079端口上,比如: