一. 入门使用
1. 引入依赖
- 父工厂
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2.1.0.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
- 子工厂
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
2. 配置文件
spring:
cloud:
sentinel:
eager: true # 取消控制台懒加载
transport:
dashboard: 192.168.1.100:8080
3. 编码
在要保护的方法上添加 @SentinelResource 注解
/** @SentinelResource
* blockHandler : 声明熔断时调用的降级方法
* fallback : 抛出异常时调用的降级方法
* value : 自定义名称
* */
@SentinelResource(value = "queryById",blockHandler = "sentinelBack",fallback ="sentinelBackEX" )
@GetMapping("/{id}")
public User queryById(@PathVariable("id") Long id,
@RequestHeader(value = "Truth", required = false) String truth) throws InterruptedException {
System.out.println("truth: " + truth);
if (id== 1){
throw new RuntimeException("用户信息异常");
}
// Thread.sleep(1000); //休眠一秒,模拟业务堵塞
return userService.queryById(id);
}
降级方法
/* sentinel
定义降级逻辑
hystrix和sentinel
熔断执行的降级方法
抛出异常执行的降级方法
*/
public User sentinelBack(@PathVariable("id") Long id,
@RequestHeader(value = "Truth", required = false) String truth) {
log.info("------User sentinel 服务降级 ------");
User user = userService.queryById(id);
user.setAddress("User sentinel 服务降级");
return user;
}
public User sentinelBackEX(@PathVariable("id") Long id,
@RequestHeader(value = "Truth", required = false) String truth) {
log.info("------User sentinel 服务降级 抛出异常 ------");
User user = userService.queryById(id);
user.setAddress("User sentinel 服务降级 抛出异常");
return user;
}