随笔 - 657,  文章 - 0,  评论 - 116,  阅读 - 153万

场景

SpringCloud中集成Hystrix实现服务降级(从实例入手):

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/124948025

上面在进行降级配置的fallback时是通过如下方式配置

复制代码
    @GetMapping("/consumer/payment/hystrix/timeout/{id}")
    @HystrixCommand(fallbackMethod = "paymentInfo_TimeOutHandler",commandProperties = { @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="2000")
    })
    public String paymentInfo_TimeOut(Integer id)
    {
        //int age = 10/0;
        String result = paymentHystrixService.paymentInfo_TimeOut(id);
        return result;
    }
    public String paymentInfo_TimeOutHandler(Integer id)
    {
        return "线程池:  "+Thread.currentThread().getName()+"来自消费者88的提示:服务提供者繁忙或者运行报错,请稍后再试,id:  "+id+"\t"+"o(╥﹏╥)o";
    }
复制代码

但是这样就需要在每个方法中重复添加注解并配置fallback方法。

有没有可以通配的方式进行配置fallback。

注:

博客:
https://blog.csdn.net/badao_liumang_qizhi
关注公众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。

实现

1、首先确保yml中如下配置已经打开

feign:
  hystrix:
    enabled: true

2、然后新建一个类实现上面的Service接口,统一为接口里面的方法进行异常处理

复制代码
package com.badao.springclouddemo.service;

import org.springframework.stereotype.Component;


@Component
public class PaymentFallbackService implements PaymentHystrixService
{
    @Override
    public String paymentInfo_OK(Integer id)
    {
        return "-----PaymentFallbackService fall back-paymentInfo_OK ,o(╥﹏╥)o";
    }

    @Override
    public String paymentInfo_TimeOut(Integer id)
    {
        return "-----PaymentFallbackService fall back-paymentInfo_TimeOut ,o(╥﹏╥)o";
    }
}
复制代码

3、给service接口中@FeignClinet注解中配置fallback属性为上面的实现类

复制代码
package com.badao.springclouddemo.service;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@Component
@FeignClient(value = "CLOUD-PROVIDER-HYSTRIX-PAYMENT",fallback = PaymentFallbackService.class)
public interface PaymentHystrixService
{
    @GetMapping("/payment/hystrix/ok/{id}")
    public String paymentInfo_OK(@PathVariable("id") Integer id);

    @GetMapping("/payment/hystrix/timeout/{id}")
    public String paymentInfo_TimeOut(@PathVariable("id") Integer id);


}
复制代码

4、此时依次启动Eureka Server 7001,以及服务提供者8001和服务消费者88

正常访问服务确保没问题

 

 

然后将8001关掉,模拟宕机的情况,此时服务消费者中调用对应的服务则会进入对应的实现中的返回。

 

 

posted on   霸道流氓  阅读(92)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示