一、什么是Sentinel
Sentinel是阿里开源的项目,提供了流量控制、熔断降级、系统负载保护等多个维度来保障服务之间的稳定性。
官网地址:https://github.com/alibaba/Sentinel/wiki
-
Sentinel主要特性:
-
Sentinel与Hystrix的区别
Sentinel与Hystrix的区别见:https://yq.aliyun.com/articles/633786/
二、代码示例
直接上代码,代码示例已经提交GitHub
本文代码见:gitHub
注意:
- JDK >= 1.7;
- Sentinel版本为1.7.0;
引入jar包:
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-core</artifactId>
<version>1.7.0</version>
</dependency>
1.限流
关于限流的使用和介绍见:Sentinel流量控制
流量控制(Flow Control),原理是监控应用流量的QPS或并发线程数等指标,当达到指定阈值时对流量进行控制,避免系统被瞬时的流量高峰冲垮,保障应用高可用性。
下面写个简单的示例,看看如何使用Sentinel实现限流。
首先写个简单的订单查询接口,用于后续接口限流示例:
@Component
public class OrderQueryService {
public String queryOrderInfo(String orderId) {
System.out.println("获取订单信息:" + orderId);
return "return OrderInfo :" + orderId;
}
}
@Controller
@RequestMapping("order")
public class OrderController {
@Autowired
private OrderQueryService orderQueryService;
@RequestMapping("/getOrder")
@ResponseBody
public String queryOrder1(@RequestParam("orderId") String orderId) {
return orderQueryService.queryOrderInfo(orderId);
}
}
正常情况下,调用OrderController中订单查询接口,会返回订单信息,如何控制接口访问的QPS在2以下呢?Sentienl限流提供了以下实现方式:
Sentienl如何使用 。
首先需要定义限流规则,比如对哪个接口进行限流,限制的QPS为多少,限制调用方app是什么等:
public void initFlowQpsRule() {
List<FlowRule> rules = new ArrayList<FlowRule>();
FlowRule rule1 = new FlowRule();
rule1.setResource(KEY);
// QPS控制在2以内
rule1.setCount(2);
// QPS限流
rule1.setGrade(RuleConstant.FLOW_GRADE_QPS);
rule1.setLimitApp("default");
rules.add(rule1);
FlowRuleManager.loadRules(rules);
}
限流实现方式有多种,本文只列出常见两种:
(1)限流实现方式一: 抛出异常的方式定义资源
此方式对代码侵入性较高,需要在接口调用的地方通过try-catch
风格的API对代码进行包装:
/**
* 限流实现方式一: 抛出异常的方式定义资源
*
* @param orderId
* @return
*/
@RequestMapping("/getOrder1")
@ResponseBody
public String queryOrder2(@RequestParam("orderId") String orderId) {
Entry entry = null;
// 资源名
String resourceName = KEY;
try {
// entry可以理解成入口登记
entry = SphU.entry(resourceName);
// 被保护的逻辑, 这里为订单查询接口
return orderQueryService.queryOrderInfo(orderId);
} catch (BlockException blockException) {
// 接口被限流的时候, 会进入到这里
log.warn("---getOrder1接口被限流了---, exception: ", blockException);
return "接口限流, 返回空";
} finally {
// SphU.entry(xxx) 需要与 entry.exit() 成对出现,否则会导致调用链记录异常
if (entry != null) {
entry.exit();
}
}
}
测试,当QPS > 2时,接口返回:
查看日志输出:
(2)限流实现方式二: 注解方式定义资源
上述通过try-catch
风格的API可以实现限流,但是对代码侵入性太高,推荐使用注解的方式来实现。下文若不做注明,默认都会采用注解的方式实现。
关于注解的使用见:Sentinel注解使用
首先需要引入支持注解的jar包:
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-annotation-aspectj</artifactId>
<version>${sentinel.version}</version>
</dependency>
Sentinel切面类配置:
@Configuration
public class SentinelAspectConfiguration {
@Bean
public SentinelResourceAspect sentinelResourceAspect() {
return new SentinelResourceAspect();
}
}
在接口OrderQueryService中,使用注解实现订单查询接口的限流:
/**
* 订单查询接口, 使用Sentinel注解实现限流
*
* @param orderId
* @return
*/
@SentinelResource(value = "getOrderInfo", blockHandler = "handleFlowQpsException",
fallback = "queryOrderInfo2Fallback")
public String queryOrderInfo2(String orderId) {
// 模拟接口运行时抛出代码异常
if ("000".equals(orderId)) {
throw new RuntimeException();
}
System.out.println("获取订单信息:" + orderId);
return "return OrderInfo :" + orderId;
}
/**
* 订单查询接口抛出限流或降级时的处理逻辑
*
* 注意: 方法参数、返回值要与原函数保持一致
* @return
*/
public String handleFlowQpsException(String orderId, BlockException e) {
e.printStackTrace();
return "handleFlowQpsException for queryOrderInfo2: " + orderId;
}
/**
* 订单查询接口运行时抛出的异常提供fallback处理
*
* 注意: 方法参数、返回值要与原函数保持一致
* @return
*/
public String queryOrderInfo2Fallback(String orderId, Throwable e) {
return "fallback queryOrderInfo2: " + orderId;
}
blockHandler = "handleFlowQpsException"
用来处理Sentinel 限流/熔断等错误;fallback = "queryOrderInfo2Fallback"
用来处理接口中业务代码所有异常(如业务代码异常、sentinel限流熔断异常等);
注:以上两种处理方法中方法名、参数都需与受保护的函数保持一致。
测试:
/**
* 限流实现方式二: 注解定义资源
*
* @param orderId
* @return
*/
@RequestMapping("/getOrder2")
@ResponseBody
public String queryOrder3(@RequestParam("orderId") String orderId) {
return orderQueryService.queryOrderInfo2(orderId);
}
测试结果在这里就不贴出来了,结果类似。
除了流量控制以外,对调用链路中不稳定的资源进行熔断降级也是保障高可用的重要措施之一。
由于调用关系的复杂性,如果调用链路中的某个资源不稳定,最终会导致请求发生堆积。Sentinel 熔断降级会在调用链路中某个资源出现不稳定状态时(例如调用超时或异常比例升高),对这个资源的调用进行限制,让请求快速失败,避免影响到其它的资源而导致级联错误。当资源被降级后,在接下来的降级时间窗口之内,对该资源的调用都自动熔断(默认行为是抛出 DegradeException
)。
关于熔断降级的介绍见:Sentinel熔断降级。
下面就使用基于注解的方式实现Sentinel的熔断降级的demo。
@Component
@Slf4j
public class GoodsQueryService {
private static final String KEY = "queryGoodsInfo2";
/**
* 模拟商品查询接口
*
* @param spuId
* @return
*/
@SentinelResource(value = KEY, blockHandler = "blockHandlerMethod", fallback = "queryGoodsInfoFallback")
public String queryGoodsInfo(String spuId) {
// 模拟调用服务出现异常
if ("0".equals(spuId)) {
throw new RuntimeException();
}
return "query goodsinfo success, " + spuId;
}
public String blockHandlerMethod(String spuId, BlockException e) {
log.warn("queryGoodsInfo222 blockHandler", e.toString());
return "queryGoodsInfo error, blockHandlerMethod res: " + spuId;
}
public String queryGoodsInfoFallback(String spuId, Throwable e) {
log.warn("queryGoodsInfo222 fallback", e.toString());
return "queryGoodsInfo error, return fallback res: " + spuId;
}
@PostConstruct
public void initDegradeRule() {
List<DegradeRule> rules = new ArrayList<>();
DegradeRule rule = new DegradeRule();
rule.setResource(KEY);
// 80s内调用接口出现异常次数超过5的时候, 进行熔断
rule.setCount(5);
rule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT);
rule.setTimeWindow(80);
rules.add(rule);
DegradeRuleManager.loadRules(rules);
}
}
// 测试类
@Controller
@RequestMapping("goods")
public class GoodsController {
@Autowired
private GoodsQueryService goodsQueryService;
@RequestMapping("/queryGoodsInfo")
@ResponseBody
public String queryGoodsInfo(@RequestParam("spuId") String spuId) {
String res = goodsQueryService.queryGoodsInfo(spuId);
return res;
}
}