栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringCloud中集成Hystrix实现降级时通过FeignFallBack实现通配服务

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringCloud中集成Hystrix实现降级时通过FeignFallBack实现通配服务

场景

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

SpringCloud中集成Hystrix实现服务降级(从实例入手)_霸道流氓气质的博客-CSDN博客

上面在进行降级配置的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。

注:

博客:
霸道流氓气质的博客_CSDN博客-C#,架构之路,SpringBoot领域博主
关注公众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。

实现

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关掉,模拟宕机的情况,此时服务消费者中调用对应的服务则会进入对应的实现中的返回。

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/930026.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号