【问题标题】:Spring Cloud Hystrix : FallbackMethod not invokedSpring Cloud Hystrix:未调用 FallbackMethod
【发布时间】:2018-07-18 00:45:47
【问题描述】:

我在玩 Spring Cloud Hystrix 时遇到了一个奇怪的错误,即我的 Fallback 方法没有被调用。我的控制器在下面。

@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";
    }

}

如您所见,我正确设置了 fallbackMethod,但是,当我运行服务器并将浏览器指向终点时,我收到一个异常,说我的服务器已关闭,因为我了解我的服务何时关闭应该调用fallbackMethod,但在我的情况下不是这样,我的fallbackMethod基本上没有被调用。

java.lang.IllegalStateException: 没有可用于 busfare-service 的实例

我的代码中缺少某些内容?

【问题讨论】:

    标签: java spring spring-cloud hystrix


    【解决方案1】:

    看起来我喜欢,Hystrix 通过errorHandling 处理这个fallbackMethod。导致我的后备没有被调用的代码搞砸了是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";
    }
    

    使用上面的代码,fallbackMethod 现在可以工作了。

    【讨论】:

      猜你喜欢
      • 2018-09-30
      • 2016-06-18
      • 2017-10-19
      • 2017-06-18
      • 2016-03-31
      • 2015-05-31
      • 2018-07-21
      • 2016-12-08
      • 2018-10-05
      相关资源
      最近更新 更多