资讯专栏INFORMATION COLUMN

[Spring-Cloud-Alibaba] Sentinel 整合RestTemplate &am

libin19890520 / 2869人阅读

摘要:开发阶段很有意义。源码整合配置文件中添加来开启编写类,实现默认用户远程调用被限流降级,默认用户应用定义可以拿到异常信息无法拿到异常信息若初启动应用,设置流控规则,结果展示如下默认用户源码

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 {

    @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 Isaac.Zhang | 若初
    * @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

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/75492.html

相关文章

  • Spring Cloud Alibaba整合Sentinel流控

    摘要:前面我们都是直接通过集成的依赖,通过编码的方式配置规则等。对于集成到中阿里已经有了一套开源框架,就是用于将一系列的框架成功的整合到中。但这也是在学习过程中遇到的一个问题,还是得通过调试源码的方式去发现问题的原因。 前面我们都是直接通过集成sentinel的依赖,通过编码的方式配置规则等。对于集成到Spring Cloud中阿里已经有了一套开源框架spring-cloud-alibaba...

    ytwman 评论0 收藏0
  • springcloud(二)——spring-cloud-alibaba集成sentinel入门

    摘要:介绍随着微服务的流行,服务和服务之间的稳定性变得越来越重要。以流量为切入点,从流量控制熔断降级系统负载保护等多个维度保护服务的稳定性。完备的实时监控同时提供实时的监控功能。您只需要引入相应的依赖并进行简单的配置即可快速地接入。 Sentinel 介绍 随着微服务的流行,服务和服务之间的稳定性变得越来越重要。 Sentinel 以流量为切入点,从流量控制、熔断降级、系统负载保护等多个维度...

    darkbug 评论0 收藏0
  • [Spring-Cloud-Alibaba] Sentinel 规则持久化

    摘要:在之前的练习中,只要应用重启,就需要重新配置,这样在我们实际的项目是非常不实用的,那么有没有办法把我们配置的规则保存下来呢答案是,那么接下来,给大家来介绍如何将规则持久化。重新启动测试效果添加流控规则查看同步的配置 在之前的练习中,只要应用重启,就需要重新配置,这样在我们实际的项目是非常不实用的,那么有没有办法把我们配置的规则保存下来呢?答案是YES,那么接下来,给大家来介绍如何将Se...

    only_do 评论0 收藏0
  • Spring Cloud Alibaba 新版本发布:众多期待内容整合打包加入!

    摘要:在之后,也终于发布了最新的版本。该版本距离上一次发布,过去了整整个月下面就随我一起看看,这个大家期待已久的版本都有哪些内容值得我们关注。如果是用户,同时也是阿里云这些产品的用户,那么直接使用还是非常方便的。 在Nacos 1.0.0 Release之后,Spring Cloud Alibaba也终于发布了最新的版本。该版本距离上一次发布,过去了整整4个月!下面就随我一起看看,这个大家期...

    不知名网友 评论0 收藏0
  • Spring Cloud Alibaba Sentinel对Feign的支持

    摘要:得到得到类得到类得到调用的服务名称检查和属性省略部分代码中的方法里面进行熔断限流的处理。在的方法中进行的包装。 Spring Cloud Alibaba Sentinel 除了对 RestTemplate 做了支持,同样对于 Feign 也做了支持,如果我们要从 Hystrix 切换到 Sentinel 是非常方便的,下面来介绍下如何对 Feign 的支持以及实现原理。 集成 Feig...

    wthee 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<