SpringCloudAlibaba完整章节六(熔断{Sentinel})

概述


阿里巴巴开源了 Sentinel 组件,实现了熔断器模式,Spring Cloud 对这一组件进行了整合。在微服务架构中,一个请求需要调用多个服务是非常常见的

什么是 Sentinel


随着微服务的流行,服务和服务之间的稳定性变得越来越重要。 Sentinel 以流量为切入点,从流量控制、熔断降级、系统负载保护等多个维度保护服务的稳定性。

Sentinel 的特征


  • 丰富的应用场景: Sentinel 承接了阿里巴巴近 10 年的 双十一大促流量 的核心场景,例如秒杀(即突发流量控制在系统容量可以承受的范围)、消息削峰填谷、实时熔断下游不可用应用等。
  • 完备的实时监控: Sentinel 同时提供实时的监控功能。您可以在控制台中看到接入应用的单台机器秒级数据,甚至 500 台以下规模的集群的汇总运行情况。
  • 广泛的开源生态: Sentinel 提供开箱即用的与其它开源框架/库的整合模块,例如与 Spring Cloud、Dubbo、gRPC 的整合。您只需要引入相应的依赖并进行简单的配置即可快速地接入 Sentinel。
  • 完善的 SPI 扩展点: Sentinel 提供简单易用、完善的 SPI 扩展点。您可以通过实现扩展点,快速的定制逻辑。例如定制规则管理、适配数据源等。

Feign 中使用 Sentinel


如果要在您的项目中引入 Sentinel,使用 group ID 为 org.springframework.cloud 和 artifact ID 为 spring-cloud-starter-alibaba-sentinel 的 starter。
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>

Sentinel 适配了 Feign 组件。但默认是关闭的。需要在配置文件中配置打开它,在配置文件增加以下代码:

feign:
  sentinel:
    enabled: true

在章节四的项目里,在 Service 中@FeignClient注解增加 fallback属性用来指定类

package com.lb.nacosconsumerfeign.service;

import com.lb.nacosconsumerfeign.service.fallback.FallbackServiceImpl;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

/**
 * @program: springcloud-alibaba
 * @description: FeignService的接口
 * @author: lb
 * @create: 2021-07-03 11:43
 **/
@FeignClient(value = "nacos-provider", fallback = FallbackServiceImpl.class)
public interface FeignService {

    @GetMapping("/test/{message}")
    String test(@PathVariable("message") String message);
}

创建熔断器类并实现对应的 Feign 接口


package com.lb.nacosconsumerfeign.service.fallback;

import com.lb.nacosconsumerfeign.service.FeignService;
import org.springframework.stereotype.Component;

/**
 * @program: springcloud-alibaba
 * @description: FallbackServiceImpl
 * @author: lb
 * @create: 2021-07-03 11:43
 **/
@Component
public class FallbackServiceImpl implements FeignService {
    @Override
    public String test(String message) {
        return "test fallback";
    }
}

目录结构
在这里插入图片描述
测试熔断器


此时我们关闭服务提供者,再次请求 http://localhost:9092/test/hi 浏览器会显示:

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值