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
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,
"count": 5,
"strategy": 0,
"controlBehavior": 0,
"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 = "授权规则不通过";
}
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);
response.getWriter().write(res.toJSONString());
}
}
源码传送
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)