不调用 Hystrix 回退方法
Hystrix fallback method is not invoked
我正在尝试 hystrix 后备方法。
在 localhost:8082,客户服务是 运行 客户的 returns 姓名。
如果客户服务出现故障,应调用回退方法。但这并没有发生。
下面是代码片段。
请推荐。
@SpringBootApplication
@EnableDiscoveryClient
@EnableCircuitBreaker
@RestController
public class DemoHystrixApplication {
@GetMapping("/")
public String name() {
String str = getCustomerName();
return str;
}
@HystrixCommand(fallbackMethod = "getFallbackCustomerName")
private String getCustomerName() {
RestTemplate restTemplate = new RestTemplate();
URI uri = URI.create("http://localhost:8082");
return restTemplate.getForObject(uri, String.class);
}
private String getFallbackCustomerName() {
System.out.println("coming inside fallback method");
return "Resillient Customer";
}
public static void main(String[] args) {
SpringApplication.run(DemoHystrixApplication.class, args);
}
}
您的@HystrixCommand 注释方法应该是public。
不确定后备方法,但我也会将其设置为 public。
这两种方法,即实际方法和后备方法都应该是 public 并将这些方法移动到单独的 class 并使用 @Component.
对其进行注释
试一试,希望对您有所帮助。
这是因为AOP。
Spring 容器在注入 bean 时注入 aspect-aware bean。
当根据用户请求调用 name()
函数时,会调用 aspect-aware bean 的方法,因此注释起作用。
但是,直接在 name()
中调用 this.getCustomerName()
会在原始 bean 包装在代理中之前调用 getCustomerName()
。它不知道方面。因此,注释不起作用。
如果您添加了 netflix-hystrix 的依赖项并且有开发工具在执行服务时获取更改,您也可以尝试停止和启动服务。
应从另一个 bean 调用回退方法。问题是您正在从 RestController 调用回退方法。
我正在尝试 hystrix 后备方法。 在 localhost:8082,客户服务是 运行 客户的 returns 姓名。
如果客户服务出现故障,应调用回退方法。但这并没有发生。
下面是代码片段。
请推荐。
@SpringBootApplication
@EnableDiscoveryClient
@EnableCircuitBreaker
@RestController
public class DemoHystrixApplication {
@GetMapping("/")
public String name() {
String str = getCustomerName();
return str;
}
@HystrixCommand(fallbackMethod = "getFallbackCustomerName")
private String getCustomerName() {
RestTemplate restTemplate = new RestTemplate();
URI uri = URI.create("http://localhost:8082");
return restTemplate.getForObject(uri, String.class);
}
private String getFallbackCustomerName() {
System.out.println("coming inside fallback method");
return "Resillient Customer";
}
public static void main(String[] args) {
SpringApplication.run(DemoHystrixApplication.class, args);
}
}
您的@HystrixCommand 注释方法应该是public。 不确定后备方法,但我也会将其设置为 public。
这两种方法,即实际方法和后备方法都应该是 public 并将这些方法移动到单独的 class 并使用 @Component.
对其进行注释试一试,希望对您有所帮助。
这是因为AOP。
Spring 容器在注入 bean 时注入 aspect-aware bean。
当根据用户请求调用 name()
函数时,会调用 aspect-aware bean 的方法,因此注释起作用。
但是,直接在 name()
中调用 this.getCustomerName()
会在原始 bean 包装在代理中之前调用 getCustomerName()
。它不知道方面。因此,注释不起作用。
如果您添加了 netflix-hystrix 的依赖项并且有开发工具在执行服务时获取更改,您也可以尝试停止和启动服务。
应从另一个 bean 调用回退方法。问题是您正在从 RestController 调用回退方法。