赞
踩
最近用到SpringBoot熔断机制,详细的demo如下,本人也是第一次写,具体原理性的东西也不是太懂,这里就简单的介绍一下它的使用方法以及注意事项,希望各位能一次性测试成功。
demo代码如下
- package com.example.demo;
-
- import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
- import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
- import org.springframework.web.bind.annotation.GetMapping;
- import org.springframework.web.bind.annotation.RequestParam;
- import org.springframework.web.bind.annotation.RestController;
-
- /**
- * Created by Lenovo on 2019/5/16.
- */
- // @RestController注解相当于@ResponseBody + @Controller合在一起的作用。
- @RestController
- public class HysController {
-
- /* @HystrixCommand(fallbackMethod="helloFallbackMethod",commandProperties =
- {@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds" , value = "10000")})*/
- @HystrixCommand(fallbackMethod="helloFallbackMethod")
- @GetMapping("/tt")
- public String tt(@RequestParam(name = "num") int num) throws InterruptedException {
- Thread.sleep(5000);
- int a = 15 / num;
- return "ok";
- }
-
- private String helloFallbackMethod(@RequestParam(name = "num") int num){
- return "fall back";
- }
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
首先在启动类添加注解@EnableHystrix表示加入熔断机制
在Controller层的具体的方法路由上添加@HystrixCommand(fallbackMethod="helloFallbackMethod")表示该方法在出错或者是超时时会跳转到helloFallbackMethod。例如在代码中如果num=0,这时就会抛异常,熔断就会跳转到helloFallbackMethod;springboot的默认的超时时间是1000ms,代码中sleep(5000)也会导致熔断并跳转到helloFallbackMethod;默认多少时间算超时可以通过在application.yml文件中进行配置,如下hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=3000;这里添加到application.yml中就可以了,表示3000ms超时。
然后实现helloFallbackMethod方法,这里helloFallbackMethod的参数必须与路由方法的参数一致,
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。