依赖
<!--网关-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!--nacos服务发现依赖-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
配置
server:
port: 88# 网关端口
spring:
application:
name: gateway # 服务名称
cloud:
nacos:
server-addr: localhost:8848 # nacos地址
gateway:
routes: # 网关路由配置
- id: user-service # 路由id,自定义,只要唯一即可
# uri: http://127.0.0.1:8081 # 路由的目标地址 http就是固定地址
uri: lb://userservice # 路由的目标地址 lb就是负载均衡,后面跟服务名称
predicates: # 路由断言,也就是判断请求是否符合路由规则的条件
- Path=/api/** # 这个是按照路径匹配,只要以/user/开头就符合要求
filter: # 过滤器
- RewritePath=/api/(?<segment>.*), /newpath/$\{segment} # 路径重写
default-filters: # 全局过滤器
- AddRequestHeader=Default-Header, DefaultValue
启动类注册nacos发现注解
断言
predicates:
- Path=/api/** # 匹配路径
- Method=GET,POST # 限制 HTTP 方法
- Host=**.example.com # 匹配域名
- Header=X-Request-Id, \d+ # 请求头匹配
- Query=token # 请求参数必须包含 token
- Before=2025-12-31T23:59:59.999Z # 在某个时间之前生效
- After=2025-01-01T00:00:00.000Z # 在某个时间之后生效
- Between=2025-01-01T00:00:00.000Z, 2025-12-31T23:59:59.999Z # 时间范围
- RemoteAddr=192.168.1.1/24 # 限制 IP 地址
- Weight=group1, 5 # 按指定权重负载均衡,group1 组内权重为 5
- Cookie=SESSIONID, abc123 # 包含名为 SESSIONID 的 Cookie,且值必须匹配 abc123
- XForwardedRemoteAddr=192.168.1.0/24 # 从 X-Forwarded-For 请求头解析 IP,限制来源于
192.168.1.0/24 网段
过滤器
filters:
- StripPrefix=1 # 去掉第一级路径
- AddRequestHeader=Token, abc123 # 给请求添加请求头
- AddResponseHeader=X-Response, OK # 给响应添加请求头
- RewritePath=/api/(?<segment>.*), /newpath/$\{segment} # 路径重写
- SetStatus=404 # 修改返回状态码
- Retry=5 # 失败重试 5 次
- RequestRateLimiter=redis-rate-limiter # 基于 Redis 令牌桶算法限流
CORS 跨域配置
spring:
cloud:
gateway:
globalcors:
corsConfigurations:
'[/**]': # 匹配所有路径
allowedOrigins: "https://example.com" # 允许的来源
allowedMethods: # 允许的请求方法
- GET
- POST
- PUT
- DELETE
allowedHeaders: "*" # 允许所有请求头
allowCredentials: true # 允许携带 Cookie
配置类处理跨域
@Configuration
public class CorsConfig {
/**
* 跨域配置
* @return
*/
@Bean
public CorsWebFilter corsWebFilter(){
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
// 允许哪些头部请求跨域:全部
corsConfiguration.addAllowedHeader("*");
// 允许哪些请求方式跨域:所有
corsConfiguration.addAllowedMethod("*");
// 允许哪些请求来源跨域:任意
corsConfiguration.addAllowedOrigin("*");
// 是否允许携带cookie跨域:是
corsConfiguration.setAllowCredentials(true);
source.registerCorsConfiguration("/**",corsConfiguration);
return new CorsWebFilter(source);
}
}