为什么要用断路器?
在微服务架构中,根据业务来拆分成一个个的服务,服务与服务之间可以相互调用(RPC),在Spring Cloud可以用RestTemplate+Ribbon和Feign来调用。为了保证其高可用,单个服务通常会集群部署。由于网络原因或者自身的原因,服务并不能保证100%可用,如果单个服务出现问题,调用这个服务就会出现线程阻塞,此时若有大量的请求涌入,Servlet容器的线程资源会被消耗完毕,导致服务瘫痪。服务与服务之间的依赖性,故障会传播,会对整个微服务系统造成灾难性的严重后果,这就是服务故障的“雪崩”效应。 为了解决这个问题,业界提出了断路器模型。
什么是断路器?
通俗点就是在服务消费者中添加一个监听,去监听注册中心里面有没有你要调用的服务(也就是监听服务提供者有没有宕机),从而做出其他的反应(一般会告诉用户此服务不能相应)。可以在restTempalte和Feign中使用断路器。
使用断路器
非常简单,首先在restTemplate中使用,需要在pom中引入
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
然后改造HelloService
@Service
public class HelloService {
@Autowired
RestTemplate restTemplate;
@HystrixCommand(fallbackMethod = "hiError")
public String hiService(String name) {
return restTemplate.getForObject("http://SERVICE-HI/hi?name=" + name, String.class);
}
public String hiError(String name) {
return "hi," + name + ",sorry,error!";
}
这样就实现了当服务关闭之后去调用hiError方法给用户很人性化的提示。
然后再Feign中使用断路器
在配置文件中添加
feign:
hystrix:
enabled: true
写一个类来处理这类异常SchedualServiceHiHystric 去实现Service接口
@Component
public class SchedualServiceHiHystric implements SchedualServiceHi {
public String sayHiFromClientOne(String name) {
return "sorry " + name;
}
}
更改Service层SchedualServiceHi
@FeignClient(value = "service-hi",fallback=SchedualServiceHiHystric.class)
public interface SchedualServiceHi {
@RequestMapping(value = "/hi", method = RequestMethod.GET)
String sayHiFromClientOne(@RequestParam(value = "name") String name);
}
这样就实现了在Feign中的找不到服务的处理方式