我正在为 Spring Boot 项目使用 Hystrix 库 (spring-cloud-starter-hystrix
)。我有一个用 @HystrixCommand
注释的 @Service
类,它按预期工作。
但是,当我在同一个服务类中添加用 @Async
注释的方法时,Hystrix 不起作用,并且永远不会调用回退方法。什么可能导致此问题以及如何解决?
这是 Application
类:
@EnableCircuitBreaker
@EnableHystrixDashboard
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
这是服务类:
@Service
public class TemplateService {
@HystrixCommand(
fallbackMethod = "getGreetingFallback",
commandProperties = {@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1500")}
)
public String getGreeting() {
URI uri = URI.create("http://localhost:8090/greeting");
ResponseEntity<String> response = restTemplate.exchange(uri, HttpMethod.GET, null, String.class);
if (response.getStatusCode().equals(HttpStatus.OK)) {
return response.getBody();
} else {
return null;
}
}
public String getGreetingFallback(Throwable e) {
return null;
}
@Async
public void async(String message) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
logger.info(MessageFormat.format("Received async message {0}", message));
}
}
@EnableAsync
注释放置在另一个用 @Configuration
注释的类中,我在其中设置属性文件中的一些其他 Thread Executor 选项。
最佳答案
给定 TemplateService
的代码(未实现接口(interface))并假设默认值在 @EnableAsync
上可以肯定的是,CGLIB 代理是由 spring 创建的。
因此 getGreeting()
上的 @HystrixCommand
注解不是由服务代理类继承;这解释了报告的行为。
要克服此错误,请将 @HystrixCommand
和 @Async
方法分开放在不同的服务中,因为启用 JDK 代理也无济于事,而且我不确定 AspectJ 模式.
引用this有关 Spring 代理机制的更多信息。
关于spring - Hystrix 和 Spring @Async 组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42810424/