基础
见官方文档吧
安装
见官方文档
先下载控制台并启动
java -Dserver.port=8131 -Dcsp.sentinel.dashboard.server=localhost:8080 -Dproject.name=sentinel-dashboard -jar sentinel-dashboard.jar
客户端启动时需要指定控制台
-Dcsp.sentinel.dashboard.server=consoleIp:port
规则配置的方法
1、在控制台进行配置(配置会丢失)
2、在代码中进行配置(硬编码)
3、使用动态配置中心
规则配置拉取的方法
1、拉模式:就是通过文件读取配置
2、推模式:利用第三方的配置中心(比如nacos),有变更时将配置推送给客户端
项目使用
定义资源
直接在方法中添加注解
@SentinelResource(value = "listQuestionBankVOByPage", blockHandler = "handleBlockException", fallback = "handleFallback")另外,如果方法中存在参数的话,会自动将参数个数和具体参数传递下去
比如:
@SentinelResource("myMethod")
public Result doSomething(String uid, int type) {
// some logic here...
}如果想要传递特定参数,就需要手动编码,
例如下面这个对IP限流的例子。
// 基于 IP 限流
String remoteAddr = request.getRemoteAddr();
Entry entry = null;
try {
entry = SphU.entry("listQuestionVOByPage", EntryType.IN, 1, remoteAddr);
// 被保护的业务逻辑
} catch (BlockException ex) {
// 资源访问阻止,被限流或被降级
if (ex instanceof DegradeException) {
return handleFallback(questionQueryRequest, request, ex);
}
// 限流操作
return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "访问过于频繁,请稍后再试");
} finally {
if (entry != null) {
entry.exit(1, remoteAddr);
}
}
定义规则
1、在管理页面端进行配置
这里不再
2、编码的方式
新建一个类,并指定启动后执行,将规则加入到规则管理器中
@PostConstruct
public void initRules() throws Exception {
// 加载规则
initFlowRules();
}
public void initFlowRules() {
// IP查看题目限流
ParamFlowRule rule = new ParamFlowRule("listQuestionVOByPage")
.setParamIdx(0) // 对第0个参数进行统计
.setCount(5) // 每分钟最多多少次
.setDurationInSec(60); //统计周期
ParamFlowRuleManager.loadRules(Collections.singletonList(rule));
}
}3、采用文件读取的方法
见官方文档
4、采用动态配置中心
例如引入 nacos
见文档