Hystrix实现熔断机制

前言

当服务规模足够大的时候,会出现多个服务之间调用的情况
这样会产生一种问题,即某个服务不可用的时候,调用方线程就会阻塞在这个不可用的服务上,不断的重试
断路器就像一把刀子,可以割断一颗树上坏掉的分支,起到断路的作用
Hystrix就是干这件事情的

一、Hystrix基于Ribbon实战

step1
在前面章节的Ribbon项目中引入hystrix依赖

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>

step2
主类开启hystrix

@EnableHystrix
@EnableEurekaClient
@SpringBootApplication
public class RibbonApplication {

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

step3
服务类配置服务不可用的时候的备选方法

@Service
public class RibbonService {
    @Autowired
    private RestTemplate restTemplate;
    @HystrixCommand(fallbackMethod = "helloFallBack")
    public String ribbonService(String name) {
        return restTemplate.getForObject("http://SERVICE-HI/hi", String.class);
    }
    public String helloFallBack(String name) {
        return name + "服务坏掉了,熔断 !";
    }
}

step4
启动eureka server,service-hi,启动ribbon

12062369-ee5cdc920c665ab2.png

step5
访问controller中配置的url,http://desktop-sk5pqmq:8787/ribbon-consumer?name=huo,然后断开service-hi之后再次访问,可以看到备用方法起作用了,即熔断机制起作用了

12062369-d7e1c13de0cdfec2.png
image.png

二、Hystrix基于Feign实战

step1
Feign中默认集成了Hystrix,所以不需要引入hystrix依赖,但是要在yml文件中开启hystrix

eureka:
  client:
    serviceUrl:
      defaultZone: http://server1:20001/eureka/
server:
  port: 8766
spring:
  application:
    name: service-feign
feign:
  hystrix:
    enabled: true

step2
伪服务端接口的方法的注解上增加fallback

@FeignClient(value = "service-hi",fallback = ServiceFeignImpl.class)
public interface ServiceFeign {
    @RequestMapping(value = "/hi", method = RequestMethod.GET)
    String sayHi(@RequestParam(value = "name") String name);
}

step3
fallback指定的类是该服务接口的实现类,其中的方法也就是备用方法,值得注意的是子类需要注入进IOC

@Component
public class ServiceFeignImpl implements ServiceFeign {
    @Override
    public String sayHi(String name) {
        return "出错了兄弟!熔断";
    }
}

step4
重复上面ribbon的测试方法,发现结果一致,熔断成功!

总结

git地址:https://github.com/KouLouYiMaSi/springcloud

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值