微服务网关的作用
微服务的网关在结构上是整个项目的统一入口,便于对用户的身份进行鉴权,对各个模块进行限流等操作。在功能上网关相当于路由转发+过滤器。
基于以上,网关的作用包括:
1、提供统一的访问入口,能降低受攻击面。
2、提供统一的跨域解决方案
3、提供统一的日志记录操作,能够统一监控各个模块
4、提供统一的权限认证服务
5、提供统一的限流服务,能够防止雪崩发生
网关的配置
基本配置
server:
port: 8080 # 网关服务端口
spring:
application:
name: gateway-service # 服务名称
cloud:
gateway:
routes:
- id: service-route # 路由 ID
uri: lb://service-name # 目标服务 URI,lb 表示使用负载均衡
predicates:
- Path=/api/** # 路径匹配
filters:
- StripPrefix=1 # 去除路径前缀
服务发现配置
spring:
cloud:
gateway:
discovery:
locator:
enabled: true # 启用服务发现
lower-case-service-id: true # 服务 ID 小写
负载均衡配置
spring:
cloud:
loadbalancer:
ribbon:
enabled: false # 禁用 Ribbon
熔断与降级配置
spring:
cloud:
gateway:
routes:
- id: service-route
uri: lb://service-name
predicates:
- Path=/api/**
filters:
- name: CircuitBreaker # 使用熔断器
args:
name: myCircuitBreaker # 熔断器名称
fallbackUri: forward:/fallback # 降级 URI
安全配置
spring:
security:
oauth2:
resourceserver:
jwt:
issuer-uri: http://auth-server/issuer # JWT 签发者 URI
日志配置
logging:
level:
org.springframework.cloud.gateway: DEBUG # 网关日志级别
跨域配置
spring:
cloud:
gateway:
globalcors:
corsConfigurations:
'[/**]':
allowedOrigins: "*" # 允许所有来源
allowedMethods: "*" # 允许所有方法
allowedHeaders: "*" # 允许所有头
超时配置
spring:
cloud:
gateway:
httpclient:
connect-timeout: 1000 # 连接超时(毫秒)
response-timeout: 5s # 响应超时
重试配置
spring:
cloud:
gateway:
routes:
- id: service-route
uri: lb://service-name
predicates:
- Path=/api/**
filters:
- name: Retry # 使用重试过滤器
args:
retries: 3 # 重试次数
statuses: BAD_GATEWAY # 重试状态码
限流配置
spring:
cloud:
gateway:
routes:
- id: service-route
uri: lb://service-name
predicates:
- Path=/api/**
filters:
- name: RequestRateLimiter # 使用限流过滤器
args:
redis-rate-limiter.replenishRate: 10 # 每秒请求数
redis-rate-limiter.burstCapacity: 20 # 突发请求数
网关路由配置
url
uri: lb://service-name # 使用负载均衡
uri: http://localhost:8080 # 具体 URL
predicates
predicates:
- Path=/api/**
method
predicates:
- Method=GET
- Between=9:00,17:00 # 只在 9:00 到 17:00 之间允许请求
- After=9:00 # 在 9:00 之后允许请求
- Before=17:00 # 在 17:00 之前允许请求
- After=2023-12-31T23:59:59 # 在 2023 年 12 月 31 日 23:59:59 之后允许请求
filter
去除路径前缀
filters:
- StripPrefix=1
添加请求头
filters:
- AddRequestHeader=X-Request-Id, 123
添加响应头
filters:
- AddResponseHeader=X-Response-Id, 456
请求限流
filters:
- name: RequestRateLimiter
args:
redis-rate-limiter.replenishRate: 10
redis-rate-limiter.burstCapacity: 20
自定义元数据metadata
metadata:
response-time: 1000
order优先级
数字越小优先级越高
order: 1