流控组件Sentinel核心注解@SentinelResource中的参数fallback和blockHandler的使用方式
生活随笔
收集整理的這篇文章主要介紹了
流控组件Sentinel核心注解@SentinelResource中的参数fallback和blockHandler的使用方式
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
fallback顧名思義當(dāng)Java程序運(yùn)行發(fā)生錯(cuò)誤時(shí),由該參數(shù)定義的方法進(jìn)行處理
@GetMapping(value = "/consumer/{id}")@SentinelResource(value = "consumer", fallback = "handlerFallback")public ResponseEntity<String> consumerData(@PathVariable("id")Integer id) {ResponseEntity<String> entity = remoteService.getData(id);if (id <= 0) {throw new IllegalArgumentException("非法參數(shù)異常!");} else if (entity.getData() == null) {throw new NullPointerException("無響應(yīng)數(shù)據(jù),空指針異常!");}return entity;}public ResponseEntity<String> handlerFallback(Integer id, Throwable e) {return new ResponseEntity<>(443, "程序處理異常,開始執(zhí)行fallback數(shù)據(jù)-->" +e.getMessage());}blockHandler這個(gè)也很好明白,也就是當(dāng)API違背控制臺(tái)設(shè)置的閾值時(shí),執(zhí)行該參數(shù)定義的方法進(jìn)行處理;說白了就是限流之后的處理
@GetMapping(value = "/consumer/{id}")@SentinelResource(value = "consumer",blockHandler = "blockHandler")public ResponseEntity<String> consumerData(@PathVariable("id")Integer id) {ResponseEntity<String> entity = remoteService.getData(id);if (id <= 0) {throw new IllegalArgumentException("非法參數(shù)異常!");} else if (entity.getData() == null) {throw new NullPointerException("無響應(yīng)數(shù)據(jù),空指針異常!");}return entity;}public ResponseEntity<String> blockHandler(BlockException blockException) {return new ResponseEntity<>(444, "QPS過高,服務(wù)開始熔斷降級(jí)--->"+blockException.getMessage());}那么問題來了,如果同時(shí)發(fā)生Java運(yùn)行錯(cuò)誤和限流,那么會(huì)走哪個(gè)默認(rèn)的方法呢?
@GetMapping(value = "/consumer/{id}")@SentinelResource(value = "consumer", fallback = "handlerFallback", blockHandler = "blockHandler")public ResponseEntity<String> consumerData(@PathVariable("id")Integer id) {ResponseEntity<String> entity = remoteService.getData(id);if (id <= 0) {throw new IllegalArgumentException("非法參數(shù)異常!");} else if (entity.getData() == null) {throw new NullPointerException("無響應(yīng)數(shù)據(jù),空指針異常!");}return entity;}public ResponseEntity<String> handlerFallback(Integer id, Throwable e) {return new ResponseEntity<>(443, "程序處理異常,開始執(zhí)行fallback數(shù)據(jù)-->" +e.getMessage());}public ResponseEntity<String> blockHandler(Integer id, BlockException blockException) {return new ResponseEntity<>(444, "QPS過高,服務(wù)開始熔斷降級(jí)--->"+blockException.getMessage());}設(shè)置限流規(guī)則
當(dāng)我持續(xù)刷新,它走的是blockHandler路線
記得在配置文件加入以下
總結(jié)
以上是生活随笔為你收集整理的流控组件Sentinel核心注解@SentinelResource中的参数fallback和blockHandler的使用方式的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 手把手带你领略双十一背后的核心技术Sen
- 下一篇: Sentinel+Nacos实现Sent