Sentinel+Gateway 网关流控规则持久化到文件
提示
网关流控规则 != 流控规则
版本声明
<java.version>1.8</java.version>
<spring.boot.version>2.3.2.RELEASE</spring.boot.version>
<spring.cloud.version>Hoxton.SR8</spring.cloud.version>
<spring.cloud.alibaba.version>2.2.5.RELEASE</spring.cloud.alibaba.version>
sentinel控制台1.8.0
配置类
@Configuration
public class SentinelConfig {
public SentinelConfig() {
GatewayCallbackManager.setBlockHandler(
(exchange, ex) -> ServerResponse.status(HttpStatus.TOO_MANY_REQUESTS)
.contentType(MediaType.APPLICATION_JSON)
.body(fromValue(ReturnResult.error().code(429).message("限流")))
);
}
@PostConstruct
public void dynamicGatewayFlowRule() throws Exception {
String flowRulePath = "E:\\harmony\\springcloudalibabademo\\gateway\\src\\main\\resources\\gateway-flow-rule.json";
ReadableDataSource<String, Set<GatewayFlowRule>> ds = new FileRefreshableDataSource<>(
flowRulePath, source -> JSON.parseObject(source, new TypeReference<Set<GatewayFlowRule>>() {
})
);
GatewayRuleManager.register2Property(ds.getProperty());
WritableDataSource<Set<GatewayFlowRule>> wds = new FileWritableDataSource<>(flowRulePath, (t) -> JSON.toJSONString(t));
UpdateGatewayRuleCommandHandler.setWritableDataSource(wds);
}
}
持久化文件
/src/main/resources
在目录下创建gateway-flow-rule.json保存网关流控规则
配置文件
server:
port: 80
spring:
jackson:
time-zone: GMT+8
date-format: yyyy-MM-dd HH:mm:ss
application:
name: gateway
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
sentinel:
transport:
dashboard: 127.0.0.1:1716
port: 1719
gateway:
routes:
- id: nodeone
uri: lb://nodeone
predicates:
- Path=/nodeone/**
filters:
- StripPrefix=1
- id: nodetwo
uri: lb://nodetwo
predicates:
- Path=/nodetwo/**
filters:
- StripPrefix=1
- id: gateway
uri: lb://gateway
predicates:
- Path=/gateway/**
filters:
- StripPrefix=0
management:
endpoints:
web:
exposure:
include: "*"
核心依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>
</dependency>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2.2.5.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Hoxton.SR8</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>