概述
一些简单的限流场景下,无需使用dashboard进行限流资源配置,我们在代码中直接设置限流资源即可。
环境搭建
代码动态指定限流资源
示例
// 动态指定限流资源
private static void doSomething(String resource) {
try (Entry entry = SphU.entry(resource)) {
// 业务逻辑处理
System.out.println(resource + " " + System.currentTimeMillis());
} catch (BlockException e) {
// 处理流控的逻辑
System.out.println(resource + " block exception, trigger traffic limit");
}
}
// 重新加载限流规则
private static void reloadFlowRules(String resource) {
FlowRule rule = new FlowRule();
rule.setResource(resource);
rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
rule.setCount(1);
List<FlowRule> rules = FlowRuleManager.getRules();
rules.add(rule);
FlowRuleManager.loadRules(rules);
}
// 测试动态指定限流资源限流
public static void main(String[] args) {
ArrayList<String> resources = new ArrayList<>();
resources.add("https://192.168.121.18:8080/test/1");
resources.add("https://192.168.121.18:8080/test/2");
resources.add("https://192.168.121.18:8080/test/3");
resources.add("https://192.168.121.18:8080/test/4");
resources.add("https://192.168.11.18:8080/test/5");
resources.add("https://192.168.131.18:8080/test/6");
HashSet<String> strings = new HashSet<>();
for (int i = 0; i < 3; i++) {
resources.forEach(resourceName -> {
if (!strings.contains(resourceName)) {
strings.add(resourceName);
reloadFlowRules(resourceName );
}
doSomething(resourceName);
});
}
}
测试结果
测试结果与预期相符,动态的指定需要限流的资源的QPS为1,结果第二次的时候全部调用失败,触发效率逻辑。
https://192.168.121.18:8080/test/1 1660646351659
https://192.168.121.18:8080/test/2 1660646351660
https://192.168.121.18:8080/test/3 1660646351661
https://192.168.121.18:8080/test/4 1660646351662
https://192.168.11.18:8080/test/5 1660646351663
https://192.168.131.18:8080/test/6 1660646351664
https://192.168.121.18:8080/test/1 block exception, trigger traffic limit
https://192.168.121.18:8080/test/2 block exception, trigger traffic limit
https://192.168.121.18:8080/test/3 block exception, trigger traffic limit
https://192.168.121.18:8080/test/4 block exception, trigger traffic limit
https://192.168.11.18:8080/test/5 block exception, trigger traffic limit
https://192.168.131.18:8080/test/6 block exception, trigger traffic limit
https://192.168.121.18:8080/test/1 block exception, trigger traffic limit
https://192.168.121.18:8080/test/2 block exception, trigger traffic limit
https://192.168.121.18:8080/test/3 block exception, trigger traffic limit
https://192.168.121.18:8080/test/4 block exception, trigger traffic limit
https://192.168.11.18:8080/test/5 block exception, trigger traffic limit
https://192.168.131.18:8080/test/6 block exception, trigger traffic limit
参考
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/100032.html