[Spring-Cloud-Alibaba] Sentinel 整合RestTemplate & Feign
Sentinel API
Github : WIKI
- Sphu (指明要保护的资源名称)
- Tracer (指明调用来源,异常统计接口)
- ContextUtil(标示进入调用链入口)
- 流控规则(针对来源属性)
  @GetMapping("/test-sentinel-api")
      public String testSentinelAPI(@RequestParam(required = false) String a) {
          String resourceName = "test-sentinel-api";
          ContextUtil.enter(resourceName, "user-center-service");
          // 定义一个sentinel 保护的资源,名称是test-sentinel-api
          Entry entry = null;
          try {
              entry = SphU.entry(resourceName);
              // ...被保护的业务逻辑处理
              if (StringUtils.isEmpty(a)) {
                  // Sentinel 默认只会统计BlockException & BlockException的子类,如果想统计其他异常信息,添加Tracer
                  throw new IllegalArgumentException("A is not empty.");
              }
              return a;
              // block Exception: 如果被保护的资源被限流或者降级了,就会抛异常出去
          } catch (BlockException e) {
              log.error("我被限流啦!!{}", e);
              return "我被限流啦!!";
          } catch (IllegalArgumentException argEx) {
              // 统计当前异常发生次数 / 占比
              Tracer.trace(argEx);
              return "非法参数信息";
          } finally {
              if (entry != null) {
                  entry.exit();
              }
              ContextUtil.exit();
          }
      }
- 降级规则
  @GetMapping("/test-sentinel-api")
      public String testSentinelAPI(@RequestParam(required = false) String a) {
          // 定义一个sentinel 保护的资源,名称是test-sentinel-api
          Entry entry = null;
          try {
              entry = SphU.entry("test-sentinel-api");
              // ...被保护的业务逻辑处理
              if (StringUtils.isEmpty(a)) {
                  // Sentinel 默认只会统计BlockException & BlockException的子类,如果想统计其他异常信息,添加Tracer
                  throw new IllegalArgumentException("A is not empty.");
              }
              return a;
              // block Exception: 如果被保护的资源被限流或者降级了,就会抛异常出去
          } catch (BlockException e) {
              log.error("我被限流啦!!{}", e);
              return "我被限流啦!!";
          } catch (IllegalArgumentException argEx) {
              // 统计当前异常发生次数 / 占比
              Tracer.trace(argEx);
              return "非法参数信息";
          } finally {
              if (entry != null) {
                  entry.exit();
              }
          }
      }
Sentinel Annotation
源码:com.alibaba.csp.sentinel.annotation.aspectj.SentinelResourceAspect & com.alibaba.csp.sentinel.annotation.aspectj.AbstractSentinelAspectSupport
- SentinelResource使用该注解重构上述方法
      @GetMapping("/test-sentinel-resource")
      @SentinelResource(value = "test-sentinel-api", blockHandler = "blockException", fallback = "fallback")
      public String testSentinelResource(@RequestParam(required = false) String a) {
          // ...被保护的业务逻辑处理
          if (StringUtils.isEmpty(a)) {
              // Sentinel 默认只会统计BlockException & BlockException的子类,如果想统计其他异常信息,添加Tracer
              throw new IllegalArgumentException("A is not empty.");
          }
          return a;
      }
      /**
       * testSentinelResource BlockException method
       */
      public String blockException(String a, BlockException e) {
          log.error("限流了,{}", e);
          return "blockHandler 对应《限流规则》";
      }
      /**
       * testSentinelResource fallback method
       * {@link SentinelResource} #fallback 在< 1.6的版本中,不能补货BlockException
       */
      public String fallback(String a) {
          return "fallback 对应《降级规则》";
      }
RestTemplate 整合Sentinel
使用 @SentinelRestTemplate.
resttemplate.sentinel.enabled可以开关是否启用该注解。(开发阶段很有意义。)
源码:com.springframework.cloud.alibaba.sentinel.custom.SentinelBeanPostProcessor
@Bean
@LoadBalanced
@SentinelRestTemplate
public RestTemplate restTemplate() {
    return new RestTemplate();
}
@Autowired
private RestTemplate restTemplate;
...
Feign整合 Sentinel
配置文件中添加 feign.sentinel.enabled: true来开启

- 编写fallback 类,实现feign client
   @Component
   public class UserCenterFeignClientFallback implements IUserCenterFeignClient {
       @Override
       public UserDTO findById(Long userId) {
           UserDTO userDTO = new UserDTO();
           userDTO.setWxNickname("默认用户");
           return userDTO;
       }
   }
   @Slf4j
   @Component
   public class UserCenterFeignClientFallbackFactory implements FallbackFactory<IUserCenterFeignClient> {
       @Override
       public IUserCenterFeignClient create(Throwable cause) {
           return new IUserCenterFeignClient() {
               @Override
               public UserDTO findById(Long userId) {
                   log.warn("远程调用被限流/降级,{}", cause);
                   UserDTO userDTO = new UserDTO();
                   userDTO.setWxNickname("默认用户");
                   return userDTO;
               }
           };
       }
   }
- 应用fallback class
   /**
    * IUserCenterFeignClient for 定义 user-center feign client
    * fallbackFactory 可以拿到异常信息
    * fallback 无法拿到异常信息
    *
    * @author <a href="mailto:magicianisaac@gmail.com">Isaac.Zhang | 若初</a>
    * @since 2019/7/15
    */
   @FeignClient(name = "user-center",
           // fallback = UserCenterFeignClientFallback.class,
           fallbackFactory = UserCenterFeignClientFallbackFactory.class
   )
   public interface IUserCenterFeignClient {
       @GetMapping(path = "/users/{userId}")
       public UserDTO findById(@PathVariable Long userId);
   }
- 启动应用,设置流控规则,结果展示如下
   {
       id: 1,
       ...
       wxNickName: "默认用户"
   }
源码:org.springframework.cloud.alibaba.sentinel.feign.SentinelFeign
[Spring-Cloud-Alibaba] Sentinel 整合RestTemplate & Feign的更多相关文章
- Spring Cloud Alibaba Sentinel对RestTemplate的支持
		Spring Cloud Alibaba Sentinel 支持对 RestTemplate 的服务调用使用 Sentinel 进行保护,在构造 RestTemplate bean的时候需要加上 @S ... 
- Spring Cloud Alibaba Sentinel 整合 Feign 的设计实现
		作者 | Spring Cloud Alibaba 高级开发工程师洛夜 来自公众号阿里巴巴中间件投稿 前段时间 Hystrix 宣布不再维护之后(Hystrix 停止开发...Spring Cloud ... 
- Spring Cloud Alibaba Sentinel对Feign的支持
		Spring Cloud Alibaba Sentinel 除了对 RestTemplate 做了支持,同样对于 Feign 也做了支持,如果我们要从 Hystrix 切换到 Sentinel 是非常 ... 
- 0.9.0.RELEASE版本的spring cloud alibaba sentinel+feign降级处理实例
		既然用到了feign,那么主要是针对服务消费方的降级处理.我们基于0.9.0.RELEASE版本的spring cloud alibaba nacos+feign实例添油加醋,把sentinel功能加 ... 
- Spring Cloud Alibaba | Sentinel:分布式系统的流量防卫兵进阶实战
		Spring Cloud Alibaba | Sentinel:分布式系统的流量防卫兵进阶实战 在阅读本文前,建议先阅读<Spring Cloud Alibaba | Sentinel:分布式系 ... 
- Spring Cloud Alibaba | Sentinel: 分布式系统的流量防卫兵初探
		目录 Spring Cloud Alibaba | Sentinel: 分布式系统的流量防卫兵初探 1. Sentinel 是什么? 2. Sentinel 的特征: 3. Sentinel 的开源生 ... 
- Spring Cloud Alibaba | Sentinel: 服务限流基础篇
		目录 Spring Cloud Alibaba | Sentinel: 服务限流基础篇 1. 简介 2. 定义资源 2.1 主流框架的默认适配 2.2 抛出异常的方式定义资源 2.3 返回布尔值方式定 ... 
- Spring Cloud Alibaba | Sentinel: 服务限流高级篇
		目录 Spring Cloud Alibaba | Sentinel: 服务限流高级篇 1. 熔断降级 1.1 降级策略 2. 热点参数限流 2.1 项目依赖 2.2 热点参数规则 3. 系统自适应限 ... 
- Spring Cloud Alibaba | Sentinel:分布式系统的流量防卫兵动态限流规则
		Spring Cloud Alibaba | Sentinel:分布式系统的流量防卫兵动态限流规则 前面几篇文章较为详细的介绍了Sentinel的使用姿势,还没看过的小伙伴可以访问以下链接查看: &l ... 
- Spring Cloud Alibaba | Sentinel:分布式系统的流量防卫兵基础实战
		Spring Cloud Alibaba | Sentinel:分布式系统的流量防卫兵基础实战 Springboot: 2.1.8.RELEASE SpringCloud: Greenwich.SR2 ... 
随机推荐
- WPF应用程序如何重启当前的Application
			// Restart current process Method 1 System.Windows.Forms.Application.Restart(); Application.Current. ... 
- Sailfish OS 2.1.0 发布,带来重大的架构变化
			Sailfish OS 2.1.0 Iijoki 发布了. Iijoki通过引入Qt 5.6 UI框架.BlueZ 5 蓝牙堆栈和 64 位架构的基本实现,为Sailfish操作系统带来了重大的架构变 ... 
- winpcap在VS2012 Qt5 X64下的配置
			最近在学网络编程,想在windows下用Qt做个网络抓包工具,就要用到WinPcap,而我的电脑的系统是Win7 64位,qt版本是Qt 5.3.1 for Windows 64-bit (VS 20 ... 
- Android-小小设置永久解决程序因为未捕获异常而异常终止的问题
			(一) 前言各位亲爱的午饭童鞋,是不是经常因为自己的程序中出现未层捕获的异常导致程序异常终止而痛苦不已?嗯,是的.. 但是,大家不要怕,今天给大家分享一个东东可以解决大家这种困扰,吼吼! (二) Un ... 
- m3u8解析、转码、下载、合并
			m3u8解析.转码.下载.合并 现在网也上大多数视频需要下载都很麻烦,极少数是MP4,大多都是m3u8, 先说视频下载, pc端: 打开网页,点击视频播放,打开开发者工具,找到网络那一栏, 等整个网页 ... 
- Centos7离线安装mysql8
			linux版本:Centois7 mysql版本:5.7 一.安装 1.下载mysql离线安装包 下载地址:https://dev.mysql.com/downloads/mysql/ 选择如下: [ ... 
- Flink UDF
			本文会主要讲三种udf: ScalarFunction TableFunction AggregateFunction 用户自定义函数是非常重要的一个特征,因为他极大地扩展了查询的表达能力.本文除了介 ... 
- jQuery入门——注册事件
			下面举例介绍注册事件的几种方法: 以光棒效果为例 1.bind注册: <!DOCTYPE html> <html> <head> <meta charset= ... 
- 手把手docker部署java应用(初级篇)
			本篇原创发布于 Flex 的个人博客:点击跳转 前言 在没有 docker 前,项目转测试是比较麻烦的一件事.首先会化较长的时间搭建测试环境,然后在测试过程中又经常出现测试说是 bug,开发说无法 ... 
- 【Linux】一步一步学Linux——虚拟机简介和系统要求(04)
			目录 00. 目录 01. VMware Workstation Pro15介绍 02. Workstation Pro 的主机系统要求 03. 虚拟机网络连接支持 04. 参考 00. 目录 @ 0 ... 
