eureka整合Hystrix,添加熔断机制
首先Hystrix是干什么的?
在分布式环境中(微服务中),我们有可能将服务注册在了注册中心里,暴露相关服务,然后呢,在各个服务之间相互调用,因此很有可能出现各种各样的问题,导致服务不可用。在这种情况下,导致雪崩,级联到服务调用放也会出现雪崩,这是很严肃的一件事。为了解决这一问题,因此引出今天的主角Hystrix(豪猪,自我保护机制)。服务依赖项中的一些必然会失败。Hystrix是一个库,通过添加延迟容忍和容错逻辑,帮助你控制这些分布式服务之间的交互。Hystrix通过隔离服务之间的访问点、停止级联失败和提供回退机制,是服务不至于级联崩溃,实现高可用。
学习Hystrix!
上一篇我们已经搭建好了eureka [【spring-cloud-eureka】][1],今天在他的基础上进行实现服务的熔断。
废话不多说,我们直接在服务调用方引入依赖
<!--熔断器-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
<version>${spring-cloud-starter-hystrix.version}</version>
</dependency>
<!--hystrix-dashboard 监控 可视化工具-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
<version>${spring-cloud-starter-hystrix-dashboard.version}</version>
</dependency>
接口和之前没变化,只需要在接口上添加如下注解
控制器(也贴出来吧)
@RestController
public class ConsumerController {
@Autowired
HelloRemoteService helloRemoteService;
@RequestMapping("/hello")
public String hello() {
return helloRemoteService.hi();
}
接口层
@Service
public class HelloRemoteService {
@Autowired
HelloRemoteInterface helloRemoteInterface;
@HystrixCommand(fallbackMethod = "fallback") //服务调用失败之后的回调方法。
public String hi() {
return helloRemoteInterface.hi();
}
public String fallback() {
return "这是熔断器的降级方法。";
}
}
看一下我们的启动类
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
@EnableHystrix //支持熔断注解
@EnableHystrixDashboard //监控
public class LocalApplication {
// spring-cloud Finchley.SR1这个版本在Hystrix图形化界面输入监控的服务地址后有bug,不能正常显示监控页面,因此加上该bean
@Bean
public ServletRegistrationBean getServlet() {
HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();
ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet);
registrationBean.setLoadOnStartup(1);
registrationBean.addUrlMappings("/hystrix.stream");
registrationBean.setName("HystrixMetricsStreamServlet");
return registrationBean;
}
public static void main(String[] args) {
SpringApplication.run(LocalApplication.class, args);
}
}
最后一步就是我们的配置文件
feign:
client:
config:
feignName:
connectTimeout: 5000
readTimeout: 5000
hystrix:
enabled: true
hystrix:
command:
default:
execution:
timeout:
#如果enabled设置为false,则请求超时交给ribbon控制,为true,则超时作为熔断根据
enabled: true
isolation:
thread:
timeoutInMilliseconds: 500 #线程超时,调用Fallback方法,断路器超时时间,默认1000ms
下边测试是在服务提供端正常的情况下,做的测试
我们更改一下服务提供端代码,模拟网路不好的条件下;客户端的表现如何
更改代码如下;
/**
* 模拟网络延迟
*/
try {
Random random = new Random();
int i = random.nextInt(2000);
Thread.sleep(i);
System.out.println("网络延迟时间" + i);
} catch (InterruptedException e) {
e.printStackTrace();
}
启动服务,调用接口测试。
上图为服务降级的示例,延迟617s,我们配置500超时,然后熔断。(但是调用了两次服务,暂时没有明白是为什么,可能是一个重试机制。也可能不是)
上图为正常情况下,请求延迟244s,结果符合预期。
顺便说一下可视化工具
启动本地服务的时候,控制台上出现http://127.0.0.1:9000//hystrix.stream
直接访问http://127.0.0.1:9000//hystrix
访问如下显示,可以监控访问的执行情况,失败和成功率等,可以深入研究。
本节完。
[1]: https://blog.csdn.net/a_a_3730/article/details/94969512