springcloud 实现fegin接口,无法对异常进行服务降级

发布于 2022-09-12 23:48:27 字数 2198 浏览 36 评论 0

最近在学习 hystrix , 和 openfeign 联合使用实现对服务的降级

出现问题:当控制器发生异常时,无法对其进行处理直接抛出异常

测试代码

feign 接口

package com.example.servicer;

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;
import com.example.servicer.impl.PaymentHystrixServcieImpl;


//fallback = PaymentHystrixServcieImpl.class

@Component
@FeignClient(value = "CLOUD-PROVIDER-HYSTRIX-PAYMENT" )   //使用微服务名称的方式访问;
public interface PaymentHystrixServcie {
    @GetMapping("/payment/get/{id}")
    public String PaymentInfo_ok(@PathVariable("id") Integer id);

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

}

实现fenign 接口并将其注入spring容器

package com.example.servicer;

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;
import com.example.servicer.impl.PaymentHystrixServcieImpl;

@Component
@FeignClient(value = "CLOUD-PROVIDER-HYSTRIX-PAYMENT" , fallback =PaymentHystrixServcieImpl.class )   //使用微服务名称的方式访问;
public interface PaymentHystrixServcie {
    @GetMapping("/payment/get/{id}")
    public String PaymentInfo_ok(@PathVariable("id") Integer id);

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

}

在控制器中制造异常

    @GetMapping(value = "/consumer/payment/timeout/get/{id}")
    public String Timeout(@PathVariable("id") Integer id){
        int age=10/0;
        String result=paymentHystrixServcie.PaymentInfo_Timeout(id);
        return  result;
    }

结果
image.png

还有一个问题,这种实现方式我该如何对一些方法设置不同的超时间时间?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文