1. 服务端搭建
- 下载地址: https://github.com/alibaba/Sentinel/releases
- 使用java -jar sentinel-dashboard-1.6.0.jar来启动,访问地址localhost:8080
账号密码都为 sentinel
控制台如下
2. 客户端搭建
- springboot项目添加下面的依赖
<!--sentinel-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
<version>0.2.2.RELEASE</version>
</dependency>
- yml中添加配置
spring:
application:
name: sentinel-server
cloud:
sentinel:
transport:
dashboard: localhost:8080 #sentinel地址
#eager: true
3. 启动项目,访问接口
4. 对方法进行限流,熔断与降级
- 添加注解支持的配置
@Bean
public SentinelResourceAspect sentinelResourceAspect(){
return new SentinelResourceAspect();
}
- 方法上添加注解
@Service
public class SentinelServiceImpl implements SentinelService {
@Override
@SentinelResource(value = "test", blockHandler = "exceptionHandler")
public String test() {
return "sucessful";
}
// 限流与熔断处理
public String exceptionHandler(BlockException ex){
System.out.println("进入熔断");
return "handler->Exception ->success";
}
}
当方法被限流后会进入 blockHandler中的方法,同时服务端会显示注解下的资源点
- 对方法进行降级
@Service
public class SentinelServiceImpl implements SentinelService {
@Override
@SentinelResource(value = "test2", fallback = "fallbackHandler")
public String test2() {
System.out.println(1/0);
return "sucessful + test2";
}
// 降级处理
public String fallbackHandler(){
return "faild + test2";
}
}
- 降级配置 查看sentinel-service,可以看到簇点链路名为test2的资源点。然后点击”降级“按钮,为该资源设置降级规则。这里使用异常比例策略,比例设置为0.5(即:50%的异常率),时间窗口设置为2(秒)。
- 验证熔断降级,根据上面的降级策略配置,当test2方法的调用QPS >= 5,如果异常率超过50%,那么后续2秒内的调用将直接触发熔断降级