1.在微服务架构中,咱们将系统拆分为不少个服务,各个服务之间经过注册与订阅的方式相互依赖,因为各个服务都是在各自的进程中运行,就有可能因为网络缘由或者服务自身的问题致使调用故障或延迟,随着服务的积压,可能会致使服务崩溃。为了解决这一系列的问题,断路器等一系列服务保护机制出现了。spring
断路器自己是一种开关保护机制,用于在电路上保护线路过载,当线路中有电器发生短路时,断路器可以及时切断故障电路,防止发生过载、发热甚至起火等严重后果。缓存
在分布式架构中,断路器模式的做用也是相似的。网络
针对上述问题,Spring Cloud Hystrix 实现了断路器、线路隔离等一系列服务保护功能。它也是基于 Netflix 的开源框架 Hystrix 实现的,该框架的目标在于经过控制那些访问远程系统、服务和第三方库的节点,从而对延迟和故障提供更强大的容错能力。Hystrix 具有服务降级、服务熔断、线程和信号隔离、请求缓存、请求合并以及服务监控等强大功能架构
2.引入依赖(在ribbon的客户端的依赖的添加)负载均衡
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-hystrix -->框架
<dependency>分布式
<groupId>org.springframework.cloud</groupId>微服务
<artifactId>spring-cloud-starter-hystrix</artifactId>this
<version>1.4.6.RELEASE</version>.net
</dependency>
3.在启动类上添加熔断器开关注解
SpringBootApplication
@EnableEurekaClient
//开启熔断标识
@EnableHystrix
public class OneEurekaClientApplication {
@LoadBalanced//让restTemplate具有Ribbon负载均衡的能力。
public RestTemplate restTemplate()
{
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(OneEurekaClientApplication.class, args);
}
}
4.在service要调用的客户端连接上的方法加上熔断后的注解
@HystrixCommand(fallbackMethod = "erroMsg")
public String getClientString(){
logger.info("到这里........................getClientString");
return this.restTemplate.getForObject("http://two-client/home/index", String.class);
}
public String erroMsg(){
return "您请求的接口出现了一点的错误....";
}
5.请求客户端,把two-client关闭,返回的数据