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

最近在学习 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

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

阅读 1.7k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进