环境配置

一般gateway单独自己一个模块:

  1. 引入依赖:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
</dependencies>
  1. 写application.yml文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# Spring Boot 核心配置
spring:
# 应用名称,在服务注册与调用时标识此服务的身份
application:
name: gateway

# Spring Cloud 相关配置
cloud:
# Nacos 服务注册与发现配置
nacos:
discovery:
# Nacos 服务注册中心的地址,此处为本地默认端口
server-addr: 127.0.0.1:8848

# Spring Profile 配置,用于激活额外的配置文件
profiles:
# include 表示额外加载名为 "route" 的配置文件(如 application-route.yml)
# 通常将路由规则单独拆分,便于管理和维护
include: route

# 服务器监听端口,此处设置为 80(HTTP 默认端口),方便直接访问无需输入端口号
server:
port: 80
  1. 写application-route.yml文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
spring:
cloud:
gateway:
routes: # 路由列表,Gateway 核心配置,定义请求如何转发
# 第一个路由:订单服务
- id: order # 路由唯一标识符,自定义,通常与服务名对应
uri: lb://service-order # 转发目标 URI,lb:// 表示使用服务发现(LoadBalance)从 Nacos 获取服务实例
predicates: # 断言(匹配条件),满足条件才执行该路由
- Path=/api/order/** # 路径匹配:当请求路径以 /api/order/ 开头时,匹配此路由(** 表示任意层级子路径)

# 第二个路由:商品服务
- id: product # 路由 ID
uri: lb://service-product # 目标服务名,通过 Nacos 负载均衡调用 service-product 服务
predicates:
- Path=/api/product/** # 匹配 /api/product/ 开头的请求

断言

就是配置厚葬的predicates,需要满足条件才能通过gateway。

过滤器

将filter的配置放在于predicates同级的yml文件中:

1
2
3
filters:  
- RewritePath=/api/order/?(?<segment>.*), /${segment} # 将路径 /api/order/{任意内容} 重写为 /{任意内容}
- OnceToken=X-Response-Token,jwt

GlobalFilter

GlobalFilter 通常,全局过滤器在网关层 用于 拦截所有请求,而局部过滤器用于单个路由。
eg:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
@Component
@Slf4j
public class RTGlobalFilter implements GlobalFilter, Ordered {

@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
ServerHttpResponse response = exchange.getResponse();
String uri = request.getURI().toString();
long startTime = System.currentTimeMillis();

log.info("请求【{}】开始,时间{}", uri, startTime);
//=============上面是前置逻辑==================

Mono<Void> filter = chain.filter(exchange).doFinally(r -> {
long endTime = System.currentTimeMillis();
log.info("请求【{}】结束,时间{},耗时:{}ms", uri, endTime, endTime - startTime);
});

return filter;
}

@Override
public int getOrder() {
return 0;
}
}

自定义filter

遇到了再说

CORS-跨域处理

添加配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
spring:
cloud:
gateway:
globalcors: # 全局跨域配置,作用于所有路由
cors-configurations: # 跨域配置映射,可针对不同路径设置不同策略
'[/**]': # 路径匹配模式,/** 表示匹配所有请求路径(即全局生效),[/**]必须加方括号 [],否则 YAML 解析可能会出错。
# 允许的源(Origin)模式,此处为 * 表示允许所有域名访问
# 注意:allowedOriginPatterns 支持通配符模式(如 *.example.com),比 allowedOrigins 更灵活
allowedOriginPatterns: '*'
# 允许的请求头,* 表示允许客户端发送所有头信息
allowedHeaders: '*'
# 允许的 HTTP 方法,* 表示允许所有方法(GET、POST、PUT、DELETE 等)
allowedMethods: '*'