微服务 springcloudAlibab之Sentinel 系统规则 自定义限流

系统规则

就是在整个应用上定义一个大的规则

在这里插入图片描述

@SentinelResource 自定义限流逻辑处理

1. @SentinelResource 资源限流

定义:使用了@SentinelResource注解的blockHandler属性,定义出现限流效果的属性

  1. 编写测试类
package com.gek.cloudalibabasentinelservice8401.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
public class SentinelResourceTestController {

    @GetMapping("/byResource")
    @SentinelResource(value = "byResource",blockHandler = "handler_resource")
    public String byResource(){
        return "------byResource";
    }
    
    public String handler_resource(){
        return "系统繁忙";
    }
}

  1. 定义限流规则:资源名就是sentinelResource的value值
    在这里插入图片描述

  2. 测试结果
    在这里插入图片描述

2. @SentinelResource url路径限流

定义:使用@SentinelResource 注解,但是不使用blockHandler属性,系统默认会处理限流异常的方法

  1. 编写测试代码
 @GetMapping("/byTest")
    @SentinelResource(value = "/byTest")
    public String byTest(){
        return "------byTest";
    }
  1. 新建限流规则
    在这里插入图片描述
  2. 测试结果
    在这里插入图片描述

自定义限流逻辑处理

@SentinelResource除了blockHandler可以设置自定义限流处理逻辑方法以外,还提供另外一个属性来设置限流处理逻辑类型blockHandlerClass属性,此属性中设置的方法必需为 static 函数,否则无法解析。

具体逻辑
  1. 新建自定义的处理限流的类(注意处理异常的类必须是static静态方法)
package com.gek.cloudalibabasentinelservice8401.handler;

import com.alibaba.csp.sentinel.slots.block.BlockException;

/**
 * 此类用来处理自定义逻辑处理
 */
public class CustomerBlockHandler {

    public static String handlerException1(BlockException blockException){
        return "handlerException1:系统异常,请稍后重试!";
    }

    public static String handlerException2(BlockException blockException){
        return "handlerException2:网络崩溃了,请稍后重试!";
    }
}

  1. 新建测试方法自定义异常处理类
   /**
     *blockHandlerClass表示自定义的限流异常类
     *  blockHandler表示调用的哪个方法
     * @return
     */
    @GetMapping("/byCustomer")
    @SentinelResource(value = "byCustomer",blockHandlerClass = CustomerBlockHandler.class,blockHandler = "handlerException1")
    public String bycustomer(){
        return "-------bycustomer";
    }
  1. 定义限流规则
    在这里插入图片描述
  2. 测试结果
    在这里插入图片描述

fallback(java异常)

fallback处理的是java异常

blockHandler(sentinel异常 )

blockHandler用来处理sentinel限流异常

exceptionsToIgnore属性

  • exceptionsToIgnore(since 1.6.0):用于指定哪些异常被排除掉,不会计入异常统计中,也不会进入 fallback 逻辑中,而是会原样抛出。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值