1.使用sentinal 对资源(一个java方法或者http接口)进行限流,下面代码每一秒2个请求,但是经过sentinal的qps限流设置1,所以一半请求进来,一半被拦截了。
public class Test1 {
public static void main(String[] args) throws InterruptedException {
// 限流 规则
List<FlowRule> rules = new ArrayList<FlowRule>();
FlowRule rule = new FlowRule();
// 设置 资源名称
rule.setResource("http://localhost:8080/Test1");
// 设置限流规则为QPS
rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
// QPS限制, 每秒不能超过一个请求
rule.setCount(1);
// 指定应用名称
// rule.setLimitApp("test1");
rules.add(rule);
// 导入限流规则
FlowRuleManager.loadRules(rules);
while (true) {
Entry entry = null;
try {
// 检查 资源是否 被sentinel触发保护机制了,会抛出异常
entry = SphU.entry("http://localhost:8080/Test1");
System.err.println("正常运行接口>>" + new SimpleDateFormat("hh:mm:ss").format(new Date()));
} catch (BlockException e) {
System.err.println("被限流了==========================");
} finally {
if (entry != null) {
// 退出限流
entry.exit();
}
}
Thread.sleep(500);
}
}
}
maven
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-core</artifactId>
<version>1.4.1</version>
</dependency>
2.整合dubbo,对dubbo接口进行限流
maven配置
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-alibaba-sentinel</artifactId>
<version>0.9.0.RELEASE</version>
</dependency>
<!-- dubbo整合适配器 -->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-apache-dubbo-adapter</artifactId>
<version>1.6.3</version>
</dependency>
<dependency>
<!-- 后台管理控制交互 -->
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-transport-simple-http</artifactId>
<version>1.6.3</version>
</dependency>
在dubbo接口上加一个注解
启动dubbo服务时加上jvm参数(指定dashboard控制台地址)
Dcsp.sentinel.dashboard.server=localhost:8080