sentinel学习
pom.xml中架上以下依赖
下面展示一些 依赖
。
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<!--sentinel限流使用-->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-zuul-adapter</artifactId>
<version>1.6.0</version>
</dependency>
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-annotation-aspectj</artifactId>
<version>1.6.0</version>
</dependency>
1、在zuul过滤器中使用限流
启动类配置限流规则
public static void main(String[] args) {
//初始化sentinel限流规则
init();
SpringApplication.run(ZuulClientApplication.class, args);
}
private static void init() {
log.info("开始初始化限流规则");
//所有限流规则的合集
List<FlowRule> flowRuleList = new ArrayList<FlowRule>();
FlowRule flowRule = new FlowRule();
//资源名称
flowRule.setResource("SentinelService.success");
//限流类型
flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
//qps
flowRule.setCount(1);
flowRuleList.add(flowRule);
FlowRuleManager.loadRules(flowRuleList);
}
过滤器中使用
@Override
public Object run() throws ZuulException {
log.info("开始执行过滤器了");
Entry entry = null;
try {
entry = SphU.entry("helloWorld");
log.info("正常执行");
} catch (BlockException e) {
log.info("阻塞了");
RequestContext.getCurrentContext().setSendZuulResponse(false);
RequestContext.getCurrentContext().setResponseStatusCode(500);
RequestContext.getCurrentContext().setResponseBody(ResponseResult.failJSON(CommonStatusEnum.INTERNAL_SERVER_EXCEPTION.getCode()
, CommonStatusEnum.INTERNAL_SERVER_EXCEPTION.getValue(), null));
return null;
} finally {
if (entry!=null){
entry.exit();
}
}
return null;
}
2、在方法上使用限流
启动类设置限流规则,并创建切面
public static void main(String[] args) {
//初始化sentinel限流规则
init();
SpringApplication.run(ZuulClientApplication.class, args);
}
private static void init() {
log.info("开始初始化限流规则");
//所有限流规则的合集
List<FlowRule> flowRuleList = new ArrayList<FlowRule>();
FlowRule flowRule = new FlowRule();
//资源名称
flowRule.setResource("SentinelService.success");
//限流类型
flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
//qps
flowRule.setCount(1);
flowRuleList.add(flowRule);
FlowRuleManager.loadRules(flowRuleList);
}
/**
* @Description: 需要配置切面,限流规则才会生效
* @Date: 2021-03-22 10:25
* @return: com.alibaba.csp.sentinel.annotation.aspectj.SentinelResourceAspect
**/
@Bean
public SentinelResourceAspect sentinelResourceAspect() {
return new SentinelResourceAspect();
}
方法上加入SentinelResource注解
@Service
@Slf4j
public class SentinelService {
@SentinelResource(value = "SentinelService.success",blockHandler = "fail")
public void success(){
log.info("访问成功");
}
public void fail(BlockException e){
log.info("访问失败,阻塞住了",e);
}
}