一,blockHandler
使用blockHandler指定发生BlockException时进入的方法,方法需满足以下条件
- 必须是 public 修饰
- 返回类型、参数与原方法一致,并在最后加BlockException 类型的参数
- 默认需和原方法在同一个类中
代码
package com.liu.controller;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Slf4j
public class SentinelTestController {
@GetMapping(value = "/hello")
@SentinelResource(value = "hello",blockHandler = "handleException")
public String hello() {
log.info("****hello-hello-hello-hello-hello");
return "Hello Sentinel";
}
/**
* 自定义异常策略
* 返回值和参数要跟目标函数一样,参数可以追加BlockException
*/
public String handleException( BlockException exception){
log.info("flow exception{}",exception.getClass().getCanonicalName());
return "达到阈值了,不要再访问了!";
}
}
此种方式,每个服务类至少要写一个异常处理方法,并且每个服务资源,必须写处理方法,加大了代码量
blockHandlerClass
将限流和降级方法外置到单独的类中,需满足以下条件:
- 方法必须 使用public static 修饰
- 满足blockHandler处理条件
- 编写类
package com.liu.exception;
import com.alibaba.csp.sentinel.slots.block.BlockException;
public class ConstomerBlockHandler {
public static String blockHandler(BlockException exception) {
return "被限流了哦!!!by ConstomerBlockHandler";
}
}
package com.liu.controller;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.liu.exception.ConstomerBlockHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Slf4j
public class SentinelTestController {
@GetMapping(value = "/hello")
@SentinelResource(value = "hello",blockHandler = "handleException")
public String hello() {
log.info("****hello-hello-hello-hello-hello");
return "Hello Sentinel";
}
@GetMapping(value = "/hello2")
//blockHandler 对应处理类的方法名
@SentinelResource(value = "hello2",blockHandler = "blockHandler",blockHandlerClass = ConstomerBlockHandler.class)
public String hello2() {
log.info("****hello2-hello2-hello-hello-hello");
return "Hello2 Sentinel";
}
/**
* 自定义异常策略
* 返回值和参数要跟目标函数一样,参数可以追加BlockException
*/
public String handleException( BlockException exception){
log.info("flow exception{}",exception.getClass().getCanonicalName());
return "达到阈值了,不要再访问了!";
}
}
fallback
用于在抛出异常的时候提供fallback处理逻辑。fallback函数可以针对所有类型的异常(除了 exceptionsToIgnore 里面排除掉的异常类型)进行处理,满足条件同blockHandler大致一致(BlockException替换为Throwable)。
fallbackClass
处理fallback的类。大致和blockHandlerClass一样
defaultFallback
用于通用的 fallback 逻辑。默认fallback函数可以针对所有类型的异常进行处理。若同时配置了 fallback 和 defaultFallback,以fallback为准。
exceptionsToIgnore
指定排除掉哪些异常。排除的异常不会计入异常统计,也不会进入fallback逻辑,而是原样抛出。