基于Sentinel的服务保护

通用资源保护#

(1) 案例准备#

复制工程 shop_service_order 并命名为 shop_service_order_rest_sentinel

(2)引入依赖#

需要注意SpringCloud-Alibaba与SpringCloud的版本关系
推荐使用的依赖关系版本

父工程引入alibaba实现的SpringCloud#

<dependency>
  <groupId>com.alibaba.cloud</groupId>
  <artifactId>spring-cloud-alibaba-dependencies</artifactId>
  <version>2.1.0.RELEASE</version>
  <type>pom</type>
  <scope>import</scope>
</dependency>

子工程中引入sentinel#

<dependency>
  <groupId>com.alibaba.cloud</groupId>
  <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>

(3) 配置熔断降级方法#

复制代码
  @GetMapping("/buy/{id}")
  @SentinelResource(value="order",blockHandler = "orderblockHandler",fallback
= "orderfallback")
  public Product order(@PathVariable Long id) {
      return restTemplate.getForObject("http://shop-service-
product/product/1", Product.class);
  }

  //降级方法
  public Product orderblockHandler(Long id) {
      Product product = new Product();
      product.setId(-1l);
      product.setProductName("触发熔断降级方法");
      return product;
  }

  //降级方法
  public Product orderfallback(Long id) {
      Product product = new Product();
      product.setId(-1l);
      product.setProductName("触发抛出异常方法");
      return product;
  }
复制代码
在需要被保护的方法上使用@SentinelResource注解进行熔断配置。与Hystrix不同的是,Sentinel对抛出异常和熔断降级做了更加细致的区分,通过 blockHandler 指定熔断降级方法,通过 fallback 指定触发异常执行的降级方法。对于@SentinelResource的其他配置如下表:
注:1.6.0 之前的版本 fallback 函数只针对降级异常( DegradeException )进行处理,不能针对业务异常进行处理。
特别地,若 blockHandler 和 fallback 都进行了配置,则被限流降级而抛出 BlockException 时只会进入 blockHandler 处理逻辑。若未配置 blockHandler 、 fallback 和 defaultFallback ,则被限流降级时会将 BlockException 直接抛出。
posted @   1640808365  阅读(57)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示
主题色彩