• spring cloud学习(三) 断路器


    在Spring Cloud中使用了Hystrix 来实现断路器的功能。Hystrix是Netflix开源的微服务框架套件之一,该框架目标在于通过控制那些访问远程系统、服务和第三方库的节点,从而对延迟和故障提供更强大的容错能力。Hystrix具备拥有回退机制和断路器功能的线程和信号隔离,请求缓存和请求打包,以及监控和配置等功能。

    一、ribbon中使用hystrix

    这里继续使用上一篇的client-a。

    1.1
    pom文件添加hystrix

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

    1.2
    ClientApplication添加@EnableHystrix开启hystrix功能

    1.3
    Controller, 使用@HystrixCommand指定回调方法

    @RestController
    public class TestController {
    
        @Autowired
        RestTemplate restTemplate;
    
        @RequestMapping("/hi")
        @HystrixCommand(fallbackMethod = "hiFallback")
        public String hi(@RequestParam String id){
            return restTemplate.getForObject("http://service-a/hi?id="+id, String.class);
        }
    
        public String hiFallback(String id) {
            return "hi, " + id + ", error!";
        }
    }
    

    1.4
    启动client-a, 然后关闭service-a, 打开页面

    可以看到成功返回错误信息,实现断路回调。

    二、feign中使用hystrix

    2.1
    feign是自带断路器功能的,并且默认打开,如果你要关闭的话,需要加上这个配置:

    feign:
        hystrix:
            enabled: false
    

    2.2
    这里只需要在@FeignClient注解上加上fallback就可以了

    @Component
    @FeignClient(value = "service-a", fallback = ServiceAFeignClientFallback.class) //这里的value对应服务的spring.applicatoin.name
    public interface ServiceAFeignClient {
    
        @RequestMapping(value = "/hi")
        String hi(@RequestParam("id") String id);
    
    }
    

    ServiceAFeignClientFallback:

    /**
     * @author fengzp
     * @date 17/5/9
     * @email fengzp@gzyitop.com
     * @company 广州易站通计算机科技有限公司
     */
    public class ServiceAFeignClientFallback implements ServiceAFeignClient {
    
        @Override
        public String hi(String id) {
            return "hi, " + id + ", error!";
        }
    
    }
    
  • 相关阅读:
    SolrCloud-5.2.1 集群部署及测试
    提问的艺术
    Zookeeper集群部署
    Linux基本操作命令总结
    LeetCode——Gray Code
    LeetCode——Find the Duplicate Number
    如何拿到国内IT巨头的Offer
    LeetCode—— Median of Two Sorted Arrays
    LeetCode——Merge k Sorted Lists
    CSS常见Bugs及解决方案列表
  • 原文地址:https://www.cnblogs.com/andyfengzp/p/6831145.html
Copyright © 2020-2023  润新知