Browse Source

Add sort for flow rules when loading rules

Signed-off-by: Eric Zhao <sczyh16@gmail.com>
master
Eric Zhao 6 years ago
parent
commit
a680b4c5e3
2 changed files with 56 additions and 0 deletions
  1. +11
    -0
      sentinel-core/src/main/java/com/alibaba/csp/sentinel/slots/block/flow/FlowRuleManager.java
  2. +45
    -0
      sentinel-core/src/test/java/com/alibaba/csp/sentinel/slots/block/flow/FlowRuleComparatorTest.java

+ 11
- 0
sentinel-core/src/main/java/com/alibaba/csp/sentinel/slots/block/flow/FlowRuleManager.java View File

@@ -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<FlowRule> comparator = new FlowRuleComparator();
// Sort the rules.
for (List<FlowRule> rules : newRuleMap.values()) {
Collections.sort(rules, comparator);
}
}

return newRuleMap;
}



+ 45
- 0
sentinel-core/src/test/java/com/alibaba/csp/sentinel/slots/block/flow/FlowRuleComparatorTest.java View File

@@ -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<FlowRule> list = Arrays.asList(ruleA, ruleB, ruleC, ruleD, ruleE);
FlowRuleComparator comparator = new FlowRuleComparator();
Collections.sort(list, comparator);
List<FlowRule> expected = Arrays.asList(ruleB, ruleC, ruleD, ruleA, ruleE);
assertOrderEqual(expected.size(), expected, list);
}

private void assertOrderEqual(int size, List<FlowRule> expected, List<FlowRule> actual) {
for (int i = 0; i < size; i++) {
assertEquals(expected.get(i), actual.get(i));
}
}
}

Loading…
Cancel
Save