在一个项目中,系统可能被拆分红多个服务,例如用户、订单和库存等。java
这里存在这服务调用服务的状况,例如,客户端调用订单服务,订单服务又调用库存服务。git
此时若库存服务响应缓慢,会直接致使订单服务的线程被挂起,以等待库存申请服务的响应,在漫长的等待以后用户会由于请求库存失败而获得建立订单失败的结果。github
若是在高并发下,因这些挂起的线程在等待库存服务的响应而未能得到释放,会似的后续到来的请求被阻塞,最终致使订单服务也不可用。web
在分布式架构中,断路器模式的做用也是相似的,当某个服务单元发生故障以后,经过断路器的故障监控,向调用方返回一个错误响应,而不是漫长的等待。spring
首先,添加断路器hystrix的依赖。缓存
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-hystrix</artifactId> </dependency>
接着在工程的主类,添加注解@EnableCircuitBreaker:架构
package cn.net.bysoft.owl.bookstore.web.console; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate; @SpringBootApplication @EnableDiscoveryClient @EnableCircuitBreaker public class OwlBookstoreWebConsoleApplication { @Bean @LoadBalanced RestTemplate restTemplate() { return new RestTemplate(); } public static void main(String[] args) { SpringApplication.run(OwlBookstoreWebConsoleApplication.class, args); } }
接着,就能够使用断路器了,能够添加@HystrixCommand注解,对调用服务的方法进行修饰:并发
@HystrixCommand(fallbackMethod = "findByIdFallback") public User findById(Long id) { UriComponents uriComponents = UriComponentsBuilder.fromUriString("http://SERVICE-USER/users/{id}").build() .expand(id).encode(); URI uri = uriComponents.toUri(); return restTemplate.getForObject(uri, User.class); } public User findByIdFallback(Long id) { return null; }
fallbackMethod是服务发生异常时,回调的降级处理函数,该函数的参数和返回值要与调用函数一致。分布式
断路器的默认超时时间为2000毫秒。当被断路器修饰的函数执行超过这个值,将触发断路器的服务降级,该参数是能够设置的。函数
全局配置属性:hystrix.[attr].default.
实例配置属性:hystrix.[attr].[key].