(27)java Spring Cloud企业快速开发架构之SpringCloud-使用Hystrix实现容错处理
2021/9/22 17:10:14
本文主要是介绍(27)java Spring Cloud企业快速开发架构之SpringCloud-使用Hystrix实现容错处理,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
创建一个新的 Maven 项目 hystrix-feign-demo,增加 Hystrix 的依赖,代码如下所示。
1 2 3 4 |
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
|
![点击并拖拽以移动](/upload/202109/22/202109221710140454.png)
在启动类上添加 @EnableHystrix 或者 @EnableCircuitBreaker。注意,@EnableHystrix 中包含了 @EnableCircuitBreaker。推荐分布式架构源码
然后编写一个调用接口的方法,在上面增加一个 @HystrixCommand 注解,用于指定依赖服务调用延迟或失败时调用的方法,代码如下所示。
1 2 3 4 5 6 |
@GetMapping( "/callHello" )
@HystrixCommand(fallbackMethod = "defaultCallHello" )
public String callHello() {
String result = restTemplate.getForObject(");
return result;
}
|
当调用失败触发熔断时会用 defaultCallHello 方法来回退具体的内容,定义 default-CallHello 方法的代码如下所示。
1 2 3 |
public String defaultCallHello() {
return "fail" ;
}
|
只要不启动 8088 端口所在的服务,调用 /callHello 接口,就可以看到返回的内容是“fail”,如图 1 所示。
将启动类上的 @EnableHystrix 去掉,重启服务,再次调用 /callHello 接口可以看到返回的是 500 错误信息,这个时候就没有用到回退功能了。
1 2 3 4 5 6 7 8 |
{
code: 500 ,
message: "I/O error on GET request for
"
exception is java.net.ConnectException: Connection refused
", data:
null
}
|
配置详解
HystrixCommand 中除了 fallbackMethod 还有很多的配置,下面我们来看看这些配置,如下表所示:
HystrixCommand 配置详解
官方的配置信息文档请参考:。
上面列出来的都是 Hystrix 的配置信息,那么在 Spring Cloud 中该如何使用呢?只需要在接口的方法上面使用 HystrixCommand 注解(如下代码所示),指定对应的属性即可。
1 2 3 4 5 6 7 8 9 |
@HystrixCommand(fallbackMethod = "defaultCallHello" ,commandProperties = {
@HystrixProperty(name= "execution.isolation.strategy" , value = "THREAD" )
}
)
@GetMapping( "/callHello" )
public String callHello() {
String result = restTemplate.getForObject(");
return result;
}
|
需要框架源码的朋友可以看我个人简介联系我
这篇关于(27)java Spring Cloud企业快速开发架构之SpringCloud-使用Hystrix实现容错处理的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-06-26结对编程到底难不难?答案在这里
- 2024-06-19《2023版Java工程师》课程升级公告
- 2024-06-15matplotlib作图不显示3D图,怎么办?
- 2024-06-1503-Loki 日志监控
- 2024-06-1504-让LLM理解知识 -Prompt
- 2024-06-05做软件测试需要懂代码吗?
- 2024-06-0514-ShardingSphere的分布式主键实现
- 2024-06-03为什么以及如何要进行架构设计权衡?
- 2024-05-31全网首发第二弹!软考2024年5月《软件设计师》真题+解析+答案!(11-20题)
- 2024-05-31全网首发!软考2024年5月《软件设计师》真题+解析+答案!(21-30题)