使用通过Eureka / Ribbon感知的RestTemplate进行配置时,不会调用@HystrixCommand
指定的后备方法。
pom.xml
....
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
....
@SpringBootApplication
配置@SpringBootApplication
@EnableDiscoveryClient
@EnableCircuitBreaker
@EnableHystrix
public class FileUploadServiceApplication {
...
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
...
}
@Component
@RefreshScope
public class FileUploadServiceImpl implements FileUploadService {
....
@HystrixCommand(fallbackMethod = "fallbackToMessageQ")
private void notifyComplete(String fileName) {
this.restTemplate.exchange(
"http://DISCOVERY-CLIENT/api/file/process?filename="+fileName, ....)
....
}
private void fallbackToMessageQ(String fileName, Throwable t) {
System.out.println("notify threw exception, "+t.getMessage());
rabbitTemplate.convertAndSend(uploadCompleteExchangeName, "", fileName.getBytes());
}
}
当执行时,它因无法访问
DISCOVERY-CLIENT
且永远不会访问fallback方法而抛出IllegalStateException后结束,请告知是否需要配置其他内容。java.lang.IllegalStateException: No instances available for DISCOVERY-CLIENT
at org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient.execute(RibbonLoadBalancerClient.java:90)
at org.springframework.cloud.client.loadbalancer.RetryLoadBalancerInterceptor$1.doWithRetry(RetryLoadBalancerInterceptor.java:88)
at org.springframework.cloud.client.loadbalancer.RetryLoadBalancerInterceptor$1.doWithRetry(RetryLoadBalancerInterceptor.java:76)
at org.springframework.retry.support.RetryTemplate.doExecute(RetryTemplate.java:286)
at org.springframework.retry.support.RetryTemplate.execute(RetryTemplate.java:163)
最佳答案
@HystrixCommand
与AOP切入点一起使用,您的方法是private
。将其可见性更改为公开。