电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁技術文章
文章詳情頁

淺析Spring Boot單體應用熔斷技術的使用

瀏覽:8日期:2023-07-25 17:37:24
壹、入圍方案Sentinel github地址:https://sentinelguard.io/zh-cn/docs/introduction.html 阿里出品,Spring Cloud Alibaba限流組件,目前持續更新中 自帶Dashboard,可以查看接口Qps等,并且可以動態修改各種規則 流量控制,直接限流、冷啟動、排隊 熔斷降級,限制并發限制數和相應時間 系統負載保護,提供系統級別防護,限制總體CPU等 主要核心:資源,規則(流量控制規則、熔斷降級規則、系統保護規則、來源訪問控制規則 和 熱點參數規則。),和指標 文檔非常清晰和詳細,中文 支持動態規則(推模式和拉模式) Hystrix github地址:https://github.com/Netflix/Hystrix/wiki Netflix出品,Spring Cloud Netflix限流組件,已經停止新特性開發,只進行bug修復,最近更新為2018年,功能穩定 有簡單的dashboard頁面 以隔離和熔斷為主的容錯機制,超時或被熔斷的調用將會快速失敗,并可以提供 fallback 機制的初代熔斷框架,異常統計基于滑動窗口 resilience4j github地址:https://resilience4j.readme.io/docs 是一款輕量、簡單,并且文檔非常清晰、豐富的熔斷工具。是Hystrix替代品,實現思路和Hystrix一致,目前持續更新中 需要自己對micrometer、prometheus以及Dropwizard metrics進行整合 CircuitBreaker 熔斷 Bulkhead 隔離 RateLimiter QPS限制 Retry 重試 TimeLimiter 超時限制 Cache 緩存 自己實現(基于Guava) 基于Guava的令牌桶,可以輕松實現對QPS進行限流 貳、技術對比

淺析Spring Boot單體應用熔斷技術的使用

叁、應用改造3.1、sentinel

3.1.1、引入依賴

<dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId> <version>2.0.3.RELEASE</version></dependency>

3.1.2、改造接口或者service層

@SentinelResource(value = 'allInfos',fallback = 'errorReturn')

@Target({ElementType.METHOD, ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Inheritedpublic @interface SentinelResource { //資源名稱 String value() default ''; //流量方向 EntryType entryType() default EntryType.OUT; //資源類型 int resourceType() default 0; //異常處理方法 String blockHandler() default ''; //異常處理類 Class<?>[] blockHandlerClass() default {}; //熔斷方法 String fallback() default ''; //默認熔斷方法 String defaultFallback() default ''; //熔斷類 Class<?>[] fallbackClass() default {}; //統計異常 Class<? extends Throwable>[] exceptionsToTrace() default {Throwable.class}; //忽略異常 Class<? extends Throwable>[] exceptionsToIgnore() default {};}

@RequestMapping('/get')@ResponseBody@SentinelResource(value = 'allInfos',fallback = 'errorReturn')public JsonResult allInfos(HttpServletRequest request, HttpServletResponse response, @RequestParam Integer num){ try { if (num % 2 == 0) {log.info('num % 2 == 0');throw new BaseException('something bad with 2', 400); } return JsonResult.ok(); } catch (ProgramException e) { log.info('error'); return JsonResult.error('error'); } }

3.1.3、針對接口配置熔斷方法或者限流方法

默認過濾攔截所有Controller接口

/** * 限流,參數需要和方法保持一致 * @param request * @param response * @param num * @return * @throws BlockException */ public JsonResult errorReturn(HttpServletRequest request, HttpServletResponse response, @RequestParam Integer num) throws BlockException { return JsonResult.error('error 限流' + num ); } /** * 熔斷,參數需要和方法保持一直,并且需要添加BlockException異常 * @param request * @param response * @param num * @param b * @return * @throws BlockException */ public JsonResult errorReturn(HttpServletRequest request, HttpServletResponse response, @RequestParam Integer num,BlockException b) throws BlockException { return JsonResult.error('error 熔斷' + num ); }

注意也可以不配置限流或者熔斷方法。通過全局異常去捕獲UndeclaredThrowableException或者BlockException避免大量的開發量

3.1.4、接入dashboard

spring: cloud: sentinel: transport: port: 8719 dashboard: localhost:8080

淺析Spring Boot單體應用熔斷技術的使用

3.1.5、規則持久化和動態更新

接入配置中心如:zookeeper等等,并對規則采用推模式

3.2、hystrix

3.2.1、引入依賴

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId></dependency><dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId> <version>2.0.4.RELEASE</version></dependency><dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> <version>2.0.4.RELEASE</version></dependency>

3.2.2、改造接口

@HystrixCommand(fallbackMethod = 'timeOutError')

@Target({ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)@Inherited@Documentedpublic @interface HystrixCommand { String groupKey() default ''; String commandKey() default ''; String threadPoolKey() default ''; String fallbackMethod() default ''; HystrixProperty[] commandProperties() default {}; HystrixProperty[] threadPoolProperties() default {}; Class<? extends Throwable>[] ignoreExceptions() default {}; ObservableExecutionMode observableExecutionMode() default ObservableExecutionMode.EAGER; HystrixException[] raiseHystrixExceptions() default {}; String defaultFallback() default '';}

@RequestMapping('/get')@ResponseBody@HystrixCommand(fallbackMethod = 'fallbackMethod')public JsonResult allInfos(HttpServletRequest request, HttpServletResponse response, @RequestParam Integer num){ try { if (num % 3 == 0) { log.info('num % 3 == 0'); throw new BaseException('something bad whitch 3', 400); } return JsonResult.ok(); } catch (ProgramException | InterruptedException exception) { log.info('error'); return JsonResult.error('error'); }}

3.2.3、針對接口配置熔斷方法

/** * 該方法是熔斷回調方法,參數需要和接口保持一致 * @param request * @param response * @param num * @return */public JsonResult fallbackMethod(HttpServletRequest request, HttpServletResponse response, @RequestParam Integer num) { response.setStatus(500); log.info('發生了熔斷!!'); return JsonResult.error('熔斷');}

3.2.4、配置默認策略

hystrix: command: default: execution: isolation: strategy: THREAD thread: # 線程超時15秒,調用Fallback方法 timeoutInMilliseconds: 15000 metrics: rollingStats: timeInMilliseconds: 15000 circuitBreaker: # 10秒內出現3個以上請求(已臨近閥值),并且出錯率在50%以上,開啟斷路器.斷開服務,調用Fallback方法 requestVolumeThreshold: 3 sleepWindowInMilliseconds: 10000

3.2.5、接入監控

淺析Spring Boot單體應用熔斷技術的使用

淺析Spring Boot單體應用熔斷技術的使用

曲線:用來記錄2分鐘內流量的相對變化,我們可以通過它來觀察到流量的上升和下降趨勢。

集群監控需要用到注冊中心

3.3、resilience4j

3.3.1、引入依賴

dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId></dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope></dependency> <dependency> <groupId>io.github.resilience4j</groupId> <artifactId>resilience4j-spring-boot2</artifactId> <version>1.6.1</version></dependency> <dependency> <groupId>io.github.resilience4j</groupId> <artifactId>resilience4j-bulkhead</artifactId> <version>1.6.1</version></dependency> <dependency> <groupId>io.github.resilience4j</groupId> <artifactId>resilience4j-ratelimiter</artifactId> <version>1.6.1</version></dependency> <dependency> <groupId>io.github.resilience4j</groupId> <artifactId>resilience4j-timelimiter</artifactId> <version>1.6.1</version></dependency>

可以按需要引入:bulkhead,ratelimiter,timelimiter等

3.3.2、改造接口

@RequestMapping('/get')@ResponseBody//@TimeLimiter(name = 'BulkheadA',fallbackMethod = 'fallbackMethod')@CircuitBreaker(name = 'BulkheadA',fallbackMethod = 'fallbackMethod')@Bulkhead(name = 'BulkheadA',fallbackMethod = 'fallbackMethod')public JsonResult allInfos(HttpServletRequest request, HttpServletResponse response, @RequestParam Integer num){ log.info('param----->' + num); try { //Thread.sleep(num); if (num % 2 == 0) { log.info('num % 2 == 0'); throw new BaseException('something bad with 2', 400); } if (num % 3 == 0) { log.info('num % 3 == 0'); throw new BaseException('something bad whitch 3', 400); } if (num % 5 == 0) { log.info('num % 5 == 0'); throw new ProgramException('something bad whitch 5', 400); } if (num % 7 == 0) { log.info('num % 7 == 0'); int res = 1 / 0; } return JsonResult.ok(); } catch (BufferUnderflowException e) { log.info('error'); return JsonResult.error('error'); }}

3.3.3、針對接口配置熔斷方法

/** * 需要參數一致,并且加上相應異常 * @param request * @param response * @param num * @param exception * @return */public JsonResult fallbackMethod(HttpServletRequest request, HttpServletResponse response, @RequestParam Integer num, BulkheadFullException exception) { return JsonResult.error('error 熔斷' + num );}

3.3.4、配置規則

resilience4j.circuitbreaker: instances: backendA: registerHealthIndicator: true slidingWindowSize: 100 backendB: registerHealthIndicator: true slidingWindowSize: 10 permittedNumberOfCallsInHalfOpenState: 3 slidingWindowType: TIME_BASED minimumNumberOfCalls: 20 waitDurationInOpenState: 50s failureRateThreshold: 50 eventConsumerBufferSize: 10 recordFailurePredicate: io.github.robwin.exception.RecordFailurePredicate resilience4j.retry: instances: backendA: maxRetryAttempts: 3 waitDuration: 10s enableExponentialBackoff: true exponentialBackoffMultiplier: 2 retryExceptions:- org.springframework.web.client.HttpServerErrorException- java.io.IOException ignoreExceptions:- io.github.robwin.exception.BusinessException backendB: maxRetryAttempts: 3 waitDuration: 10s retryExceptions:- org.springframework.web.client.HttpServerErrorException- java.io.IOException ignoreExceptions:- io.github.robwin.exception.BusinessException resilience4j.bulkhead: instances: backendA: maxConcurrentCalls: 10 backendB: maxWaitDuration: 10ms maxConcurrentCalls: 20 resilience4j.thread-pool-bulkhead: instances: backendC: maxThreadPoolSize: 1 coreThreadPoolSize: 1 queueCapacity: 1 resilience4j.ratelimiter: instances: backendA: limitForPeriod: 10 limitRefreshPeriod: 1s timeoutDuration: 0 registerHealthIndicator: true eventConsumerBufferSize: 100 backendB: limitForPeriod: 6 limitRefreshPeriod: 500ms timeoutDuration: 3s resilience4j.timelimiter: instances: backendA: timeoutDuration: 2s cancelRunningFuture: true backendB: timeoutDuration: 1s cancelRunningFuture: false

配置的規則可以被代碼覆蓋

3.3.5、配置監控

如grafana等

肆、關注點 是否需要過濾部分異常 是否需要全局默認規則 可能需要引入其他中間件 k8s流量控制 規則存儲和動態修改 接入改造代價 【后面的話】

個人建議的話,比較推薦sentinel,它提供了很多接口便于開發者自己拓展,同時我覺得他的規則動態更新也比較方便。最后是相關示例代碼:單體應用示例代碼

以上就是淺析Spring Boot單體應用熔斷技術的使用的詳細內容,更多關于Spring Boot單體應用熔斷技術的資料請關注好吧啦網其它相關文章!

標簽: Spring
相關文章:
主站蜘蛛池模板: 广州办公室设计,办公室装修,写字楼设计,办公室装修公司_德科 | 高低温老化试验机-步入式/低温恒温恒湿试验机-百科 | 精密冲床,高速冲床等冲压设备生产商-常州晋志德压力机厂 | TPU薄膜_TPU薄膜生产厂家_TPU热熔胶膜厂家定制_鑫亘环保科技(深圳)有限公司 | 有机肥设备生产制造厂家,BB掺混肥搅拌机、复合肥设备生产线,有机肥料全部加工设备多少钱,对辊挤压造粒机,有机肥造粒设备 -- 郑州程翔重工机械有限公司 | 礼仪庆典公司,礼仪策划公司,庆典公司,演出公司,演艺公司,年会酒会,生日寿宴,动工仪式,开工仪式,奠基典礼,商务会议,竣工落成,乔迁揭牌,签约启动-东莞市开门红文化传媒有限公司 | 检验科改造施工_DSA手术室净化_导管室装修_成都特殊科室建设厂家_医疗净化工程公司_四川华锐 | 合肥地磅_合肥数控切割机_安徽地磅厂家_合肥世佳电工设备有限公司 | 沟盖板_复合沟盖板厂_电力盖板_树脂雨水篦子-淄博拜斯特 | 合肥抖音SEO网站优化-网站建设-网络推广营销公司-百度爱采购-安徽企匠科技 | 精密线材测试仪-电线电缆检测仪-苏州欣硕电子科技有限公司 | 盘古网络技术有限公司| 四川成人高考_四川成考报名网| 同学聚会纪念册制作_毕业相册制作-成都顺时针宣传画册设计公司 | 英国雷迪地下管线探测仪-雷迪RD8100管线仪-多功能数字听漏仪-北京迪瑞进创科技有限公司 | 意大利Frascold/富士豪压缩机_富士豪半封闭压缩机_富士豪活塞压缩机_富士豪螺杆压缩机 | 小型手持气象站-空气负氧离子监测站-多要素微气象传感器-山东天合环境科技有限公司 | 杭州用友|用友软件|用友财务软件|用友ERP系统--杭州协友软件官网 | 拉力机-拉力试验机-万能试验机-电子拉力机-拉伸试验机-剥离强度试验机-苏州皖仪实验仪器有限公司 | 双齿辊破碎机-大型狼牙破碎机视频-对辊破碎机价格/型号图片-金联机械设备生产厂家 | 上海刑事律师|刑事辩护律师|专业刑事犯罪辩护律师免费咨询-[尤辰荣]金牌上海刑事律师团队 | loft装修,上海嘉定酒店式公寓装修公司—曼城装饰 | 对夹式止回阀_对夹式蝶形止回阀_对夹式软密封止回阀_超薄型止回阀_不锈钢底阀-温州上炬阀门科技有限公司 | 【德信自动化】点胶机_全自动点胶机_自动点胶机厂家_塑料热压机_自动螺丝机-深圳市德信自动化设备有限公司 | 南京种植牙医院【官方挂号】_南京治疗种植牙医院那个好_南京看种植牙哪里好_南京茀莱堡口腔医院 尼龙PA610树脂,尼龙PA612树脂,尼龙PA1010树脂,透明尼龙-谷骐科技【官网】 | 经济师考试_2025中级经济师报名时间_报名入口_考试时间_华课网校经济师培训网站 | 微型驱动系统解决方案-深圳市兆威机电股份有限公司 | 有源电力滤波装置-电力有源滤波器-低压穿排电流互感器|安科瑞 | 西安标准厂房_陕西工业厂房_西咸新区独栋厂房_长信科技产业园官方网站 | 企业微信scrm管理系统_客户关系管理平台_私域流量运营工具_CRM、ERP、OA软件-腾辉网络 | 无菌实验室规划装修设计-一体化实验室承包-北京洁净净化工程建设施工-北京航天科恩实验室装备工程技术有限公司 | 合景一建-无尘车间设计施工_食品医药洁净车间工程装修总承包公司 | 防潮防水通风密闭门源头实力厂家 - 北京酷思帝克门窗 | 不发火防静电金属骨料_无机磨石_水泥自流平_修补砂浆厂家「圣威特」 | 急救箱-应急箱-急救包厂家-北京红立方医疗设备有限公司 | 东莞螺杆空压机_永磁变频空压机_节能空压机_空压机工厂批发_深圳螺杆空压机_广州螺杆空压机_东莞空压机_空压机批发_东莞空压机工厂批发_东莞市文颖设备科技有限公司 | 机房监控|动环监控|动力环境监控系统方案产品定制厂家 - 迈世OMARA | 吲哚菁绿衍生物-酶底物法大肠菌群检测试剂-北京和信同通科技发展有限公司 | 空气能暖气片,暖气片厂家,山东暖气片,临沂暖气片-临沂永超暖通设备有限公司 | 济南冷库安装-山东冷库设计|建造|冷库维修-山东齐雪制冷设备有限公司 | 橡胶弹簧|复合弹簧|橡胶球|振动筛配件-新乡市永鑫橡胶厂 |