SpringCloud(四)Hystrix服务降级,服务熔断

目录

一.服务容错降级

1.介绍

2.代码实现

二.熔断机制


在spring cloud组件中 spring cloud Hystrix是防雪崩的利器,它也是基于Netflix提供的Hystrix进行封装的。

一.服务容错降级

1.介绍

  • 优先核心服务,非核心服务不可用或弱可用
  • 通过HystrixCommand注解指定
  • fallbackMethod(回退函数)中具体实现降级逻辑

2.代码实现

首先是一个基本的restful请求(可以在customer启动类上将@SpringBootApplication替换成@SpringCloudApplication)

// 断路器配置,当无法调用如下方法时,就会调用自定的hiError方法。
    @HystrixCommand(fallbackMethod = "hiError")
    public String hiService(String name)
    {
        RestTemplate restTemplate = new RestTemplate();
        String data =  restTemplate.getForObject("http://service-provider/hi?name=" + name, String.class);
        return data;
    }

    public String hiError(String name)
    {
        return "hey " +
                name + ", there is some problem with hi page";
    }

当hiService方法出错时,服务降级会执行hiError方法。
但是,如果超时之后,也会进行服务降级,那么就需要根据需求配置超时时间。

#配置hystrix的超时时间
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=5000

#配置方法体的超时时间
hystrix.command.方法名.execution.isolation.thread.timeoutInMilliseconds=5000

也可以注解对指定方法配置超时时间

  // 断路器配置,当无法调用如下方法时,就会调用自定的hiError方法。
    @HystrixCommand(fallbackMethod = "hiError",
            commandProperties = {@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value = "5000")})
    public String hiService(String name)
    {
        String data =  restTemplate.getForObject("http://service-provider/hi?name=" + name, String.class);
        return data;
    }

无论使用哪种配置,要实现服务降级,都需要在方法体上加入注解@HystrixCommand
另外,如果使用的是feign,则使用的是ribbon的超时设置

#ribbon的超时时间
ribbon.ReadTimeout=3000
ribbon.ConnectTimeout=3000

二.熔断机制

熔断机制:当一段时间内请求量超过限制的时候,会进行断路器模式。
断路器模式:将受保护的服务封装在一个可以监控故障的断路器对象中去,当故障达到一定的值,断路器将会跳闸,断路器对象返回错误信息。

1.断路器配置

@HystrixCommand(commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),//最小请求数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),//10秒时间窗口(进行请求统计)。休眠之后再次设置断路器half open(允许正常请求)
            @HystrixProperty(name="circuitBreaker.errorThresholdPercentage",value = "60")})//百分比条件,时间窗口内达到最小请求数,错误率高达60%,则打开断路器
#断路器
feign.hystrix.enabled=true


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值