码迷,mamicode.com
首页 > 编程语言 > 详细

springcloud学习04- 断路器Spring Cloud Netflix Hystrix

时间:2019-12-20 15:23:47      阅读:85      评论:0      收藏:0      [点我收藏+]

标签:eureka   网络   disco   servlet   模型   灾难   toc   end   tor   

依赖上个博客:https://www.cnblogs.com/wang-liang-blogs/p/12072423.html

1.断路器存在的原因

引用博客 https://blog.csdn.net/zhou199252/article/details/80745151 的说明

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


2.在项目中使用断路器

  2.1.在eureka-customer的pom文件中加入相关的jar包

<!--断路器-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-hystrix</artifactId>
    <version>1.4.4.RELEASE</version>
</dependency>

  2.2.在eureka-customer/EurekaCustomerApplication.java中增加@EnableHystrix注解表示开启断路器

package com.springcloud.eurekacustomer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@EnableDiscoveryClient
@EnableHystrix
public class EurekaCustomerApplication {

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

    @Bean
    @LoadBalanced
    RestTemplate restTemplate(){
        return new RestTemplate();
    }


}

  2.3.在service中加入断路器所需的fallback方法

package com.springcloud.eurekacustomer;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class HelloService {

    @Autowired
    RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "helloError")
    public String helloService(){
        String rltStr = restTemplate.getForObject("http://server-provider/hello",String.class);
        rltStr = rltStr + " form service-provider by service-customer.";
        return rltStr;
    }

    public String helloError(){
        return "eureka-provider dowm";
    }

}

  2.4.用postman测试

关闭eureka-provider的服务,用postman调用eureka的接口localhost:8887/cushello,结果如下:

技术图片

这时候就会不调用服务eureka-provider而是调用一个eureka-customer的一个对服务宕机时的一个统一处理,不会导致一些的网络超时的错误抛出,发送“雪崩”现象。

springcloud学习04- 断路器Spring Cloud Netflix Hystrix

标签:eureka   网络   disco   servlet   模型   灾难   toc   end   tor   

原文地址:https://www.cnblogs.com/wang-liang-blogs/p/12073175.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!