项目介绍
基于springboot + gateway + nacos + sentinel 搭建的微服务网关
持久化限流降级规则到nacos
项目技术
- springboot
- gateway
- nacos
- sentinel
项目功能
应对高并发请求,我们打造接口一般的做法是缓存,限流,降级,熔断,黑白名单等。
- 限流:限制请求访问速率,避免服务被压垮
- 降级:当某个服务不可用时,返回一个友好的提示,避免服务被压垮
- 缓存:将热点数据存储到缓存中,提高访问速度
- 熔断:当某个服务不可用时,快速返回,避免服务被压垮
- 黑白名单:限制某些IP的访问,或者限制某些接口的访问
代码详细
网关配置
# Tomcat
server:
port: 8086
# Spring
spring:
application:
# 应用名称
name: gateway
profiles:
# 环境配置
active: dev
main:
allow-bean-definition-overriding: true
cloud:
nacos:
discovery:
# 服务注册地址
server-addr: localhost:8848
# config:
# # 配置中心地址
# server-addr: localhost:8848
# # 配置文件格式
# file-extension: yml
# # 共享配置
# shared-configs:
# - application-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}
sentinel:
#心跳启动
eager: true
transport:
#sentinel控制台访问路径
dashboard: localhost:8082
port: 8082
#sentinel数据源配置(从哪里获取限流规则)
datasource:
ds:
nacos:
server-addr: localhost:8848
#限流规则配置文件的名称
dataId: gateway-sentinel-flow-limit
groupId: sentinel
data-type: json
rule-type: GW_FLOW #网关限流配置
ds1:
nacos:
server-addr: localhost:8848
#限流规则配置文件的名称
dataId: gateway-sentinel-degrade
groupId: sentinel
data-type: json
rule-type: DEGRADE #降级配置
gateway:
discovery:
locator:
lowerCaseServiceId: true
enabled: true
routes:
# 服务
- id: demo
uri: lb://demo
predicates:
- Path=/api/demo/**
filters:
- RewritePath=/api/?(?<segment>.*),/${segment}
nacos配置
限流持久化配置
[
{
"resource":"demo",
"limitApp":"default",
"grade":1,
"count":1,
"strategy":0,
"controlBehavior":0,
"clusterMode":"false"
}
]
降级持久化配置
[
{
"resource": "demo",
"count": 1000,
"grade": 0,
"timeWindow": 10,
"minRequestAmount": 10,
"statIntervalMs": 1000,
"slowRatioThreshold": 0.2
}
]
请求调用
jmeter压测会报对应的错误提示
ok(0, "成功"),
NO_PARAM(201, "传入参数缺失,请检查"),
ERR_PARAM(202, "传入参数异常,请检查"),
VALID_FAIL_PARAM(203, "参数校验异常"),
SENTINEL_FLOW_ERROR(427, "请求过于频繁,被限流了"),
SENTINEL_DEGRADE_ERROR(428, "请求过于频繁,被降级了"),
SENTINEL_PARAM_FLOW_ERROR(429, "热点数据请求过于频繁"),
SENTINEL_SYSTEM_ERROR(430, "请求过于频繁,触发系统限制"),
SENTINEL_AUTHORITY_ERROR(431, "授权规则不通过"),
UNKNOWN(999, "操作失败!!");
对应的github代码地址: https://github.com/zbmzbm/springboot-gateway-sentinel-nacos 本地可直接引入测试