@HystrixCommand 注解的作用与注意事项
生活随笔
收集整理的這篇文章主要介紹了
@HystrixCommand 注解的作用与注意事项
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、說明
@HystrixCommand 注解 能對某個一個接口定制 Hystrix的超時時間。
通過修改?execution.isolation.thread.timeoutInMilliseconds 屬性可以設置超時時間,
通過設置 fallbackMethod 可以設置超時后響應的格式
?
二、示例
?
@HystrixCommand(fallbackMethod = "sleepFallback", commandProperties ={@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "900")}) @PostMapping("/sleep") public ResultBean test(@RequestParam(value = "sleep") Integer sleep) throws InterruptedException {log.info("開始睡眠" + sleep + "毫秒");Thread.sleep(sleep);log.info("睡眠結束...");return ResultBean.result("請求結束!"); }private ResultBean sleepFallback(Integer sleep) {return ResultBean.result(Code.REQUEST_TIME_OUT.getCode(), "請求超時,請稍后重試。"); }三、注意事項
① 設置?fallbackMethod 指定的 返回值方法類型要跟目標方法一致,否則將報錯。
② 如果方法內部有明顯的異常,將不走目標方法,直接返回 fallback 方法的返回值。
@HystrixCommand(fallbackMethod = "sleepFallback", commandProperties ={@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")}) @PostMapping("/sleep2") public ResultBean test02(@RequestParam(value = "sleep") Integer sleep) throws InterruptedException {log.info("開始睡眠" + sleep + "毫秒");String s = null;s.trim();//編譯通過,但明顯空指針異常int i = 1 / 0;編譯通過,但明顯算術異常Thread.sleep(sleep);log.info("睡眠結束...");return ResultBean.result("請求結束!"); }③ 如果@HystrixCommand 注解同時指定了目標方法的 timeoutInMilliseconds,同時又在配置文件 application.yml 中配置了hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds ,甚至設置了Ribbon.ReadTimeout??
那么,超時時間最小的將生效。
總結
以上是生活随笔為你收集整理的@HystrixCommand 注解的作用与注意事项的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ZZULIOJ069:向z同学学习
- 下一篇: ZZULIOJ 1057:素数判定