熔断器简介
在微服务架构中, 根据业务来拆分成一个个的服务, 服务与服务之间可以用过RPC相互调用。为了保证其高可用, 单个服务通常会集群部署。由于网络原因或者自身的原因, 服务并不能保证100%可用, 如果单个服务出现问题, 调用这个服务就会出现线程阻塞, 此时若有大量的请求涌入, Servlet容器的线程资源会被消耗完毕, 导致服务瘫痪。服务与服务之间的依赖性, 故障会传播, 会对整个微服务系统造成灾难性的严重后果, 这就是服务的雪崩效应
为了解决这个问题, 业界提出了熔断器模型
Netflix开源了Hystrix组件, 实现了熔断器模式, Spring Cloud对这一组件进行了整合
较低层的服务如果出现了故障, 会导致连锁故障。当特定的服务的调用不可用达到一个阈值(Hystrix是5秒20次)熔断器将会被断开
熔断器打开后, 为了避免连锁故障, 通过fallback方法可以直接返回一个固定值
Dubbo Provider中使用熔断器
在pom.xml中增加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
<version>2.0.1.RELEASE</version>
</dependency>
在Application中增加@EnableHystrix注解
@EnableHystrix
@SpringBootApplication
public class HelloDubboServiceUserProviderApplication {
public static void main(String[] args) {
SpringApplication.run(HelloDubboServiceUserProviderApplication.class, args);
Main.main(args);
}
}
在Service中增加@HystrixCommand注解
在调用方法上增加@HystrixCommand配置, 此时调用会经过Hystrix代理
@Service(version="${user.service.version}")
public class UserServiceImpl implements UserService {
@Value("${dubbo.protocol.port}")
private String port;
@HystrixCommand(commandProperties = {
@HystrixProperty(name="circuitBreaker.requestVolumeThreshold", value = "10"),
@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds", value="2000")
})
@Override
public String sayHi() {
//return "Hello Dubbo, i am from port:" + port;
throw new RuntimeException("Exception to show hystrix enabled.")
}
}
测试熔断器
此时我们再次请求服务提供者, 浏览器会包500异常
Exception to show hystrix enabled
Dubbo Consumer中使用熔断器
在pom中添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
<version>2.0.1.RELEASE</version>
</dependency>
在Application中增加@EnableHystrix注解
@EnableHystrix
@SpringBootApplication
public class HelloDubboServiceUserConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(HelloDubboServiceUserConsumerApplication.class, args);
}
}
在调用方法上增加@HystrixCommand注解, 并指定fallbackMethod方法
@RestController
public class UserController {
@Reference(version="${user.service.version}")
private UserService userService;
@HystrixCommand(fallbackMethod = "hiError")
@RequestMapping(value="hi", method= RequestMethod.GET)
public String sayHi(){
return userService.sayHi();
}
public String hiError(){
return "Hystrix fallback";
}
}
测试熔断器
此时再次请求服务提供者, 浏览器显示
Hystrix fallback