欢迎来我的博客参观,交流:https://endwas.cn
Spring Cloud Hystrix是用于做微服务之间服务短路,服务限流,服务降级,服务容错等的组件,为了避免在庞大微服务系统中,因为某一服务依赖出现异常导致全盘崩溃的严重问题。
1.快速入门
@EnableCircuitBreaker
@EnableDiscoveryClient
@SpringBootApplication
public class ConsumerApplication {
@Bean
@LoadBalanced
RestTemplate restTemplate () {
return new RestTemplate ();
}
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class, args);
}
}
- 使用@EnableCircuitBreaker开启断路器
注意:这里还可以直接使用@SpringCloudApplication来开启断路器
他相当于我们上面加的三个注解,也就是说Spring Cloud应用默认包含了服务发现和断路器功能
@SpringBootApplication
@EnableDiscoveryClient
@EnableCircuitBreaker
public interface SpringCloudApplication {
}
- 改造服务消费方式
新增 HelloService 类, 注入RestTemplate 实例。 然后在 helloService 函数上增加@HystrixCommand 注解来指定降级方法,最后就可以在调用的Controller中注入该service进行函数式调用即可。
@Service
public class HelloService {
@Autowired
RestTemplate restTemplate;
@HystrixCommand(fallbackMethod = "helloFallback")
public String helloService() {
return restTemplate.getForEntity("http://HELLO-SERVICE/hello", String.class) .getBody();
}
public