diff --git a/sentinel-core/src/main/java/com/alibaba/csp/sentinel/slots/block/flow/FlowRuleManager.java b/sentinel-core/src/main/java/com/alibaba/csp/sentinel/slots/block/flow/FlowRuleManager.java index 31997527..230b4679 100755 --- a/sentinel-core/src/main/java/com/alibaba/csp/sentinel/slots/block/flow/FlowRuleManager.java +++ b/sentinel-core/src/main/java/com/alibaba/csp/sentinel/slots/block/flow/FlowRuleManager.java @@ -16,6 +16,8 @@ package com.alibaba.csp.sentinel.slots.block.flow; import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -144,6 +146,15 @@ public class FlowRuleManager { ruleM.add(rule); } + + if (!newRuleMap.isEmpty()) { + Comparator comparator = new FlowRuleComparator(); + // Sort the rules. + for (List rules : newRuleMap.values()) { + Collections.sort(rules, comparator); + } + } + return newRuleMap; } diff --git a/sentinel-core/src/test/java/com/alibaba/csp/sentinel/slots/block/flow/FlowRuleComparatorTest.java b/sentinel-core/src/test/java/com/alibaba/csp/sentinel/slots/block/flow/FlowRuleComparatorTest.java new file mode 100644 index 00000000..808bf515 --- /dev/null +++ b/sentinel-core/src/test/java/com/alibaba/csp/sentinel/slots/block/flow/FlowRuleComparatorTest.java @@ -0,0 +1,45 @@ +package com.alibaba.csp.sentinel.slots.block.flow; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import com.alibaba.csp.sentinel.slots.block.RuleConstant; + +import org.junit.Test; + +import static org.junit.Assert.*; + +/** + * @author Eric Zhao + */ +public class FlowRuleComparatorTest { + + @Test + public void testFlowRuleComparator() { + FlowRule ruleA = new FlowRule("abc") + .setCount(10); + ruleA.setLimitApp(RuleConstant.LIMIT_APP_DEFAULT); + FlowRule ruleB = new FlowRule("abc"); + ruleB.setLimitApp("originA"); + FlowRule ruleC = new FlowRule("abc"); + ruleC.setLimitApp("originB"); + FlowRule ruleD = new FlowRule("abc"); + ruleD.setLimitApp(RuleConstant.LIMIT_APP_OTHER); + FlowRule ruleE = new FlowRule("abc") + .setCount(20); + ruleE.setLimitApp(RuleConstant.LIMIT_APP_DEFAULT); + + List list = Arrays.asList(ruleA, ruleB, ruleC, ruleD, ruleE); + FlowRuleComparator comparator = new FlowRuleComparator(); + Collections.sort(list, comparator); + List expected = Arrays.asList(ruleB, ruleC, ruleD, ruleA, ruleE); + assertOrderEqual(expected.size(), expected, list); + } + + private void assertOrderEqual(int size, List expected, List actual) { + for (int i = 0; i < size; i++) { + assertEquals(expected.get(i), actual.get(i)); + } + } +} \ No newline at end of file