IDEA开发SpringCloud指南(五)—给Ribbon添加Hystrix熔断器

一 Hystrix 熔断器

在微服务架构中,根据业务拆分成一个个的服务,服务与服务之间可以通过RPC相互调用,在SpringCloud中可以用RestTemlate+ribbon和Feign来调用。为了保证其高可用,单个服务通常会集群部署。由于网络原因或者自身的原因,服务并不能保证100%可用,如果单个服务出现问题,待哦用这个服务就会出现线程阻塞,此时若有大量的请求涌入,Servlet容器的线程资源会被消耗完毕,导致服务瘫痪。服务与服务之间的依赖性,故障会传播,会对整个微服务系统造成灾难性的严重后果,这就是服务故障的“雪崩”效应。

为了解决这个问题,业界提出了熔断器模型

Netflix开源了Hystrix组件,实现了熔断器模式,SpringCloud对着一组件进行了整合。

当对特定的服务调用不可用达到一个阙值(Hystrix是5秒20次)熔断器会被打开。熔断器打开后,为了避免连锁故障,通过fallback方法可以直接返回一个固定值。

二  Ribbon增加Hystrix熔断器

Ribbon和Feign增加熔断器方式略有不同,我们先看下Ribbon增加熔断器的方式

1.  修改文章中的代码,在pom.xml文件里添加spring-cloud-starter--netflix-hystrix的起步依赖:

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

2.在Application里增加@EnableHystrix注解开启Hystrix

@EnableHystrix
@EnableDiscoveryClient
@SpringBootApplication
public class EurekaConsumerRibbonApplication {

	@Bean
	@LoadBalanced//负载均衡
	RestTemplate restTemplate(){
		return new RestTemplate();
	}
	public static void main(String[] args) {
		SpringApplication.run(EurekaConsumerRibbonApplication.class, args);
	}

}

3. 修改ConsumerService类,在ConsumerService方法上加上@HystrixCommand注解。该注解对该方法创建了熔断器的功能,并指定了fallbackMethod熔断方法,熔断方法直接返回了一个字符串,字符串为"hi,"+name+",sorry,error!",代码如下:

@Service
public class ConsumerService {
    @Autowired
    RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "hiError")
    @RequestMapping("hello")
    public String goHello()
    {
        return restTemplate.getForEntity("http://EUREKA-PROVIDER/hello",String.class).getBody();
    }

    public String hiError() {
        return "sorry,error!";
    }
}

4. 运行程序,重新刷新http://localhost:8761 ,界面如下,可以看到eureka_consumer-ribbon已经在到注册中心了:

此时断开eureka-provider,重新输入 http://localhost:8791/hello ,显示如下,证明调用熔断成功

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值