SpringCloud组件四之Hystrix-熔断器(G版本)

1.熔断器

熔断器是为了防止“雪崩效应”的发生所提出的模型。

  • 雪崩效应
    下图为个独立服务之间的依赖关系,假设服务A出故障,不可使用,随着时间推移,服务A,B,C,D都会不可用,使得系统瘫痪。

在这里插入图片描述

2.项目现状

一个注册中心(registry),服务提供微服务(provider),消费者(ribbon),消费者(feign)
在这里插入图片描述

3.Ribbon项目

  • POM文件中添加依赖
      <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>
  • 启动类添加注解:@EnableHystrix
@SpringBootApplication
@EnableEurekaClient
@EnableHystrix
public class RibbonApplication {

    public static void main(String[] args) {
        SpringApplication.run(RibbonApplication.class, args);
    }

    @Bean
    @LoadBalanced //Ribbon具有负载均衡的功能,添加该注解表示开启
    RestTemplate restTemplate() {
        return new RestTemplate();
    }

}
  • 对controller类进行修改
@RestController
public class TestController {

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("hello")
    @HystrixCommand(fallbackMethod = "helloError")
    public String hello(){
        String str = "端口8082正在被调用:";
        return str+restTemplate.getForObject("http://SERVER-PROVIDER/hello",String.class);
    }

    public String helloError(){
        return "抱歉,服务出错!";
    }
}

  • 正常结果
端口8082正在被调用:hello
  • 熔断结果
抱歉,服务出错

4. Feign项目

  • Feign自带Hystrix,D版本后默认为关闭,需要手动开启
feign:
  hystrix:
    enabled: true

  • 修改Client
@FeignClient(value = "SERVER-PROVIDER",fallback = HelloError.class)
public interface HelloClient {

    @GetMapping("hello")
    String hello();
}
@Component
public class HelloError implements HelloClient{

    public String hello(){
        return "抱歉,服务故障!";
    }
}

  • 正常结果
8083端口正在被调用:hello
  • 熔断结果
8083端口正在被调用:抱歉,服务故障!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值