springcloud网关的常见功能有哪些 - responseTimeout: 5000ms
在微服务架构中,网关是一个非常重要的角色。它作为服务的入口,负责请求的路由、负载均衡、熔断降级等功能。Spring Cloud Gateway 是 Spring Cloud 官方推出的一个高性能、轻量级的 API 网关,它基于 Spring WebFlux 构建,提供了丰富的功能特性。介绍 Spring Cloud Gateway 的常见功能。
1. 请求路由
请求路由是网关最基本的功能之一。Spring Cloud Gateway 支持多种路由策略,如:固定路径、请求头匹配、请求参数匹配等。通过配置文件或注解的方式,可以轻松实现请求的路由。
spring:
cloud:
gateway:
routes:
- id: user-service
uri: lb://user-service
predicates:
- Path=/user/**
- id: order-service
uri: lb://order-service
predicates:
- Path=/order/**
2. 服务熔断与降级
服务熔断与降级是保障系统稳定性的重要手段。Spring Cloud Gateway 支持对服务进行熔断和降级处理,当某个服务出现故障时,可以快速切换到备用服务,保证系统的高可用性。
spring:
cloud:
gateway:
retry:
enabled: true
maxAttempts: 3
backoffPeriod: 1000ms
3. 限流与防火墙 拼多多帮助力入口
为了防止恶意请求或者突发流量导致的系统过载,Spring Cloud Gateway 支持限流和防火墙功能。通过配置限流规则,可以限制单个用户或IP在一定时间内的请求次数;通过配置防火墙规则,可以过滤掉不符合要求的请求。
spring:
cloud:
gateway:
httpclient:
connectTimeout: 5000ms
responseTimeout: 5000ms
maxRequestSize: 1024MB
retry:
enabled: true
maxAttempts: 3
backoffPeriod: 1000ms
hystrix:
command: default
execution:
isolation: THREAD
retryer: com.netflix.hystrix.HystrixRetryerFactory.class
retryPolicy: com.netflix.hystrix.HystrixRetryPolicy.Factory
properties: {}
exceptionPercentageThreshold: 60 # 失败率达到60%时触发熔断降级
requestVolumeThreshold: 20 # 每秒请求数达到20时触发熔断降级
circuitBreakerTimeoutInMilliseconds: 10000 # 熔断器超时时间(毫秒)
sleepWindowInMilliseconds: 5000 # 滑动窗口大小(毫秒)
errorThresholdPercentageThreshold: 80 # 错误率达到80%时触发熔断降级
4. 过滤器与认证授权
Spring Cloud Gateway 支持自定义过滤器和认证授权功能。通过编写自定义过滤器,可以实现对请求和响应的拦截处理;通过配置认证授权规则,可以实现对用户的权限控制。
spring:
security:
oauth2:
client:
registration: my-client-registration # OAuth2 Client Registration Bean 名称
client-id: my-client-id # OAuth2 Client ID
client-secret: my-client-secret # OAuth2 Client Secret
scope: read,write # OAuth2 Scopes(作用域)列表,多个用逗号分隔,默认为空字符串表示不设置作用域范围,只使用授权码模式(Authorization Code Grant)获取访问令牌。此处设置为 "read,write" 则表示该客户端拥有读写权限。如果要使用其他授权方式(如密码模式),则需要在配置文件中添加相应的配置项。例如:`authorization-grant-type=password`, `token-info-uri=http://localhost:8080/oauth/token_info`, `user-info-uri=http://localhost:8080/user`, `jwk-set-uri=http://localhost:8080/.well-known/jwks.json`。同时还需要在代码中实现对应的逻辑来处理这些配置项。