官方文档中文的 比较简单 直接上主要代码
@SpringBootApplication
public class SpringbootSentinelApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootSentinelApplication.class, args);
}
//配置规则
@PostConstruct
public void init() {
List rules = new ArrayList<>();
FlowRule flowRule = new FlowRule();
flowRule.setResource("doTest"); //针对那个资源设置规则
flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);//QPS或者并发数
flowRule.setCount(2); //QPS=5
rules.add(flowRule);
FlowRuleManager.loadRules(rules);
}
}
//使用
@Service
public class TestService {
@SentinelResource(value = "doTest",blockHandler="blockHandler",fallback = "blockHandler") //声明限流的资源
public String doTest(String name){
return "hello , "+name;
}
public String blockHandler(String name, BlockException e){ //降级,限流触发的
return "被限流了";
}
public String fallback(String name){ //熔断触发的
return "被降级了";
}
}
结合控制台实现动态路由
- 安装控制台的jar
java -Dserver.port=8888 -Dcsp.sentinel.dashboard.server=localhost:8888 - Dproject.name=sentinel-dashboard-1.8.0 -jar sentinel-dashboard-1.8.0.jar - 添加Nacos Datasouce依赖
com.alibaba.csp sentinel-datasource-nacos1.8.0 - 修改数据源加载方式
public class DataSourceInitFunc implements InitFunc{ private final String remoteAddress="192.168.216.128"; //Nacos 远程服务 hostprivate final String groupId="SENTINEL_GROUP"; //Nacos GroupID private final String dataId="com.gupaoedu.sentinel.demo.flow.rule"; @Override public void init() throws Exception { ReadableDataSource> flowRuleDataSource= new NacosDataSource<>(remoteAddress,groupId,dataId, source-> JSON.parseObject(source,new TypeReference>(){})); FlowRuleManager.register2Property(flowRuleDataSource.getProperty()); } }
- 在Nacos上添加配置 DataID Group 内容
git@github.com:David0101/springcloud-alibaba-example.git



