1. 准备工作
创建 SpringBoot
应用,命名为 Sentinel-Quick-start
1.1. Maven
依赖
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-core</artifactId>
<version>1.8.0</version>
</dependency>
1.2. Controller
层
@Controller
public class TestController {
@RequestMapping(path = {
"/hello"}, method = RequestMethod.GET)
@ResponseBody
public String hello() {
try {
// 设置一个资源名称为 Hello
Entry ignored = SphU.entry("Hello");
System.out.println("Hello Sentinel");
return "Hello Sentinel";
} catch (BlockException e) {
System.out.println("系统繁忙,请稍后");
e.printStackTrace();
return "系统繁忙,请稍后";
}
}
/**
* 使用代码编写流控规则,项目中不推荐使用,这是硬编码方式
*
* 注解 @PostConstruct 的含义是:本类构造方法执行结束后执行
*/
@PostConstruct
public void initFlowRule() {
/* 1.创建存放限流规则的集合 */
List<FlowRule> rules = new ArrayList<>();
/* 2.创建限流规则 */
FlowRule rule = new FlowRule();
/* 定义资源,表示 Sentinel 会对哪个资源生效 */
rule.setResource("Hello");
/* 定义限流的类型(此处使用 QPS 作为限流类型) */
rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
/* 定义 QPS 每秒通过的请求数 */
rule.setCount(2);
/* 3.将限流规则存放到集合中 */
rules.add(rule);