SpringCloud学习(十三):Hystrix的服务降级实现

简介: SpringCloud学习(十三):Hystrix的服务降级实现

1、订单侧使用fallback


     

在cloud-provider-payment8001中完成


(1)为paymentInfo_TimeOut写一个降级的服务

             

当我们当前的方法不能正常运行时,需要有一个方法来为他兜底


public String paymentInfo_TimeOutHandler(Integer id) {
        return "线程池:  "+Thread.currentThread().getName()+"  8001系统繁忙或者运行报错,请稍后再试,id:  "+id+"\t"+"o(╥﹏╥)o";
    }


(2)开启和激活服务降级

       

为paymentInfo_TimeOut加上@HystrixCommand注解,并在主启动类上添加@EnableCircuitBreaker注解


@HystrixCommand(fallbackMethod = "paymentInfo_TimeOutHandler",commandProperties = {
            @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="3000")
    })
    public String paymentInfo_TimeOut(Integer id) {
        int timeNumber = 5;
//        int age = 10/0;
        try {
            TimeUnit.SECONDS.sleep(timeNumber);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "线程池:  "+Thread.currentThread().getName()+" id:  "+id+"\t"+"O(∩_∩)O哈哈~"+"  耗时(秒): "+timeNumber;
    }
    public String paymentInfo_TimeOutHandler(Integer id) {
        return "线程池:  "+Thread.currentThread().getName()+"  8001系统繁忙或者运行报错,请稍后再试,id:  "+id+"\t"+"o(╥﹏╥)o";
    }


bdd5b7b3b3e346a692ae45faab16d331.png


(3)运行测试

             

1.测试超时

     

在浏览器地址栏输入

     

http://localhost:8001/payment/hystrix/timeout/1

016af9c2e3e54394a6a8ac7a7c1d77cf.png


2.测试异常

     

将代码中睡眠5秒的代码注释掉,将模拟异常的 int age = 10/0; 注释打开,重启测试

fe097b6ee87f4bd4a69ef07f389de68f.png


2、服务侧使用fallback



这里涉及到一个重要的常识:Hystrix不仅能放在消费侧,也能放在服务侧。


(1)yml


1. feign:
2.   hystrix:
3.     enabled: true


2)在主启动类上加上@EnableHystrix注解


(3)逻辑代码

       

与上面订单侧一致


(4)运行测试

     

启动7001、8001、80,在浏览器地址栏输入

     

http://localhost:90/consumer/payment/hystrix/timeout/1

ef3ceaaa185c44c2a9adaafad9028e4e.png


3、解决代码膨胀



使用DefaultProperties

       假如每个方法都需要一个兜底的降级方法,那一百个方法就需要一百个兜底,而这些兜底方法的代码逻辑往往大同小异,导致代码膨胀,于是我们可以写一个全局通用的降级方法。


(1)在类上加上注解@DefaultProperties


@DefaultProperties(defaultFallback = "payment_Global_FallbackMethod")


(2)暂时把fallbackMethod里的内容注释

     

因为就近原则,fallbackMethod里的内容会干扰我们的测试,但是不要注释掉@HystrixCommand了。

e807d20ff8d84a4189a06b172c1c4a6c.png


@RestController
@Slf4j
@DefaultProperties(defaultFallback = "payment_Global_FallbackMethod")
public class OrderHystrixController {
    @Autowired
    private PaymentHystrixService paymentHystrixService;
    @GetMapping("/consumer/payment/hystrix/ok/{id}")
    public String paymentInfo_OK(@PathVariable("id") Integer id) {
        String result = paymentHystrixService.paymentInfo_OK(id);
        log.info("===========result:" + result);
        return result;
    }
    @GetMapping("/consumer/payment/hystrix/timeout/{id}")
    @HystrixCommand
//            (fallbackMethod = "paymentInfo_TimeOutHandler",commandProperties = {
//            @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="1500")
//    })
    public String paymentInfo_TimeOut(@PathVariable("id") Integer id) {
//        int i = 10/0;
        String result = paymentHystrixService.paymentInfo_TimeOut(id);
        log.info("===========result:" + result);
        return result;
    }
    public String paymentInfo_TimeOutHandler(Integer id) {
        return "线程池:  "+Thread.currentThread().getName()+"  8001系统繁忙或者运行报错,请稍后再试,id:  "+id+"\t"+"o(╥﹏╥)o";
    }
    // 全局fallback方法
    public String payment_Global_FallbackMethod()
    {
        return "Global异常处理信息,请稍后再试,/(ㄒoㄒ)/~~";
    }
}


(3)运行测试


6dd0f61206bc4c2a86401c29f813b041.png


4、实现解耦



       现在我们将fallback方法写在controller层上,那么有其他服务又要为每个服务配置fallback,并且与业务逻辑代码混在一起,耦合度高;并且在客户端去调用服务端时,若遇上服务端宕机,就不能实现服务降级。于是我们可以在80服务中单独写一个类继承service接口,来处理服务降级。


1、新建PaymentFallbackService类,实现80服务中的PaymentHystrixService接口


@Component
public class PaymentFallbackService implements PaymentHystrixService{
    @Override
    public String paymentInfo_OK(Integer id) {
        return "----------PaymentHystrixService`s fallback-----------------";
    }
    @Override
    public String paymentInfo_TimeOut(Integer id) {
        return "----------PaymentHystrixService`s fallback-----------------";
    }
}


2、 在service接口上标注

74713f1d836d49a081332d58c31db1b7.png


3、运行测试

       

将之前配置的全局fallback方法暂时注释掉,重新运行。


195637b048c0432481351b1c66bda1a1.png


目录
打赏
0
0
0
0
178
分享
相关文章
基于MicrometerTracing门面和Zipkin实现集成springcloud2023的服务追踪
Sleuth将会停止维护,Sleuth最新版本也只支持springboot2。作为替代可以使用MicrometerTracing在微服务中作为服务追踪的工具。
254 1
SpringCloud2023实战之接口服务测试工具SpringBootTest
SpringBootTest同时集成了JUnit Jupiter、AssertJ、Hamcrest测试辅助库,使得更容易编写但愿测试代码。
119 3
SpringCloud基础9——服务异步通信-高级篇
消息可靠性、死信交换机、惰性队列、MQ集群
SpringCloud基础9——服务异步通信-高级篇
Spring Cloud全解析:熔断之Hystrix简介
Hystrix 是由 Netflix 开源的延迟和容错库,用于提高分布式系统的弹性。它通过断路器模式、资源隔离、服务降级及限流等机制防止服务雪崩。Hystrix 基于命令模式,通过 `HystrixCommand` 封装对外部依赖的调用逻辑。断路器能在依赖服务故障时快速返回备选响应,避免长时间等待。此外,Hystrix 还提供了监控功能,能够实时监控运行指标和配置变化。依赖管理方面,可通过 `@EnableHystrix` 启用 Hystrix 支持,并配置全局或局部的降级策略。结合 Feign 可实现客户端的服务降级。
360 23
故障隔离与容错处理:Hystrix在Spring Cloud和Netflix OSS中的应用
故障隔离与容错处理:Hystrix在Spring Cloud和Netflix OSS中的应用
94 3
微服务魔法启动!Spring Cloud与Netflix OSS联手,零基础也能创造服务奇迹!
这段内容介绍了如何使用Spring Cloud和Netflix OSS构建微服务架构。首先,基于Spring Boot创建项目并添加Spring Cloud依赖项。接着配置Eureka服务器实现服务发现,然后创建REST控制器作为API入口。为提高服务稳定性,利用Hystrix实现断路器模式。最后,在启动类中启用Eureka客户端功能。此外,还可集成其他Netflix OSS组件以增强系统功能。通过这些步骤,开发者可以更高效地构建稳定且可扩展的微服务系统。
106 1
【Azure Spring Cloud】Azure Spring Cloud服务,如何获取应用程序日志文件呢?
【Azure Spring Cloud】Azure Spring Cloud服务,如何获取应用程序日志文件呢?
【Azure 服务总线】Spring Cloud 的应用 使用Service Bus 引起 org.springframework.beans.BeanInstantiationException 异常,无法启动
【Azure 服务总线】Spring Cloud 的应用 使用Service Bus 引起 org.springframework.beans.BeanInstantiationException 异常,无法启动
SpringCloud:服务保护和分布式事务详解
SpringCloud:服务保护和分布式事务详解
160 0
SpringCloud基于Eureka的服务治理架构搭建与测试:从服务提供者到消费者的完整流程
Spring Cloud微服务框架中的Eureka是一个用于服务发现和注册的基础组件,它基于RESTful风格,为微服务架构提供了关键的服务注册与发现功能。以下是对Eureka的详细解析和搭建举例。
123 0