Spring Cloud入门与实践(三)-Hystrix

接着跟着前一篇,通过负载均衡来减轻服务端压力,客户端利用RestTemplate来获取服务。
那么这里有个问题,如果所有服务器极限压力了,那么就算负载都没有用了,等了好久没返回怎么办?
此时就需要服务器的容错机制了。

容错性

服务的容错性,简单讲就是为失败而设计。比如以下情况:
由于网络原因或是依赖服务自身问题出现调用故障或延迟,而这些问题直接导致调用方的对外服务也延迟,若此时调用方请求不断增加,最后就会
因等待出现故障的依赖方响应形成任务积压,最终导致自身服务的瘫痪。

What is Hystrix

Spring Cloud Hystrix 实现了断路器,线程隔离等一系列服务保护功能,它也是基于Netflix的开源框架Hystrix实现的。
Hystrix具有服务降级、服务熔断、线程和信号隔离、请求缓存、请求合并以及服务监控等强大功能。

例子

  1. pom文件
    在原有pom文件的基础上,加入Hystrix支持:
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix</artifactId>
        </dependency>
  1. 在启动类上,加入@EnableCircuitBreaker ,从而开启断路器功能。

  2. 对可能需要容错的方法,加入额外容错参数:
    例如在本例中,编写了一个HystrixService 类,对它的hystrixService方法进行容错操作:

@Service
public class HystrixService {
    @Autowired
    private RestTemplate restTemplate;
    @HystrixCommand(fallbackMethod = "hystrixFallback")
    public String hystrixService(String name){
        ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://hello-service/hystrix?name={1}",String.class,name+":test anla");
        String body = responseEntity.getBody();
        return body;
    }
    public String hystrixFallback(String name){
        return "arg is "+name+",sorry,service is busy, please wait a moment and try again.";
    }
}

这样依赖,当调用hystrixService失败时候(超时或者报错),例如在controller等里面调用,就会调用hystrixFallback返回结果。
从而使得无论成功或者失败,结果都是可控的。

Hystrix Dashboard

Hystrix还给我们提供了一个监控功能,从里面可以看到Hystrix的各项指标信息。以下几步即可轻松应用
1. pom文件:

<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
  1. 在application.yaml上面配置端口以及实例名称:
spring:
  application:
    name: hystrix-dashboard
server:
  port: 2001
  1. 开启@EnableHystrixDashboard 在启动类上加上如上注解即可。
    这里写图片描述

  2. 如果需要监控某个包含熔断器的应用熔断情况,在上图输入该项目地址例如:http://127.0.0.1:8086/hystrix.stream 再点击Monitor Stream 即可。 另外,需要在pom中加入hystrix和actuator两个依赖包。此时就能看到如下dashboard:
    这里写图片描述

实心圆:颜色代表健康度,(绿-黄-红-橙递减);大小代表并发量。
曲线:请求量的变化,可以通过他来观察流量上升下降趋势

本篇例子在v3分支:hello-springcloud

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值