官网地址

程序猿升级课

热爱开源,喜欢摸索


Spring Cloud系列三 之 Hystrix断路器

声明本篇文章部分内容参考自 程序猿DD Spring Cloud系列书籍

断路器模式源于Martin Fowler的Circuit Breaker一文。“断路器”本身是一种开关装置,用于在电路上保护线路过载,当线路中有电器发生短路时,“断路器”能够及时的切断故障电路,防止发生过载、发热、甚至起火等严重后果。

在分布式架构中,断路器模式的作用就像是生活中家庭用电,一旦发生短路,就立马断电,不让灾难蔓延。

Netflix Hystrix

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

在Spring Cloud中使用Hystrix组件,是非常容易的,只需要两个注解

  • 准备工作

首先启动(eureka-server)服务注册中心,两个Service服务

  • 添加Hystrix断路器组件

只需要引入Hystrix依赖,在Ribbon负载均衡应用启动类添加@EnableCircuitBreaker

@SpringBootApplication
@EnableDiscoveryClient
@EnableCircuitBreaker
public class RibbonApplication {
    @Bean
    @LoadBalanced
    RestTemplate restTemplate() {
        return new RestTemplate();
    }
    public static void main(String[] args) {
        SpringApplication.run(RibbonApplication.class, args);
    }
}

改造原来的服务消费方式,新增ComputeService类,在使用ribbon消费服务的函数上增加@HystrixCommand注解来指定回调方法。

@Service
public class ComputeService {
    @Autowired
    RestTemplate restTemplate;
    @HystrixCommand(fallbackMethod = "addServiceFallback")//回调方法
    public String addService() {
        return restTemplate.getForEntity("http://COMPUTE-SERVICE/add?a=10&b=20", String.class).getBody();
    }
    public String addServiceFallback() { //回调方法
        return "error";
    }
}

本文标题:Dekel Tankel 谈 Cloud Foundry 与 Spring 前景
本文地址:https://www.oschina.net/news/68979/cloudfundry-meetup

posted @ 2017-02-23 19:56  chinesszz  阅读(96)  评论(0编辑  收藏  举报
ヾ(≧O≦)〃嗷~