其他分享
首页 > 其他分享> > sentinel篇1-官方快速限流指引

sentinel篇1-官方快速限流指引

作者:互联网

前言

快速开始

目标代码块快速限流

<dependency>
	<groupId>com.alibaba.csp</groupId>
	<artifactId>sentinel-core</artifactId>
	<version>${sentinel.version}</version>
</dependency>
public class Demo0 {
	public static void main(String[] args) {
		// 配置规则.
		initFlowRules();

		while (true) {
			// 1.5.0 版本开始可以直接利用 try-with-resources 特性
			try (Entry entry = SphU.entry("HelloWorld")) {
				// 被保护的逻辑
				protectedCodes();
			} catch (BlockException ex) {
				// 处理被流控的逻辑
				System.err.println(DateUtil.formatDateTime(new Date()) + " blocked!");
			}
			
			try {
				Thread.sleep(RandomUtil.randomLong(300L));
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	private static void protectedCodes() {
		System.out.println(DateUtil.formatDateTime(new Date()) + " hello world");
	}

	private static void initFlowRules() {
		List<FlowRule> rules = new ArrayList<>();
		FlowRule rule = new FlowRule();
		rule.setResource("HelloWorld");
		rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
		// Set limit QPS to 20.
		rule.setCount(3);
		rules.add(rule);
		FlowRuleManager.loadRules(rules);
	}
}
2021-11-11 15:12:38 hello world
2021-11-11 15:12:38 hello world
2021-11-11 15:12:39 hello world
2021-11-11 15:12:39 hello world
2021-11-11 15:12:39 blocked!
2021-11-11 15:12:39 hello world
2021-11-11 15:12:39 blocked!
2021-11-11 15:12:39 blocked!
2021-11-11 15:12:39 blocked!
2021-11-11 15:12:40 hello world
2021-11-11 15:12:40 hello world
2021-11-11 15:12:40 blocked!
2021-11-11 15:12:40 hello world
2021-11-11 15:12:40 blocked!
2021-11-11 15:12:40 blocked!
2021-11-11 15:12:40 blocked!
2021-11-11 15:12:41 hello world
2021-11-11 15:12:41 hello world
2021-11-11 15:12:41 hello world
2021-11-11 15:12:41 blocked!
2021-11-11 15:12:42 hello world
2021-11-11 15:12:42 hello world
2021-11-11 15:12:42 blocked!
2021-11-11 15:12:42 hello world
2021-11-11 15:12:42 blocked!
2021-11-11 15:12:42 blocked!
2021-11-11 15:12:42 blocked!
2021-11-11 15:12:42 blocked!
2021-11-11 15:12:43 hello world

sentinel-dashboard

sentinel“资源”注册到控制台

有效参考

标签:11,指引,12,15,限流,2021,sentinel,world,hello
来源: https://www.cnblogs.com/noodlerkun/p/15541109.html