一、在Fegion的Hystrix支持中,我们通过在@FeignClient(fallback = HystrixClientFallback.class),当服务提供者出现异常的时候,使用Hystrix回调方法。但是我们却无法看到具体的异常是什么。那么怎么解决这个问题呢,我们可以听通过配置fallbackFactory方法来配置,举个例子
一、我们先启动eureka
二、新建一个spring boot 项目,加入如下配置
application.yml
server:
port: 8010
spring:
application:
# 指定注册到eureka server上的服务名称
name: microservice-consumer-movie
eureka:
client:
service-url:
# 指定eureka server通信地址,注意/eureka/小尾巴不能少
defaultZone: http://user:password123@localhost:8761/eureka
instance:
# 是否注册IP到eureka server,如不指定或设为false,那就会注册主机名到eureka server
prefer-ip-address: true
feign:
hystrix:
enabled: true
MovieController.java
@RequestMapping("/movies")
@RestController
public class MovieController {
@Autowired
private UserFeignClient userFeignClient;
@GetMapping("/users/{id}")
public User findById(@PathVariable Long id) {
return this.userFeignClient.findById(id);
}
}
UserFeignClient.java
@FeignClient(name = "microservice-provider-user", fallbackFactory = UserFeignClientFallbackFactory.class)
public interface UserFeignClient {
@GetMapping("/users/{id}")
User findById(@PathVariable("id") Long id);
}
@Component
@Slf4j
class UserFeignClientFallbackFactory implements FallbackFactory<UserFeignClient> {
@Override
public UserFeignClient create(Throwable throwable) {
return new UserFeignClient() {
@Override
public User findById(Long id) {
log.error("进入回退逻辑", throwable);
return new User(id, "默认用户", "默认用户", 0, new BigDecimal(1));
}
};
}
}
代码已经标注了回退逻辑的throwable