用 @HystrixCommand
指定的回退方法使用 Eureka/Ribbon 感知 RestTemplate 配置时不会调用。
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
而引发 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)
。更改其对公众的可见性。
关于java - SpringBoot : @HystrixCommand not working,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42767461/