网关作为内部系统外的一层屏障,对内起到-定的保护作用,限流便是其中之- - .网关层的限流可以简单地针对不同路由进行限流,也可针对业务的接口进行限流,或者根据接口的特征分组限流。
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
server:
port: 8088
spring:
application:
name: api-gateway
# gateway的配置
cloud:
gateway:
routes:
- id: order_route #路由的唯一标识,路由到order
uri: lb://order-service # 需要转发的地址 lb指的是从nacos中按照名称获取微服务,并遵循负载均衡策略 order-service服务名
#断言规则 用于路由规则的匹配
predicates:
- Path=/order/**
# http://localhost:8088/order-serve/order/add 路由到↓
# http://localhost:8020/order-serve/order/add
#- After=2020-10-19T09:07:00.660+08:00[Asia/Shanghai]
#- Header=X-Request-Id, \d+
#- Method=GET
#- Query=name,xushu|zhuge
#- CheckAuth = xushu
#filters:
#- AddRequestHeader=X-Request-color,red
#- AddRequestParameter=color,blue
#- PrefixPath=/mall-order #添加前缀对应微服务需要配置context-path
#- StripPrefix=1 # 转发之前,去掉第一次的路径
# http://localhost:8020/order/add
#- RedirectTo=302, https://www.baidu.com
#- SetStatus= 404
#- CheckAuth=xushu
#- id: stock_route
# 配置Nacos
# 跨域的配置
# globalcors:
# cors-configurations:
# '[/**]': # 允许跨域访问的资源
# allowedOrigins: "*" #跨域允许的来源 例如:www.smsm.com
# allowedMethods:
# - GET
# - POST
# - PUT
#配置Nacos
nacos:
discovery:
server-addr: 127.0.0.1:8848
username: nacos
password: nacos
# 配置sentinel
sentinel:
transport:
dashboard: 127.0.0.1:8858
下载:sentinel-dashboard-1.8.0.jar
https://github.com/alibaba/Sentinel/releases
运行jar包
java -Dserver.port=8858 -Dsentinel.dashboard.auth.username=xushu -Dsentinel.dashboard.auth.password=123456 -jar C:\Users\ZHENG\Desktop\sentinel-dashboard-1.8.0.jar
账号:xushu
密码:123456
http://127.0.0.1:8088/order/add
访问:http://127.0.0.1:8088/order/add
不断点击连续访问
@Configuration
public class GatewayConfig {
@PostConstruct //设置初始化的时候
public void init(){
BlockRequestHandler blockRequestHandler = new BlockRequestHandler() {
@Override
public Mono<ServerResponse> handleRequest(ServerWebExchange serverWebExchange, Throwable t) {
System.out.println(t);
HashMap<String,String> map = new HashMap<String,String>();
map.put("code",HttpStatus.TOO_MANY_REQUESTS.toString());
map.put("message","限流了");
//自定义的异常处理
return ServerResponse.status(HttpStatus.OK)
.contentType(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromValue(map))
;
}
};
GatewayCallbackManager.setBlockHandler(blockRequestHandler);
}
}
访问:http://127.0.0.1:8088/order/get
访问:http://127.0.0.1:8088/order/get
连续不断访问
scg:
fallback:
mode: response
response-body: "{code:'',messageL:''}"
为了保证Gateway的高可用性,可以同时启动多个Gateway实例进行负载,在Gateway的.上游使用Nginx或者F5进行负载转发以达到高可用。
更多【spring-Java之SpringCloud Alibaba【八】【Spring Cloud微服务Gateway整合sentinel限流】】相关视频教程:www.yxfzedu.com