前言
上篇讲到了Sentinel 简单使用和Sentinel dashboard 控制台整合,这篇主要讲到通过注解和自定义编码来实现限流。
Sentinel 服务保护配置类
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
/**
* Sentinel服务保护配置
* @author terry
* @version 1.0
* @date 2022/5/22 15:31
*/
@Configuration
public class SentinelConfig {
@PostConstruct
public void init() {
List<FlowRule> rules = new ArrayList<>();
FlowRule rule1 = new FlowRule();
rule1.setResource("userQps");
// QPS控制在1,每秒钟运行1个请求
rule1.setCount(1);
// QPS限流
rule1.setGrade(RuleConstant.FLOW_GRADE_QPS);
rule1.setLimitApp("default");
rules.add(rule1);
FlowRuleManager.loadRules(rules);
}
}
通过注解实现限流
@SentinelResource 对应 配置类的resource,代码如下:
public String qpsException(BlockException e) {
e.printStackTrace();
return "当前访问人数过多,稍后重试!";
}
@GetMapping("testAnnotation")
@SentinelResource(value = "userQps", blockHandler = "qpsException")
public String testAnnotation() throws InterruptedException {
Thread.sleep(1000);
return "terry";
}
被限流后:
通过代码整合限流
public String qpsException(BlockException e) {
e.printStackTrace();
return "当前访问人数过多,稍后重试!";
}
@RequestMapping("/testCode")
public String orderToMember() {
Entry entry = null;
try {
entry = SphU.entry("userQps");
return "terry";
} catch (BlockException e) {
// 限流的情况就会进入到Exception
return qpsException(e);
} finally {
// 避免调用链记录异常
if (entry != null) {
entry.exit();
}
}
}
测试:
被限流后: