springcloud sentinel持久化
1.POM
关键包 sentinel-datasource-nacos 持久化
它的将nacos的配置,加载到sentinel. 所以首先要在nacos上配置限流规则。
如果能够将sentinel 自动保存在nacos上。就更好了。毕竟Sentinel提供了一个UI配置界面。能够更直观的查看配置信息。
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-nacos</artifactId>
</dependency>
<!--openfeign-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!--nacos-config-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<!--nacos-discovery-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
2. yml
server:
port: 8887
spring:
profiles:
active: dev
application:
name: cloud-consumer-service
cloud:
sentinel:
transport:
dashboard: localhost:8858
port: 8719
datasource:
ds1: #自定义规则的一个标识
nacos:
server-addr: localhost:8848
data-id: cloud-consumer-service
group-id: DEFAULT_GROUP
data-type: json
rule-type: flow #流控
3. 主启动
@SpringBootApplication
@EnableDiscoveryClient
public class OrderMain {
public static void main(String[] args) {
SpringApplication.run(OrderMain.class,args);
}
}
4. 业务类
@RestController
@Slf4j
@RequestMapping("consumer")
public class SentinelController {
@GetMapping("/testHotKey")
@SentinelResource(value = "testHotKey",blockHandlerClass = CustomerBlockHandler.class, blockHandler = "handlerException")
public CommonResult testHotkey() {
return new CommonResult(200,"success");
}
}
4.全局降级处理方法
public class CustomerBlockHandler {
public static CommonResult handlerException(BlockException exception){
return new CommonResult(445,exception.getClass().getCanonicalName(),null);
}
}
5. nacos 配置

- resource:资源名称
- limitApp:来源应用
- grade:阀值类型,0表示线程数,1表示QPS
- count:单机阈值
- strategy:流控模式,0表示直接,1表示关联,2表示链路
- controllerBehavior:流控效果,0表示快速失败,1表示Warm up,2表示排队等待
- clusterMode:是否集群
6. sentinel
启动后,等待一会,看到流控规则

com.alibaba.cloud.sentinel.datasource.RuleType:
FLOW("flow", FlowRule.class),
DEGRADE("degrade", DegradeRule.class),
PARAM_FLOW("param-flow", ParamFlowRule.class),
SYSTEM("system", SystemRule.class),
AUTHORITY("authority", AuthorityRule.class),
GW_FLOW("gw-flow", "com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule"),
GW_API_GROUP("gw-api-group", "com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiDefinition");

浙公网安备 33010602011771号