1 通用资源保护
package com.tzb.restorder.controller;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.tzb.restorder.entity.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
@RequestMapping("/order")
public class OrderController {
@Autowired
private RestTemplate restTemplate;
/**
*
* @param id
* @return
*/
@SentinelResource(blockHandler = " orderBlockHandler",fallback = "orderFallback")
@GetMapping("/buy/{id}")
public Product findById(@PathVariable Long id){
if(id !=1L){
throw new RuntimeException("错误");
}
return restTemplate.getForObject("http://service-product/product/1", Product.class);
}
/**
* 定义降级逻辑
* @param id
* @return
*/
public Product orderBlockHandler(Long id){
Product product = new Product();
product.setProductName("触发熔断的降级方法");
return product;
}
public Product orderFallback(Long id){
Product product = new Product();
product.setProductName("抛出异常执行的降级方法");
return product;
}
}
1.1 配置降级规则
-
马上访问1
-
5s 后再次刷新,熔断已经关闭了,此时正常访问
1.2 配置说明
在需要被保护的方法上使用@SentinelResource
注解进行熔断配置。与Hystrix不同的是,Sentinel对抛出异常和熔断降级做了更加细致的区分,通过blockHandler
指定熔断降级方法,通过fallback
指定触发异常执行的降级方法。
2 加载本地配置
对于@SentinelResource
的其他配置如下表:
- 注:1.6.0 之前的版本 fallback 函数只针对降级异常( DegradeException )进行处理,不能针对业务异常进行处理。
- 特别地,若 blockHandler 和 fallback 都进行了配置,则被限流降级而抛出 BlockException 时只会进入 blockHandler 处理逻辑。若未配置 blockHandler 、fallback 和 defaultFallback ,则被限流降级时会将 BlockException 直接抛出。
一条限流规则主要由下面几个因素组成:
- resource:资源名,即限流规则的作用对象
- count: 限流阈值
- grade: 限流阈值类型(QPS 或并发线程数)
- limitApp: 流控针对的调用来源,若为 default 则不区分调用来源
- strategy: 调用关系限流策略
- controlBehavior: 流量控制效果(直接拒绝、Warm Up、匀速排队)
java代码 RuleConstant
配置文件添加如下配置
#通过文件读取限流规则
spring.cloud.sentinel.datasource.ds1.file.file=classpath: flowrule.json
spring.cloud.sentinel.datasource.ds1.file.data-type=json
spring.cloud.sentinel.datasource.ds1.file.rule-type=flow
[
{
"resource": "orderFindById",
"controlBehavior": 0,
"count": 1,
"grade": 1,
"limitApp": "default",
"strategy": 0
}
]
- 重新启动