专注于 JetBrains IDEA 全家桶,永久激活,教程
持续更新 PyCharm,IDEA,WebStorm,PhpStorm,DataGrip,RubyMine,CLion,AppCode 永久激活教程

SpringCloud(六)Hystix

一.开启熔断器

1、引入依赖

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>

2、 主程序打上@EnableHystrix标签,开启熔断器功能

@SpringBootApplication
@EnableEurekaClient
/**
 * @EnableHystrix: 开启 hystrix ,开启熔断器功能
 */
@EnableHystrix
@EnableHystrixDashboard //开启 Hystrix Dashboard (断路器:Hystrix 仪表盘)
public class ConsumerApplication {

    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication.class, args);
    }

    //如果赋予了restTemplate负载均衡的能力 就只能通过服务名去调了
    @Bean
    @LoadBalanced  //赋予负载均衡的能力,默认是轮询
    RestTemplate restTemplate(){
        return new RestTemplate();
    }
}

3、在ConsumerController中的方法上打上注解 @HystrixCommand注解,开启熔断器功能

@RestController
public class ConsumerController {

    @Autowired
    private RestTemplate restTemplate;

    //HystrixCommand:给方法启用熔断器功能,当出现访问故障,自动调用 fallbackMethod 指向的方法
    @HystrixCommand(fallbackMethod = "fallback") //此方法开启熔断器
    @RequestMapping("/consumer")
    public String consumerTest(@RequestParam(value = "name") String name){
        String forObject = restTemplate.getForObject("http://PROVIDER/provider?name=" + name, String.class);
        return forObject;
    }

    public String fallback(String name){
        return "出错啦!";
    }
}
  • @HystrixCommand(fallbackMethod="fallback"):声明一个失败回滚处理函数fallback,当queryUserById执行超时(默认是1000毫秒),就会执行fallback函数,返回错误提示。

4、测试:一次启动 EurekaServer,Provider,Consumer服务,访问地址 http://localhost:8083/consumer?name=andy ,你将会看到“andy你好呀这里是Producer服务”,
当关掉 Producer服务,再访问会出现:出错啦!
当Producer服务关掉,那么Consumer服务不能调用Producer服务的接口,那么马上回执行errorMethod方法进行故障处理。

5、这里需要注意, Hystix的超时时间默认也是1000ms,我们在配置的时候, Ribbon的超时时间一定要小于Hystix的超时时间。

我们可以通过 hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds 来设置Hystrix超时时间。

hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMillisecond: 10000 # 熔断超时时长:10000ms

文章永久链接:https://tech.souyunku.com/25096

未经允许不得转载:搜云库技术团队 » SpringCloud(六)Hystix

JetBrains 全家桶,激活、破解、教程

提供 JetBrains 全家桶激活码、注册码、破解补丁下载及详细激活教程,支持 IntelliJ IDEA、PyCharm、WebStorm 等工具的永久激活。无论是破解教程,还是最新激活码,均可免费获得,帮助开发者解决常见激活问题,确保轻松破解并快速使用 JetBrains 软件。获取免费的破解补丁和激活码,快速解决激活难题,全面覆盖 2024/2025 版本!

联系我们联系我们