限流降级

使用 Sentinel 保护您的应用,防止应用因个别服务的突发流量过载而出现稳定性问题。

Sentinel 是什么

随着微服务的流行,服务和服务之间的稳定性变得越来越重要。Sentinel 是面向分布式、多语言异构化服务架构的流量治理组件,主要以流量为切入点,从流量路由、流量控制、流量整形、熔断降级、系统自适应过载保护、热点流量防护等多个维度来帮助开发者保障微服务的稳定性。

一、示例架构说明

接口定义:

  1. public interface FooService {
  2. String sayHello(String name);
  3. }

接口实现:

  1. @DubboService(timeout = 3000)
  2. public class FooServiceImpl implements FooService {
  3. @Override
  4. public String sayHello(String name) {
  5. return String.format("Hello, %s at %s", name, LocalDateTime.now());
  6. }
  7. }

限流配置:

  1. FlowRule flowRule = new FlowRule(FooService.class.getName())
  2. .setCount(10)
  3. .setGrade(RuleConstant.FLOW_GRADE_QPS);
  4. FlowRuleManager.loadRules(Collections.singletonList(flowRule));

二、快速启动示例

Step 1: 下载源码

  1. git clone -b master https://github.com/apache/dubbo-samples.git
  2. cd ./dubbo-samples-sentinel/

Step 2: 构建用例

执行 maven 命令,打包 demo 工程

  1. mvn clean package

Step 3: 启动 Provider

  1. java -classpath ./target/dubbo-samples-sentinel-1.0-SNAPSHOT.jar org.apache.samples.sentinel.FooProviderBootstrap

Step 4: 启动 OrderService

  1. java -classpath ./target/dubbo-samples-sentinel-1.0-SNAPSHOT.jar org.apache.samples.sentinel.FooConsumerBootstrap

可以看到控制台输出中,Blocked 代表已经开始拦截。

  1. Success: Hello, dubbo at 2022-08-08T15:42:40.809
  2. Success: Hello, dubbo at 2022-08-08T15:42:40.812
  3. Success: Hello, dubbo at 2022-08-08T15:42:40.815
  4. Success: Hello, dubbo at 2022-08-08T15:42:40.818
  5. Success: Hello, dubbo at 2022-08-08T15:42:40.821
  6. Success: Hello, dubbo at 2022-08-08T15:42:40.823
  7. Success: Hello, dubbo at 2022-08-08T15:42:40.826
  8. Success: Hello, dubbo at 2022-08-08T15:42:40.828
  9. Success: Hello, dubbo at 2022-08-08T15:42:40.830
  10. Success: Hello, dubbo at 2022-08-08T15:42:40.834
  11. Blocked
  12. Blocked
  13. Blocked
  14. Blocked
  15. Blocked

关于 Sentinel 的更多使用方式可以参考:Sentinel 为 Dubbo 服务保驾护航Sentinel 官网

最后修改 December 16, 2022: Fix check (#1736) (97972c1)