sentinel 高可用流控
sentinel 是阿里开源的一款系统流控系统,可以在线配置本系统请求访问请求控制
软件下载
运行
nohup java -jar sentinel-dashboard-1.7.2.jar --server.port=19080 > console.log 2>&1 &
登录
localhost:19080 用户密码:sentinel/sentinel
界面展示
登录成功界面
资源限流界面
资源限流操作界面
与spring cloud项目集成
因为sentinel流控默认使用内存,如果不把流控规则放入nacos,sentinel重启后,需要再重新设置一遍
pom加入依赖
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-transport-simple-http</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-nacos</artifactId>
</dependency>
bootstrap.yml 配置
spring:
cloud:
sentinel:
# 取消控制台懒加载
eager: true
transport:
# 控制台地址
dashboard: 1.0.0.0:19080
# nacos配置持久化
datasource:
ds1:
nacos:
server-addr: 1.0.0.0:19200
dataId: ${spring.application.name}-sentinel
groupId: SENTINEl_GROUP
data-type: json
rule-type: flow
在nacos中编写流控规则
[
{
"resource": "/testA", # 资源名称
"limitApp": "default", #来源应用
"grade": 1, #阀值类型,0-线程数,1-qps
"count": 5, #单机阀值
"strategy": 0, #流控模式,0-直接,1-关联,2-链路
"controlBehavior": 0, #流控效果,0-快速失败,1-warm up,2-排队等待
"clusterMode": false #是否集群
}
]
sentinel自带的被限流提示不好,我们可以自定提示
@Component
public class CustomUrlBlockHandler implements BlockExceptionHandler {
@Override
public void handle(HttpServletRequest httpServletRequest, HttpServletResponse response, BlockException ex) throws Exception {
String msg = null;
if (ex instanceof FlowException) {
msg = "限流了";
} else if (ex instanceof DegradeException) {
msg = "降级了";
} else if (ex instanceof ParamFlowException) {
msg = "热点参数限流";
} else if (ex instanceof SystemBlockException) {
msg = "系统规则(负载/...不满足要求)";
} else if (ex instanceof AuthorityException) {
msg = "授权规则不通过";
}
// http状态码
response.setStatus(500);
response.setCharacterEncoding("utf-8");
response.setHeader("Content-Type", "application/json;charset=utf-8");
response.setContentType("application/json;charset=utf-8");
JSONObject res = new JSONObject();
res.put("code",500);
res.put("msg",msg);
// spring mvc自带的json操作工具,叫jackson
response.getWriter().write(res.toJSONString());
}
}