熱點即經常訪問的數據。很多時候我們希望統計某個熱點數據中訪問頻次最高的 Top K 數據,並對其訪問進行限制。比如:
- 商品 ID 為參數,統計一段時間內最常購買的商品 ID 並進行限制
- 用戶 ID 為參數,針對一段時間內頻繁訪問的用戶 ID 進行限制
熱點參數限流會統計傳入參數中的熱點參數,並根據配置的限流閾值與模式,對包含熱點參數的資源調用進行限流。熱點參數限流可以看做是一種特殊的流量控制,僅對包含熱點參數的資源調用生效。
使用方法
Entry entry = null; try { entry = SphU.entry(resourceName, EntryType.IN, 1, paramA, paramB); // Your logic here. } catch (BlockException ex) { // Handle request rejection. } finally { if (entry != null) { entry.exit(1, paramA, paramB); } }
熱點參數規則(ParamFlowRule
)類似於流量控制規則(FlowRule
):
屬性 | 說明 | 默認值 |
---|---|---|
resource | 資源名,必填 | |
count | 限流閾值,必填 | |
grade | 限流模式 | QPS 模式 |
durationInSec | 統計窗口時間長度(單位為秒),1.6.0 版本開始支持 | 1s |
controlBehavior | 流控效果(支持快速失敗和勻速排隊模式),1.6.0 版本開始支持 | 快速失敗 |
maxQueueingTimeMs | 最大排隊等待時長(僅在勻速排隊模式生效),1.6.0 版本開始支持 | 0ms |
paramIdx | 熱點參數的索引,必填,對應 SphU.entry(xxx, args) 中的參數索引位置 |
|
paramFlowItemList | 參數例外項,可以針對指定的參數值單獨設置限流閾值,不受前面 count 閾值的限制。僅支持基本類型和字符串類型 |
|
clusterMode | 是否是集群參數流控規則 | false |
clusterConfig | 集群流控相關配置 |
我們可以通過 ParamFlowRuleManager
的 loadRules
方法更新熱點參數規則,下面是一個示例:
ParamFlowRule rule = new ParamFlowRule(resourceName) .setParamIdx(0) .setCount(5); // 針對 int 類型的參數 PARAM_B,單獨設置限流 QPS 閾值為 10,而不是全局的閾值 5. ParamFlowItem item = new ParamFlowItem().setObject(String.valueOf(PARAM_B)) .setClassType(int.class.getName()) .setCount(10); rule.setParamFlowItemList(Collections.singletonList(item)); ParamFlowRuleManager.loadRules(Collections.singletonList(rule));
示例

public class ParamFlowQpsDemo { private static final int PARAM_A = 1; private static final int PARAM_B = 2; private static final int PARAM_C = 3; private static final int PARAM_D = 4; /** * Here we prepare different parameters to validate flow control by parameters. */ private static final Integer[] PARAMS = new Integer[] {PARAM_A, PARAM_B, PARAM_C, PARAM_D}; private static final String RESOURCE_KEY = "resA"; public static void main(String[] args) throws Exception { initParamFlowRules(); final int threadCount = 20; ParamFlowQpsRunner<Integer> runner = new ParamFlowQpsRunner<>(PARAMS, RESOURCE_KEY, threadCount, 120); runner.tick(); Thread.sleep(1000); runner.simulateTraffic(); } private static void initParamFlowRules() { // QPS mode, threshold is 5 for every frequent "hot spot" parameter in index 0 (the first arg). ParamFlowRule rule = new ParamFlowRule(RESOURCE_KEY) .setParamIdx(0) .setGrade(RuleConstant.FLOW_GRADE_QPS) //.setDurationInSec(3) //.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER) //.setMaxQueueingTimeMs(600) .setCount(5); // We can set threshold count for specific parameter value individually. // Here we add an exception item. That means: QPS threshold of entries with parameter `PARAM_B` (type: int) // in index 0 will be 10, rather than the global threshold (5). ParamFlowItem item = new ParamFlowItem().setObject(String.valueOf(PARAM_B)) .setClassType(int.class.getName()) .setCount(10); rule.setParamFlowItemList(Collections.singletonList(item)); ParamFlowRuleManager.loadRules(Collections.singletonList(rule)); } }