在微服务架构中,根据业务来拆分成一个个的服务,服务与服务之间可以相互调用(RPC),在Spring Cloud可以用RestTemplate+Ribbon和Feign来调用。为了保证其高可用,单个服务通常会集群部署。由于网络原因或者自身的原因,服务并不能保证100%可用,如果单个服务出现问题,调用这个服务就会出现线程阻塞,此时若有大量的请求涌入,Servlet容器的线程资源会被消耗完毕,导致服务瘫痪。服务与服务之间的依赖性,故障会传播,会对整个微服务系统造成灾难性的严重后果,这就是服务故障的“雪崩”效应。
为了解决这个问题,业界提出了断路器模型。
Netflix开源了Hystrix组件,实现了断路器模式,SpringCloud对这一组件进行了整合。 在微服务架构中,一个请求需要调用多个服务是非常常见的,如下图:
较底层的服务如果出现故障,会导致连锁故障。当对特定的服务的调用的不可用达到一个阀值(Hystric 是5秒20次) 断路器将会被打开。
断路打开后,可用避免连锁故障,fallback方法可以直接返回一个固定值
启动eureka-server 启动eureka-client
1在ribbon中添加断路器
在ribbon-server服务pom.xml文件中添加对hystrix的依赖
<!--熔断器-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
在启动类中添加@EnableHystrix注解
@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
@EnableHystrix
public class RibbonServerApplication {
public static void main(String[] args) {
SpringApplication.run(RibbonServerApplication.class, args);
}
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
改造HelloService类,在hello方法上加上@HystrixCommand注解。该注解对该方法创建了熔断器的功能,并指定了fallbackMethod熔断方法,熔断方法直接返回了一个字符串,字符串为"出现错误了!"
@Service
public class HelloService {
@Autowired
private RestTemplate restTemplate;
@HystrixCommand(fallbackMethod="error")
public String hello(String name){
return restTemplate.getForObject("http://eureka-client/hi?name="+name,String.class);
}
public String error(String name){
return "出现错误了!";
}
}
启动ribbon
正常访问http://localhost:8764/hi?name=123
此时如果停止eureka-client服务 再次访问发现快速执行error方法
2Feign中使用断路器
Feign是自带断路器的,在D版本的Spring Cloud之后,它没有默认打开。需要在配置文件中配置打开它,在配置文件加以下代码:
application.properties文件中添加
feign.hystrix.enabled=true
Feign接口Hello上加@FeignClient注解
@FeignClient(value = "eureka-client",fallback = HelloHystrix.class)
public interface Hello {
@RequestMapping(value = "/hi",method = RequestMethod.GET)
public String selectOneTohello(@RequestParam(value="name") String name);
}
添加HelloHystrix实现Hello接口
@Component
public class HelloHystrix implements Hello{
@Override
public String selectOneTohello(String name) {
return "出错了!";
}
}
正常访问http://localhost:8765/hi?name=123
此时如果停止eureka-client服务 再次访问发现快速执行error方法