SpringCloud学习(五)-- hystrix学习

一,引入必要的包

            <dependency>
                <groupId>com.netflix.hystrix</groupId>
                <artifactId>hystrix-javanica</artifactId>
                <version>${hystrix.version}</version>
            </dependency>

二、添加部分配置

调用方Application入口,增加@EnableHystrix

@SpringBootApplication
@EnableDiscoveryClient //开启eureka客户端发现功能
@EnableHystrix //开始hystrix
public class ConsumerApplication {

    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication.class,args);
    }

    @Bean
    @LoadBalanced//开启Ribbon的负载均衡,调用时,可以通过user-service名字,找到对应的服务。
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}

对应的方法,配置熔断时执行方法

    @GetMapping("/{id}")
    @HystrixCommand(defaultFallback = "defalutFallback")
    public String queryById(@PathVariable Long id){

        if(id == 1){
            throw new RuntimeException("太忙了");
        }

        //String url = "http://localhost:9091/user/1";

//        List<ServiceInstance> userInstances = discoveryClient.getInstances("user-service");
//
//        ServiceInstance userInstance = userInstances.get(0);
//
//        String url = "http://"+userInstance.getHost()+":"+userInstance.getPort()+"/user/"+id;
        String url = "http://user-service/user/"+id;

        log.info(url);

        String forObject = restTemplate.getForObject(url, String.class);

        log.info(forObject);

        return forObject;
    }

    public String defalutFallback(){
        return "默认提示:对不起,网络太拥挤了!";
    }

四、熔断演示

先访问 http://localhost:8080/consumer/2

出现

再连续访问 http://localhost:8080/consumer/1

出现

再访问 http://localhost:8080/consumer/2

出现

五、部分hystrix配置

hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 20000 # 在调用方配置,被该调用方的所有方法的超时时间都是该值,优先级低于下边的指定配置
      circuitBreaker:
        errorThresholdPercentage: 50 # 触发熔断错误比例阀值,默认50%
        sleepWindowInMilliseconds: 10000 #熔断后休眠状态时长,默认值5秒
        requestVolumeThreshold: 10 # 熔断触发最小请求次数,默认值为0

六、原理简介

七、代码传送门

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值