谢谢rostlvan!
我在下面概述了我的实现:
我使用的是 Spring Cloud 版本 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>
虽然我不确定我们是否需要同时拥有 openfeign 和 hystrix 依赖项。有人可以验证!
在我的application.properties 我有feign.circuitbreaker.enabled=true
在我的主应用程序类中,我有
@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的答案