sentinel整合spirngcloud
导入依赖
<!--sentinel-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
<version>0.9.0.RELEASE</version>
</dependency>
下载github服务端
并启动sentinel-dashboard-1.7.1.jar
yml配置
#---------------------sentinel
sentinel:
transport:
dashboard: localhost:8080
heartbeat-interval-ms: 500
要进行服务熔断的方法上添加注解SentinelResource 并且配置触发sentinel的规则及补偿机制
/**
* 测试多数据源及seata事务的方法
* SentinelResource @Param blockHandler 执行触发规则的方法名 value是要执行规则池中的规则名
*/
@SentinelResource(value = "/rule1",blockHandler = "sentinelBlockHandler")
@RequestMapping("/get")
@GlobalTransactional//seata全局事务注解
public void get(){
userservice.selectBYMaster();
userservice.selectBySlave();
}
可以对其配置规则也可以服务端配置
package com.example.seatea.sentinel;
import com.alibaba.csp.sentinel.annotation.aspectj.SentinelResourceAspect;
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.Bean;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
@Configuration
public class SentinelConfig {
//注入sentinel拦截resource注解的单例
@Bean
public SentinelResourceAspect sentinelResourceAspect() {
return new SentinelResourceAspect();
}
@PostConstruct//启动容器后执行一次
private void initRules() {
//=============================规则1=========================
FlowRule rule1 = new FlowRule();
rule1.setResource("rule1");//规则名称
rule1.setGrade(RuleConstant.FLOW_GRADE_QPS);//如果设置0则按照线程数限流,如果设置1则按照QPS(每秒查询率)限流
rule1.setCount(10); // 每秒调用最大次数为 10 次
rule1.setControlBehavior(2);//0快速失败,1预警,2排队等候
rule1.setMaxQueueingTimeMs(1000);//排队超时阈值
//还有其他规则可在官网查看
//=============================规则2=========================
FlowRule rule2 = new FlowRule();
rule2.setResource("rule2");
rule2.setGrade(RuleConstant.FLOW_GRADE_QPS);
rule2.setCount(10); // 每秒调用最大次数为 10 次
List<FlowRule> rules = new ArrayList<>();
rules.add(rule1);
rules.add(rule2);
// 将控制规则载入到 Sentinel
FlowRuleManager.loadRules(rules);
}
}