Spring Cloud 应用篇 之 Hystrix 的基本使用
在微服务架构中,我们会将系统根据业务垂直拆分为很多服务,各个服务之间通过注册与订阅的方式相互依赖。但是由于网络出现不稳定或自身服务出现异常,导致调用故障或延迟,此时若并发量很大,可能会导致服务崩溃。断路器 Hystrix 就是解决此问题的。
(一)简介
Spring Cloud Hystrix 是基于 Netflix 的开源框架 Hystrix 实现的,它具有断路器、线路隔离等一系列服务保护功能。Hystrix 具备服务降级、服务熔断、请求缓存、请求合并以及服务监控等强大功能。
(二)基于 Ribbon 使用 Hystrix
1. 仍然是基于上一篇的工程,启动 eureka-service,spring-demo-service
2. 修改 spring-demo-service-ribbon 的 pom 文件,添加 Hystrix 的依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
修改启动类,添加 @EnableHystrix 注解开启 Hystrix 功能
@SpringBootApplication
@EnableEurekaClient
@EnableHystrix
public class ServiceRibbonApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceRibbonApplication.class, args);
}
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
@Bean
public IRule ribbonRule() {
return new RandomRule(); //这里配置策略,和配置文件对应
}
}
修改 SpringDemoRibbonService
@Service
public class SpringDemoRibbonService {
@Autowired
RestTemplate restTemplate;
@Autowired
LoadBalancerClient loadBalancerClient;
@HystrixCommand(fallbackMethod = "portFallback")
public String port() {
this.loadBalancerClient.choose("spring-demo-service"); //随机访问策略
return restTemplate.getForObject("http://SPRING-DEMO-SERVICE/port", String.class);
}
public String portFallback() {
return "sorry ribbon, it's error!";
}
}
在 port 方法上加上 @HystrixCommand 注解,对此方法开启熔断器功能,用 fallbackMethod 属性指定熔断回调方法。
启动 spring-demo-service-ribbon,访问 localhost:8381/hello,浏览器会正常显示:
关闭 spring-demo-service,再次访问 localhost:8381/hello,浏览器显示:
即是熔断方法 portFallback 输出的一串字符。说明 spring-demo-service 出现异常或不可用时,spring-demo-service-ribbon 调用其接口失败,会直接调用熔断方法返回,而不会等待超时响应。
(三)基于 Feign 使用 Hystrix
Feign 自带熔断器功能,但是在 Dalston 版本之后,其默认是关闭的,需要手动打开。
1. 修改 spring-demo-service-feign 的 pom 文件,添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
2. 修改配置文件,添加下面的配置,打开 Feign 的熔断功能
feign:
hystrix:
enabled: true
3. 修改 SpringDemoFeignService 接口,在 @FeignClient 注解中加入 fallback 即可。
@FeignClient(value = "spring-demo-service", fallback = ErrorHystrix.class)
public interface SpringDemoFeignService {
@RequestMapping(value = "port", method = RequestMethod.GET)
String hello();
}
4. 创建上一步指定的 ErrorHystrix 类,实现 SpringDemoFeignService 接口,注入容器中
@Component
public class ErrorHystrix implements SpringDemoFeignService {
@Override
public String hello() {
return "sorry, it's error!";
}
}
5. 启动 spring-demo-service-feign
浏览器访问 localhost:8382/hello,当 spring-demo-service 正常启动的时候,浏览器访问即正常显示调用,当 spring-demo-service 关闭或者出现异常的时候,浏览器会显示 fallback 指定类里的方法的返回值。截图这里就不贴了。
还没有评论,来说两句吧...