spring cloud: Hystrix(一):简单使用
在微服务架构中,我们将系统拆分为很多个服务,各个服务之间通过注册与订阅的方式相互依赖,由于各个服务都是在各自的进程中运行,就有可能由于网络原因或者服务自身的问题导致调用故障或延迟,随着服务的积压,可能会导致服务崩溃。为了解决这一系列的问题,断路器等一系列服务保护机制出现了。
断路器本身是一种开关保护机制,用于在电路上保护线路过载,当线路中有电器发生短路时,断路器能够及时切断故障电路,防止发生过载、发热甚至起火等严重后果。
在分布式架构中,断路器模式的作用也是类似的。
针对上述问题,Spring Cloud Hystrix 实现了断路器、线路隔离等一系列服务保护功能。它也是基于 Netflix 的开源框架 Hystrix 实现的,该框架的目标在于通过控制那些访问远程系统、服务和第三方库的节点,从而对延迟和故障提供更强大的容错能力。Hystrix 具备服务降级、服务熔断、线程和信号隔离、请求缓存、请求合并以及服务监控等强大功能。
简单直白的介绍:
但A调用B服务时,B服务不太稳定,经常挂掉。那么在A调用的方法里加入Hystrix方法,并写一个fallbackMethod方法;在A服务多次调用B服务失败后,将不在调用B服务,而是直接返回fallbackMethod方法.
1.引入配置:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
2.简单实例
app入库文件加入:@EnableCircuitBreaker注解
@EnableEurekaClient
@SpringBootApplication
@EnableCircuitBreaker
public class HystrixApplication {
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(HystrixApplication.class, args);
}
}
在调用B服务的方法里加入@HystrixCommand(fallbackMethod=“”)注解
@RestController
public class MovieController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/movie/{id}")
@HystrixCommand(fallbackMethod = "notfindback")
public User findById(@PathVariable Long id)
{
//http://localhost:7900/simple/
return restTemplate.getForObject("http://spring-boot-user/simple/" + id, User.class);
}
public User notfindback(Long id)
{
User user = new User();
user.setId(0L);
return user;
}
}
运行实例,可以看到结果。
浙公网安备 33010602011771号