当前位置: 首页 > news >正文

02-限流熔断详解

限流熔断详解

一、知识概述

限流和熔断是系统自我保护的两大核心机制。限流防止系统过载,熔断防止级联故障。两者结合,构建系统的"免疫系统"。

核心目标:

  • 保护系统不被压垮
  • 防止故障扩散
  • 保证核心服务可用
  • 提供友好的降级体验

适用场景:

  • 流量突增(营销活动、热点事件)
  • 下游服务故障
  • 资源耗尽(CPU、内存、连接池)
  • 第三方服务不可用

二、知识点详细讲解

2.1 限流算法

2.1.1 固定窗口算法
原理:在固定时间窗口内限制请求数量 ┌─────────────────────────────────────┐ │ 时间窗口(1秒) │ │ │ │ ▓▓▓▓▓▓▓▓▓▓░░░░░░░░░░ │ │ 10个请求(限制) │ │ │ │ T0 ──────────────── T1 │ └─────────────────────────────────────┘ 优点:实现简单,内存占用小 缺点:边界问题(窗口边界可能突发2倍流量)
/** * 固定窗口限流器 */publicclassFixedWindowRateLimiter{privatefinalintlimit;// 限制数量privatefinallongwindowSize;// 窗口大小(ms)privatefinalAtomicIntegercounter=newAtomicInteger(0);privatefinalAtomicLongwindowStart=newAtomicLong(System.currentTimeMillis());publicFixedWindowRateLimiter(intlimit,longwindowSizeMs){this.limit=limit;this.windowSize=windowSizeMs;}publicbooleantryAcquire(){longnow=System.currentTimeMillis();longcurrentWindowStart=windowStart.get();// 检查是否需要重置窗口if(now-currentWindowStart>=windowSize){// CAS更新窗口起始时间if(windowStart.compareAndSet(currentWindowStart,now)){counter.set(0);}}// 计数器增加returncounter.incrementAndGet()<=limit;}}
2.1.2 滑动窗口算法
原理:将窗口划分为多个小格,滑动计算 ┌─────────────────────────────────────┐ │ 滑动窗口(1秒 = 10格,每格100ms) │ │ │ │ ┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐ │ │ 1 │ 2 │ 1 │ 3 │ 2 │ 1 │ 0 │ 0 │ 0 │ 0 │ │ └───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘ │ ↑ 当前位置 │ │ │ │ 总计: 1+2+1+3+2+1 = 10 (限制) │ └─────────────────────────────────────┘ 优点:解决了固定窗口的边界问题 缺点:内存占用较大
/** * 滑动窗口限流器 */publicclassSlidingWindowRateLimiter{privatefinalintlimit;// 总限制privatefinalintwindowSize;// 窗口大小(ms)privatefinalintsubWindowCount;// 子窗口数量privatefinalint[]counters;// 每个子窗口的计数privatefinallongsubWindowSize;// 子窗口大小privatelonglastTime;publicSlidingWindowRateLimiter(intlimit,intwindowSize,intsubWindowCount){this.limit=limit;this.windowSize=windowSize;this.subWindowCount=subWindowCount;this.subWindowSize=windowSize/subWindowCount;this.counters=newint[subWindowCount];this.lastTime=System.currentTimeMillis();}publicsynchronizedbooleantryAcquire(){longnow=System.currentTimeMillis();// 计算当前子窗口索引intcurrentIndex=(int)((now/subWindowSize)%subWindowCount);// 重置过期的子窗口longelapsed=now-lastTime;if(elapsed>0){intexpiredCount=(int)Math.min(elapsed/subWindowSize,subWindowCount);for(inti=0;i<expiredCount;i++){intindex=(currentIndex-i+subWindowCount)%subWindowCount;counters[index]=0;}lastTime=now;}// 计算当前总请求数inttotalCount=0;for(intcount:counters){totalCount+=count;}// 判断是否允许if(totalCount<limit){counters[currentIndex]++;returntrue;}returnfalse;}}
2.1.3 令牌桶算法
原理:以固定速率生成令牌,请求消耗令牌 ┌─────────────────────────────────────┐ │ 令牌桶 │ │ │ │ ┌─────────────────────┐ │ │ │ ▣ ▣ ▣ ▣ ▣ ▣ ▣ ▣ ░ ░ │ │ │ │ 桶中令牌(容量100) │ │ │ └─────────────────────┘ │ │ ↑ │ │ 固定速率补充 │ │ (如100个/秒) │ │ │ │ 请求 → 取令牌 → 有则通过 │ │ → 无则拒绝 │ └─────────────────────────────────────┘ 优点:允许一定程度的突发流量 适用:需要应对突发流量的场景
/** * 令牌桶限流器 */publicclassTokenBucketRateLimiter{privatefinallongcapacity;// 桶容量privatefinallongrate;// 令牌生成速率(个/秒)privatefinalAtomicLongtokens=newAtomicLong(0);privatefinalAtomicLonglastRefillTime=newAtomicLong(System.currentTimeMillis());publicTokenBucketRateLimiter(longcapacity,longrate){this.capacity=capacity;this.rate=rate;this.tokens.set(capacity);// 初始满桶}publicbooleantryAcquire(){returntryAcquire(1);}publicbooleantryAcquire(longpermits){// 补充令牌refillTokens();// 尝试获取令牌while(true){longcurrent=tokens.get();longtarget=current-permits;if(target<0){returnfalse;// 令牌不足}if(tokens.compareAndSet(current,target)){returntrue;}}}/** * 补充令牌 */privatevoidrefillTokens(){longnow=System.currentTimeMillis();longlastTime=lastRefillTime.get();if(now>lastTime){// 计算应该补充的令牌数longelapsed=now
http://www.jsqmd.com/news/642090/

相关文章:

  • 14款主流富文本编辑器深度评测:从功能到实战应用
  • 【异常】使用git clone 时提示git@github.com: Permission denied (publickey). fatal: Could not read from remote
  • 大模型推理优化:降低推理成本90%的核心技巧
  • 光刻胶选购指南:如何根据线宽需求选择I-line/DUV/EUV(附参数对比表)
  • 2026年近期宿迁AI销售服务商综合评测与选购指南 - 2026年企业推荐榜
  • AIAgent稳定性失效全景图(SITS2026核心洞察+27家头部企业故障归因数据)
  • SQL统计各分组中排名前三的记录_使用窗口函数RANK
  • Opencascade避坑指南:模型选取常见问题及解决方案
  • 2026年4月云南市场深度观察:天威太阳能热水器厂家何以成为区域优选? - 2026年企业推荐榜
  • 超实用!Informer-LSTM时序预测+SHAP可解释性分析,手把手教你打造高精度模型
  • NDK开发实战:从C/C++到高性能Android应用的关键技术解析
  • 保姆级教程:在QGC地面站源码中为自定义QML组件创建qmldir模块(附完整配置流程)
  • 从黑胶到流媒体:数字音频的“采样”与“量化”是如何一步步吃掉声音细节的?
  • Arduino实战:从DHT11到DHT22,精准环境监测传感器选型与应用全解析
  • 别再死记硬背了!用Arduino和S8050三极管,5分钟搞定一个会响的智能蜂鸣器
  • 【搜索技术代际跃迁预警】:2024 Q3起,未接入多模态语义对齐能力的搜索引擎将面临CTR断崖式下滑
  • 二维码识别器 - MKT
  • SwiftUI实战:5分钟搞定MacOS无边框窗口的3种实现方式(附完整代码)
  • 避坑指南:PX4与APM仿真连接QGC时,那些没人告诉你的UDP网络细节
  • AI语音克隆与合成:商用级方案搭建与版权风险规避
  • 创建Controller HTTP测试脚本
  • 多模态对话系统落地实战手册(含医疗/金融/政务三大高合规场景SOP),大会唯一授权中文版限量发放中
  • C#实战:二维码与条形码生成技术全解析
  • 信息学奥赛训练指南:如何用for循环优化累加问题(从OJ例题到竞赛技巧)
  • 2026年4月昆明AI关键词优化服务商综合评估与报价指南 - 2026年企业推荐榜
  • Topit:你的数字工作台智能管家,让窗口管理从此优雅高效
  • 开源大模型二次开发:Llama 3/通义千问/混元适配全教程
  • CANoe信号发生器深度玩法:结合User Defined与Log回放,搭建自动化测试闭环
  • 2026年第二季度江苏钢板网护栏采购指南:优质厂家深度解析与推荐 - 2026年企业推荐榜
  • 多模态大模型“小而强”训练秘钥(内部技术白皮书节选):冻结率>67%、模态采样熵<1.2、跨模态KL阈值=0.043——这些数字决定成败