openfeign使用fallback指定降级方法无法执行问题

文章讲述了如何在SpringCloudFeign中使用FeignClient调用服务,并介绍了UserClient接口和其降级类UserClientFallback。重点强调了在消费方开启sentinel或Hystrix以实现服务降级,以及作者在排查问题过程中关于配置耗时的经历。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

直接点上代码:

package com.fuXiApi.api;

import com.common.util.MyResult;
import com.fuXiApi.api.fallback.UserClientFallback;
import com.fuXiApi.dto.UserDTO;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@FeignClient(name = "fuxi-user-server", fallback = UserClientFallback.class)
public interface UserClient {
    @GetMapping("/user/getUserById/{id}")
    MyResult<UserDTO> getUserById(@PathVariable("id") Integer id);
}

定义了以对外提供服务的接口,并且声明了降级类。

降级类:

package com.fuXiApi.api.fallback;

import com.common.util.MyResult;
import com.fuXiApi.api.UserClient;
import com.fuXiApi.dto.UserDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @program: springCloudeAlibabaFuXi
 * @author: quxiao
 * @create: 2024-03-19 21:09
 **/
@Component
@Slf4j
public class UserClientFallback implements UserClient {
    @Override
    public MyResult<UserDTO> getUserById(Integer id) {
        log.info("用户通过id获取方法降级方法");
        return MyResult.fail();
    }
}

但是一直无法走这里面的方法,直到我把以前的代码,一个服务一个服务的排除配置,这个配置耗时我今晚两小时:

feign:
  sentinel:
    enabled: true

 

一定要在消费方开启这个配置! 

或者这个:

feign:
  hystrix:
    enabled: true

选择其中一个在消费方开启!

### 实现OpenFeign中的Fallback机制 为了处理服务调用失败的情况,Spring Cloud提供了Hystrix作为断路器来增强系统的稳定性和弹性。当使用带有Hystrix支持的OpenFeign客户端时,可以通过定义一个实现了目标接口并标注了`@Component`的类来指定回退逻辑[^2]。 下面是一个简单的例子展示如何配置以及创建具有fallback功能的服务消费者: #### 定义Feign Client 接口 ```java import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; @FeignClient(name = "example-service", fallback = ExampleServiceFallback.class) public interface ExampleServiceApi { @GetMapping("/api/example") String getExample(); } ``` 在这个案例里,`name="example-service"`指定了要访问的服务名称;而`fallback=ExampleServiceFallback.class`则声明了一个具体的实现类用于提供备用响应方案。 #### 创建 Fallback 类 ```java import org.springframework.stereotype.Component; @Component public class ExampleServiceFallback implements ExampleServiceApi { @Override public String getExample() { return "Default response from fallback"; } } ``` 这里定义了一个名为 `ExampleServiceFallback` 的组件,它实现了之前提到过的API接口,并重写了其中的方法以给出默认的结果,在实际应用中可以根据需求自定义更复杂的错误恢复策略。 需要注意的是,为了让上述设置生效,还需要确保项目已经引入了必要的依赖项并且启用了相应的特性开关(例如通过application.properties文件)。此外,如果希望进一步定制化熔断行为,则可以考虑利用Hystrix命令属性来进行调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值