SpringCloud(四):服务熔断保护-Hystrix【Finchley版】
发布日期:2021-09-18 10:05:49 浏览次数:13 分类:技术文章

本文共 2374 字,大约阅读时间需要 7 分钟。

SpringCloud(四):服务熔断保护-Hystrix【Finchley版】

上几篇文章我们一起学习了服务的注册与调用,这一篇我们一起来了解一下服务的熔断保护,现在业界用的比较多的应该是 Hystrix ,随着hystrix的闭源,使用Resilience4j的用户也在增加,今天我们就先来聊聊用hystrix进行服务熔断保护。

为什么需要服务熔断保护?

在微服务架构中,我们将一个大的业务系统拆解成各种小的服务并且集群化部署,服务与服务之间通过RPC来进行调用,如果某个服务出现问题,导致线程阻塞了,外部进入大量请求,服务资源会在短时间内进行消耗,从而导致整个系统不可用,这就会出现一个雪崩效应,为了解决这个问题,我们就需要对服务进行熔断保护。

在 SpringCloud 中调用方式有 Ribbon+RestTemplate 和 Feign 两种方式,所以我们分别来看看这两种方式是如何用 Hystrix 来进行服务熔断的?

Ribbon+RestTemplate 结合 Hystrix 服务熔断

我们对ribbon-customer-server进行改造

1、pom.xml

在 pom.xml 中引入 Hystrix 依赖

org.springframework.cloud
spring-cloud-starter-netflix-hystrix

2、引导类

在引导类上添加@EnableCircuitBreaker或者@EnableHystrix注解,来开启 Hystrix

@SpringBootApplication@EnableDiscoveryClient//@EnableHystrix@EnableCircuitBreakerpublic class RibbonCustomerServerApplication {
public static void main(String[] args) {
SpringApplication.run(RibbonCustomerServerApplication.class, args); } @Bean @LoadBalanced RestTemplate restTemplate(){
return new RestTemplate(); }}

3、Service 类

service类的hello方法上添加@HystrixCommand注解并且指定fallbackMethod ="helloError",我们在helloError方法里编写默认返回数据

@HystrixCommand(fallbackMethod = "helloError") public String hello(){
return restTemplate.getForObject("http://hello-provider-service/hello",String.class); } public String helloError(){
return "服务器繁忙,请稍后再试!"; }

我们先不启动hello-provider-server服务,直接启动ribbon-customer-server,在浏览器里访问http://127.0.0.1:8087/hello,我们将看到返回的为:

服务器繁忙,请稍后再试!

我们启动hello-provider-server服务,再次多次访问http://127.0.0.1:8087/hello,我们就会看到:

hello spring cloud ,i am port :8085

Feign 结合 Hystrix 服务熔断

Feign 已经结合了 Hystrix,所以我们不需要额外引入配置,我们对feign-customer-service项目进行改造,我们只要要编写一个HelloService接口的实现类,提供一些默认返回值就可以,并且在@FeignClient上配置fallback

Service 改造

修改HelloService接口,在@FeignClient上添加fallback参数

@FeignClient(value = "hello-provider-service",fallback = HelloHystrix.class)public interface HelloService {
@GetMapping(path = "/hello") String hello();}

编写HelloHystrix

@Componentpublic class HelloHystrix implements HelloService {
@Override public String hello() {
return "系统繁忙,请稍后再试!!!"; }}

启动feign-customer-service服务,访问http://127.0.0.1:8088/hello,能够正常访问得到

hello spring cloud ,i am port :8085

关闭hello-provider-server服务,再次访问http://127.0.0.1:8088/hello,浏览器显示

系统繁忙,请稍后再试!!!

本文demo下载 :

在这里插入图片描述

扫码关注公众号(搜索公众号:平头哥的技术博文)一起交流学习呗

转载地址:https://blog.csdn.net/z694644032/article/details/96875730 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:SpringCloud (五) :Nacos 服务配置中心【Finchley版】
下一篇:SpringCloud(三):@EnableDiscoveryClient 注解如何实现服务注册与发现

发表评论

最新留言

能坚持,总会有不一样的收获!
[***.219.124.196]2024年04月21日 02时33分32秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章