Spring Cloud服务容错组件Hystrix断路器原理

欢迎来我的博客参观,交流: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);}
  1. 使用@EnableCircuitBreaker开启断路器

注意:这里还可以直接使用@SpringCloudApplication来开启断路器
他相当于我们上面加的三个注解,也就是说Spring Cloud应用默认包含了服务发现和断路器功能

@SpringBootApplication 
@EnableDiscoveryClient 
@EnableCircuitBreaker 
public interface SpringCloudApplication {
   
}
  1. 改造服务消费方式
    新增 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 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值