Feign Hystrix 回退不起作用

Feign Hystrix fallback not working

我有以下FeignClient:

@FeignClient(name="FooMS",fallback=CustomerFeign.CustomerFeignImpl.class)
public interface CustomerFeign {

    @RequestMapping(value="/bar/{phoneNo}")
    List<Long> getFriends(@PathVariable("phoneNo") Long phoneNo);


    class CustomerFeignImpl implements CustomerFeign{

        @Override
        public List<Long> getFriends(Long phoneNo) {
            return new ArrayList<Long>(108);
        }

    }

}

当 FooMS 实例关闭时,我收到 500 错误而不是正在执行回退。为什么会这样?

将您的 CustomerFeignImpl 标记为 @Component 或从中创建一个 @Bean

添加 @Component 和 feign.hystrix.enabled=true 效果很好

这适用于我 2020.0.3:

application.properties

feign.circuitbreaker.enabled=true

pom.xml

 <spring-cloud.version>2020.0.3</spring-cloud.version>

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
    <version>2.2.9.RELEASE</version>
</dependency>

谢谢,rostlvan

我在下面概述了我的实现:

我正在使用 Spring 云版本 2020.0.4,以下配置对我有用:

pom.xml 中,我有这些依赖项:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
    <version>2.2.9.RELEASE</version>
</dependency>

虽然我不确定我们是否需要同时拥有 openfeignhystrix 依赖项。有人可以验证这一点!

在我的 application.properties 我有 feign.circuitbreaker.enabled=true

在我的主应用程序 class 中,我有

@SpringBootApplication
@EnableFeignClients
public class MySpringBootApplication{

   public static void main(String[] args) {
       SpringApplication.run(MySpringBootApplication.class, args);
   }

 }

最后,我的 Feign 客户端、后备和后备工厂:

UserServiceFeignClient.java

@FeignClient(name = "USER-SERVICE", fallbackFactory = UserServiceFallbackFactory.class)
public interface UserServiceFeignClient {
    
    @GetMapping("/api/users/{userId}")
    public ResponseEntity<User> getUser(@PathVariable String userId);
}   

UserServiceFeignClientFallback.java

public class UserServiceFeignClientFallback implements UserServiceFeignClient{
    
    @Override
    public ResponseEntity<User> getUser(String userId) {
        return ResponseEntity.ok().body(new User());
    }
}

并且,UserServiceFeignClientFallbackFactory.java

@Component
public class UserServiceFallbackFactory implements FallbackFactory<UserServiceFeignClientFallback>{

    @Override
    public UserServiceFeignClientFallback create(Throwable cause) {
        return new UserServiceFeignClientFallback();
    }
    
}

我自己也遇到了这个问题,直到我偶然发现了 @rostlvan

的答案