⼀、网关介绍
使用服务网关作为接口服务的统⼀代理,前端通过网关完成服务的统⼀调用
- 网关可以干什么?
路由:接口服务的统⼀代理,实现前端对接⼝服务的统⼀访问
过滤:对用户请求进行拦截、过滤(用户鉴权)、监控
限流:限制用户的访问流量 - 常用的网关
Nginx
Spring Cloud Netflix zuul
Spring Cloud Gateway
Nginx通常被用作应用服务器网关(Tomcat集群,Redis集群,前端浏览器网关),
zuul或者gateway通常被用作服务网关(springcloud微服务)
二、Gateway使用
Route: 路由是网关的基本组成部分,它是由id、目标uri、断⾔组成,如果断⾔为true,则匹配该路由,转向到当前路由的URI
Predicate:断⾔,用户请求的匹配规则
Filter:过滤器,用于对请求进行前置、后置处理(可以在网关实现对请求或相应的加工处理)
- 添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
- 添加配置
server:
port: 9999
spring:
application:
name: gateway-server
cloud:
gateway:
routes:
# 配置api-service1路由规则
# id随便起
- id: api-service1
uri: http://localhost:8001
# 断言规则:路径里有product的跳转
# http://localhost:9999/product/query —> http://localhost:8001/product/query
predicates:
- Path=/product/**
# 配置api-service2路由规则
- id: api-service2
uri: http://localhost:8002
predicates:
- Path=/order/**
三、Predicate断言
SpringCloud Gateway提供了多种断⾔匹配的⽅式:
After
Before
Between
Cookie
Header
Host
Method
Path
Query
RemoteAddr
Weight
3.1 Path
根据请求路径的正则匹配
server:
port: 9999
spring:
application:
name: gateway-server
cloud:
gateway:
routes:
# 配置api-service1路由规则
# id随便起
- id: api-service1
uri: http://localhost:8001
# 断言规则:路径里有product的跳转
# http://localhost:9999/product/query —> http://localhost:8001/product/query
predicates:
- Path=/product/**
# 配置api-service2路由规则
- id: api-service2
uri: http://localhost:8002
predicates:
- Path=/order/**
3.2 Query
根据请求携带的参数匹配路由
spring:
application:
name: gateway-server
cloud:
gateway:
routes:
- id: aaa
uri: http://localhost:8001
predicates:
# http://localhost:9999/product/query?name=wang ---> http://localhost:8001/product/query?name=wang
- Query=name
- id: bbb
uri: http://localhost:8002
predicates:
#如果请求url中带有pwd参数 ---> http://localhost:8002
- Query=pwd
3.3 Header
根据Header中携带的参数匹配
spring:
application:
name