2、记Hystrix熔断 @HystrixCommand 注解失效问题
HystrixCommand注解失效可能是由于@EnableHystrix注解也失效导致的。在4.x版本之后,Hystrix可能无效,因为无法扫描到Hystrix的配置。这可能是导致HystrixCommand注解无效的原因之一。
版本说明:
- Spring Boot:3.0.9 Spring Boot:3.2.0
- Spring Cloud:2022.0.4 Spring Cloud:2023.0.0
- jdk:20 jdk:20
我这边的userService服务已停,为了测试Hystrix是否生效。
报错信息:
2024-01-10T21:40:01.890+08:00 ERROR 1796 --- [nio-8081-exec-1] o.a.c.c.C.[.[.[.[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [/borrow] threw exception [Request processing failed: feign.FeignException$ServiceUnavailable: [503] during [GET] to [http://userService/user/getUser/1] [UserClient#getUserByUserId(int)]: [Load balancer does not contain an instance for the service userService]] with root cause
feign.FeignException$ServiceUnavailable: [503] during [GET] to [http://userService/user/getUser/1] [UserClient#getUserByUserId(int)]: [Load balancer does not contain an instance for the service userService]
at feign.FeignException.serverErrorStatus(FeignException.java:265) ~[feign-core-12.4.jar:na]
at feign.FeignException.errorStatus(FeignException.java:206) ~[feign-core-12.4.jar:na]
at feign.FeignException.errorStatus(FeignException.java:194) ~[feign-core-12.4.jar:na]
at feign.codec.ErrorDecoder$Default.decode(ErrorDecoder.java:104) ~[feign-core-12.4.jar:na]
at feign.ResponseHandler.decodeError(ResponseHandler.java:136) ~[feign-core-12.4.jar:na]
at feign.ResponseHandler.handleResponse(ResponseHandler.java:70) ~[feign-core-12.4.jar:na]
at feign.SynchronousMethodHandler.executeAndDecode(SynchronousMethodHandler.java:114) ~[feign-core-12.4.jar:na]
Controller 层代码:
@RestController
public class BorrowController {
@Resource(name = "borrowService")
BorrowService borrowService;
@HystrixCommand(fallbackMethod = "getUserBorrowsFallback")
@GetMapping(value = "/getBorrows/{user_id}")
public UserBorrowDetail getUserBorrows(@PathVariable("user_id")int user_id){
return borrowService.getUserBorrowDetailByUserId(user_id);
}
// 备选方案,这里直接返回空列表
// 注意参数和返回值要和上面的一致
public UserBorrowDetail getUserBorrowsFallback(int user_id){
return new UserBorrowDetail(null, Collections.emptyList());
}
}
启动类:
@SpringBootApplication
@EnableFeignClients // Feign实现负载均衡
@EnableHystrix // 启用Hystrix
public class BorrowApplication {
public static void main(String[] args) {
SpringApplication.run(BorrowApplication.class,args);
}
}
解决办法:定义一个配置类,让相关缺少的配置生效
@Configuration
public class MyHystrixConfig {
/**
* 用来拦截处理HystrixCommand注解
* @return
*/
@Bean
public HystrixCommandAspect hystrixCommandAspect() {
return new HystrixCommandAspect();
}
}
具体文章参考大佬所著:链接: https://blog.csdn.net/Jason_2020/article/details/130110355