在 Spring Cloud 等框架中,可以通过 @SentinelResource
注解来定义资源,并配置相应的流量控制规则。这种方式非常直观,可以直接在业务代码中声明资源,并且支持配置 fallback 函数来处理被限流或降级的情况。
Sentinel 支持通过配置文件(如 YAML 或 properties)来静态配置各种规则,包括流量控制规则、熔断降级规则等。这种方式适用于规则相对固定,不需要频繁变更的场景。
Sentinel 提供了控制台用于动态地管理和推送规则到客户端。你可以通过 Sentinel 控制台配置各种规则,并实时推送到各个服务节点,实现规则的动态更新,无需重启服务。
对于分布式系统,Sentinel 支持集群限流,通过 Sentinel 服务发现模块(如与 Nacos、Zookeeper 集成)来发现和管理集群中的服务实例,实现全局的流量控制。例如,可以设置集群整体的入口流量阈值,防止整个系统过载。
Sentinel 支持基于热点参数(如某个URL参数值的访问频率过高)的限流,能够针对特定的参数值进行流量控制,而不是简单地对整个接口进行限流,更加精细化。
Sentinel 可以根据系统的实际负载情况动态调整限流阈值,比如通过监控系统的CPU、内存等资源使用情况,自动调整流量控制策略,以保护系统在高负载时不被压垮。
在 Redis 场景中,Sentinel 也常用于Redis主从切换的监控和管理,但这是Redis自身的一个高可用解决方案,与上述流量控制无关。不过,如果在使用Redis作为数据存储的同时,也想对访问Redis的操作进行流量控制,可以将Sentinel的流量控制逻辑应用于访问Redis的客户端代码中。
Sentinel 提供了丰富的代码实现方式,可以方便地在应用程序中进行流量控制和熔断降级。
@SentinelResource
注解来定义流量控制规则和熔断降级规则。@SentinelResource(value = "hello", blockHandler = "handleBlock", fallback = "handleFallback")
public String hello() {
// 方法逻辑
}
<filter>
<filter-name>SentinelWebServletFilter</filter-name>
<filter-class>com.alibaba.csp.sentinel.adapter.servlet.CommonFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SentinelWebServletFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<dubbo:protocol name="dubbo" port="20880" >
<dubbo:parameter key="sentinel.filter.enabled" value="true"/>
</dubbo:protocol>
spring:
cloud:
gateway:
default-filters:
- name: Sentinel
routes:
- id: sentinel_route
uri: http://localhost:8080
predicates:
- Path=/hello/**
通过以上的实现方式,可以轻松地在代码中使用 Sentinel 来实现流量控制和熔断降级的功能,提高应用程序的稳定性和可靠性。
在Spring Boot项目中实现Sentinel的流量控制和熔断降级可以按照以下步骤进行:
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
@EnableCircuitBreaker
注解,开启熔断降级功能@SpringBootApplication
@EnableCircuitBreaker
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@RestController
public class DemoController {
@GetMapping("/hello")
@SentinelResource(value = "hello", blockHandler = "helloBlockHandler")
public String hello() {
return "Hello, Sentinel!";
}
public String helloBlockHandler(BlockException e) {
return "Blocked by Sentinel";
}
}
@Configuration
public class SentinelConfig {
@PostConstruct
public void init() {
// 定义资源规则
FlowRule flowRule = new FlowRule("hello");
flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
flowRule.setCount(10);
// 定义熔断降级规则
RuleManager.loadRules(Collections.singletonList(flowRule));
}
}
application.yml
或application.properties
中配置Sentinel的相关参数,例如:spring:
cloud:
sentinel:
transport:
dashboard: localhost:8080
datasource:
ds1:
nacos:
server-addr: localhost:8848
其中,dashboard
配置项指定Sentinel的控制台地址,datasource
配置项指定Sentinel的数据源,这里使用Nacos作为数据源。
综上,Sentinel 通过灵活的规则配置、动态规则推送、丰富的限流策略以及对微服务架构的深度集成,实现了高效且可扩展的服务保护方案。