简体   繁体   English

Spring Cloud Hystrix:未调用FallbackMethod

[英]Spring Cloud Hystrix : FallbackMethod not invoked

I am playing around Spring Cloud Hystrix and I got this weird error that my Fallback method is not being invoked. 我在Spring Cloud Hystrix周围玩耍,但遇到了一个奇怪的错误,即我的Fallback方法没有被调用。 My Controller is below . 我的控制器在下面。

@Controller
public class DashboardController {

    @LoadBalanced
    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder){
        return builder.build();
    }

    @Autowired
    private RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "getFareBackup")
    @RequestMapping("/dashboard")
    public String getFareDashboard(Model m) {
        try {
            ResponseEntity<List<BusFare>> responseEntity = restTemplate.exchange("http://busfare-service/api/v1/fare/",
                    HttpMethod.GET, null, new ParameterizedTypeReference<List<BusFare>>() {
                    });
            m.addAttribute("fareList", responseEntity.getBody());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "dashboard";
    }


    public String getFareBackup(Model m){
        System.out.println("Fallback operation called");

        m.addAttribute("fareList", new ArrayList<BusFare>().add(new BusFare(1, BigDecimal.valueOf(0.7), "Regular")));
        return "dashboard";
    }

}

As you can see, I set the fallbackMethod properly, however, when I run the server and point my browser to the end point, I get an exception saying that my server is down, as I understand when my service is down it should invoke the fallbackMethod, but it in my case that is not the case, my fallbackMethod is basically not being invoked. 如您所见,我正确设置了fallbackMethod,但是,当我运行服务器并将浏览器指向端点时,出现了一个异常,说我的服务器已关闭,因为我了解到我的服务在关闭时应该调用fallbackMethod,但就我而言并非如此,我的fallbackMethod基本上没有被调用。

java.lang.IllegalStateException: No instances available for busfare-service java.lang.IllegalStateException:没有实例可用于公交服务

I am missing something in my code? 我的代码中缺少什么?

It seems my like, Hystrix handles this fallbackMethod thru errorHandling. 好像我喜欢,Hystrix通过errorHandling处理这个fallbackMethod。 What messed up my code that caused my fallback not being invoked is the errorHandling. 错误处理导致我的代码混乱,从而导致无法调用我的后备广告。

@HystrixCommand(fallbackMethod = "getFareBackup")
@RequestMapping("/dashboard")
public String getFareDashboard(Model m) {

    ResponseEntity<List<BusFare>> responseEntity = restTemplate.exchange("http://busfare-service/api/v1/fare/",
                HttpMethod.GET, null, new ParameterizedTypeReference<List<BusFare>>() {
                });

    m.addAttribute("fareList", responseEntity.getBody());

    return "dashboard";
}

With the code above, the fallbackMethod is now working. 使用上面的代码,fallbackMethod现在可以正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM