开发者社区 > 云原生 > 正文

使用FlowRule线程电流限制模式时,SphU和SphO之间的差异

@Test public void boolThread() throws InterruptedException { // 配置规则. initFlowRules(); while (true) { if (SphO.entry("HelloWorld")) { System.out.println("hello world"); } else { System.out.println("blocked!"); } Thread.sleep(10); } }

@Test public void exThread() throws InterruptedException { // 配置规则. initFlowRules();

while (true) {
	Entry entry = null;
	try {
		entry = SphU.entry("HelloWorld");
		// 资源中的逻辑.
		System.out.println("hello world");
	} catch (BlockException e1) {
		System.out.println("blocked!");
	} finally {
		if (entry != null) {
			entry.exit();
		}
	}
	Thread.sleep(10);
}

}

/** * 线程数与QPS控制 */ private static void initFlowRules() { FlowRule rule = new FlowRule(); rule.setResource("HelloWorld"); rule.setGrade(RuleConstant.FLOW_GRADE_THREAD); rule.setCount(5);// 限制QPS rules.add(rule); FlowRuleManager.loadRules(rules); }

当执行 boolThread() 的时候,打印5个"hello world"后,就无限 blocked 了,而exThread()方法是表现正常的(其实就一个线程在跑),对比代码发现唯一区别就是 SphO.entry 里面,不会执行 entry.exit(),导致执行完毕后线程数不会减一,请问这是一个BUG吗?还是说规则上,线程流控不允许使用SphO这个类? 在文档上没发现说明,有劳多多指教,多谢了。

原提问者GitHub用户WindyDovs

展开
收起
码字王 2023-05-19 18:59:49 119 0
1 条回答
写回答
取消 提交回答
  • 你使用SphO的方式是不正确的。SphO也需要退出。例子:

    if (SphO.entry(resourceName)) { try { // Your code logic here. } finally { SphO.exit(); } } else { // Resource is rejected. // Your logic to handle blocking here. } }

    代码中使用 SphO 的方式错误,SphO 同样需要 exit,示例:

    // 资源名可使用任意有业务语义的字符串 if (SphO.entry("自定义资源名")) { // 务必保证finally会被执行 try { /** * 被保护的业务逻辑 */ } finally { // 务必保证 exit SphO.exit(); } } else { // 资源访问阻止,被限流或被降级 // 进行相应的处理操作 }

    参考:使用文档(How to use)

    https://github.com/alibaba/Sentinel/wiki/%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8#%E5%AE%9A%E4%B9%89%E8%B5%84%E6%BA%90

    原回答者GitHub用户sczyh30

    2023-05-19 21:28:06
    赞同 展开评论 打赏
问答标签:
问答地址:

阿里云拥有国内全面的云原生产品技术以及大规模的云原生应用实践,通过全面容器化、核心技术互联网化、应用 Serverless 化三大范式,助力制造业企业高效上云,实现系统稳定、应用敏捷智能。拥抱云原生,让创新无处不在。

相关电子书

更多
多IO线程优化版 立即下载
低代码开发师(初级)实战教程 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载