一、Maven 配置
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>二、主程序上配置的注解
@EnableHystrix或@EnableCiruitBreaker三、Controller配置
通过以下代码可以看出, 在/eureka/{id} 请求访问注解上,加了@HystrixCommand注解,如果访问失败,会请求findByIdFallback方法返回数据,在下文中,会详细描述Hystrix的更多功能。
/**
* #1 第一种 基于Eureka服务方式来调用
*
* @param id
* @return
*/
@GetMapping("/eureka/{id}")
@HystrixCommand(fallbackMethod="findByIdFallback")
public User findByIdEureka(@PathVariable Long id) {
User user = this.restTemplate.getForObject("http://cloud-service/get/" + id, User.class);
String rs = loadEurekaInstance();
user.setEurekaServiceName(rs);
return user;
}
public User findByIdFallback(Long id) {
User user = new User();
user.setId(-1L);
user.setName("NULL");
return user;
}
本文介绍如何使用 Spring Cloud Hystrix 实现服务间的熔断与容错处理。通过具体代码示例展示了如何配置 Maven 依赖、启用 Hystrix 注解,并在 Controller 中实现基于 Eureka 的服务调用及熔断回退逻辑。
2万+

被折叠的 条评论
为什么被折叠?



