sentinel以流量为切入点,从流量控制,熔断降级、系统负载保护等多个维度保护服务的稳定性;
应用场景:消息的削峰填谷、集群流量控制、实时熔断下游不可用应用等;
sentinel还能进行实时的监控功能。
一、部署sentinel
拉取镜像:
docker pull bladex/sentinel-dashboard:latest
查看镜像:
docker images
启动sentinel
docker run --name sentinel -d -p 8858:8858 ID
启动后通过 http:// ip:8858 访问 初始账号密码都是sentinel
sentinel本质就是一个springboot应用
二、使用sentinel
1、将依赖添加进入 common项目和网关项目中
因为网关到微服务的过程中,网关需要做限流,而且微服务本身也需要做限流,通常网关所在的机器性能需要更加强,才能承担所有微服务的管理。
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
2、在各个微服务模块中配置sentinel
# sentinel限流配置
sentinel:
transport:
dashboard: 47.100.54.149:8858
port: 9999
配置在springcloud的下一级
sentinel是懒加载的模式,只有向访问了,才会在控制台生成记录;
3、在sentinel里面设置流控策略
4、自定义降级数据
由于异常后sentinel只是抛出一串 blocked by sentinel ,不能具体的显示异常情况,因此需要自定义降级数据,当发生异常的时候,利用自定义异常显示异常信息。
/**
* 这个异常处理器需要被spring进行扫描
*
* 具体的是通过实现 BlockExceptionHandler接口,并重写其方法
*/
@Component
public class SentinelBlockHandle implements BlockExceptionHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
JsonData jsonData = null;
// 流控异常
if(e instanceof FlowException){
jsonData = JsonData.buildResult(BizCodeEnum.CONTROL_FLOW);
// 降级异常
}else if (e instanceof DegradeException){
jsonData = JsonData.buildResult(BizCodeEnum.CONTROL_DEGRADE);
}else if(e instanceof AuthorityException){
jsonData = JsonData.buildResult(BizCodeEnum.CONTROL_AUTH);
}
response.setStatus(200);
CommonUtil.sendJsonMessage(response,jsonData);
}
}
5、限流配置持久化到
<!-- 限流持久化到nacos-->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-nacos</artifactId>
</dependency>
在common和gataway中添加。
datasource:
ds1:
nacos:
server-addr: 192.168.0.88:8848
data-id: ${spring.application.name}.json
group-id: DEFAULT_GROUP
data-type: json
rule-type: flow
配置到nacos的配置中心