简体   繁体   English

如何使用 netflix hystrix 获取断路器状态的状态?

[英]How to get status for circuit breaker status with netflix hystrix?

This is my AppService Class, where I need to add logic for getting the status for the circuit breaker if it's open or closed but I am unable to find a way.这是我的 AppService 类,我需要添加逻辑来获取断路器打开或关闭的状态,但我找不到方法。 Also, i have made use of ignoreExceptions but seems like trouble is there.另外,我已经使用了 ignoreExceptions 但似乎有麻烦。 Just new to coding and this feature and unable to get an appropriate answer.刚刚接触编码和此功能,无法获得适当的答案。 I am not sure how to use isCircuitBreakerOpen().我不确定如何使用 isCircuitBreakerOpen()。

@Service
public class AppService {

    private static final Logger LOG = LoggerFactory.getLogger(AppService.class);
    private final RestTemplate restTemplate;

    public AppService(RestTemplate rest) {
        this.restTemplate = rest;
    }
    
    
    
    @HystrixCommand(fallbackMethod = "reliable", commandProperties= {
            @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_ERROR_THRESHOLD_PERCENTAGE, value = "100"),
            @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_SLEEP_WINDOW_IN_MILLISECONDS, value = "10000"),
            @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_REQUEST_VOLUME_THRESHOLD, value = "10")
            })
            public ResponseEntity<String> answerList() throws Exception {
                return callingDownStreamService404();
                }

    @HystrixCommand(fallbackMethod = "reliable", commandProperties= {
            @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_ERROR_THRESHOLD_PERCENTAGE, value = "100"),
            @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_SLEEP_WINDOW_IN_MILLISECONDS, value = "10000"),
            @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_REQUEST_VOLUME_THRESHOLD, value = "10")
        })
    public ResponseEntity<String> answerList503() throws Exception {
                return callingDownStreamService503();
                }
    
    
                private ResponseEntity<String> callingDownStreamService404() throws Exception {
                    URI uri = URI.create("http://localhost:8090/recommended/404");

                    RestTemplate restTemplate = new RestTemplate();
                    HttpHeaders headers = new HttpHeaders();
                    HttpEntity<Object> entity = new HttpEntity<Object>(headers);

                    ResponseEntity<String> out = restTemplate.exchange(uri, HttpMethod.GET, entity, String.class);
                    System.out.println("Application code : " + out.getStatusCode());
                    return out;

                }

                private ResponseEntity<String> callingDownStreamService503() throws Exception {
                    URI uri = URI.create("http://localhost:8090/recommended/503");

                    RestTemplate restTemplate = new RestTemplate();
                    HttpHeaders headers = new HttpHeaders();
                    HttpEntity<Object> entity = new HttpEntity<Object>(headers);

                    ResponseEntity<String> out = restTemplate.exchange(uri, HttpMethod.GET, entity, String.class);
                    System.out.println("Application code : " + out.getStatusCode());

                    if (out.getStatusCode().toString().startsWith("5")) {
                        throw new HystrixBadRequestException("bad request messageg");
                    }

                    return out;

                }

                @HystrixCommand(commandKey = "MyHystrixCommand",fallbackMethod = "myHystrixFallback", threadPoolKey = "ThreadPoolKey",commandProperties= {
                      @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_ERROR_THRESHOLD_PERCENTAGE, value = "100"),
                      @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_SLEEP_WINDOW_IN_MILLISECONDS, value = "10000"),
                      @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_REQUEST_VOLUME_THRESHOLD, value = "10")},
                    ignoreExceptions = {HttpServerErrorException.class, HystrixBadRequestException.class, HttpClientErrorException.class})
                
                public ResponseEntity<String> getServiceCallResponse(String serviceUrl, HttpEntity<?> entity) {
                     serviceUrl = "http://localhost:8090/recommended/500";
                    
                    ResponseEntity<String> resp = null;
                    
                    try {
                        System.out.println("Calling -----" + serviceUrl);
                        resp = restTemplate.exchange(serviceUrl, HttpMethod.POST, entity, String.class);
                        
                        }
                    catch(RestClientException e) {
                        System.out.println("Calling -----" + serviceUrl + "Exception is this" + e.getRootCause());
                        handleExceptionForHystrix("getServiceCallResponse", e);
                    }
                    return resp;
                    }

                    private void handleExceptionForHystrix(String function, Exception e) {
                            if (e instanceof HttpStatusCodeException) {
                                HttpStatus httpStatusCode = ((HttpStatusCodeException)e).getStatusCode();
                                if(httpStatusCode.equals(HttpStatus.BAD_REQUEST) || httpStatusCode.equals(HttpStatus.INTERNAL_SERVER_ERROR)) {
                                    throw new HystrixBadRequestException("Hystrix Bad Request Exception Occurred" + httpStatusCode, e);
                                }
                                throw new RuntimeException(function, e);
                            }
                            throw new RuntimeException(function, e);
                        }


                    public ResponseEntity<String> myHystrixFallback(String serviceUrl, HttpEntity<?> entity, Throwable hystrixCommandExp) {
                        
                                return new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR);
                            }
                
                @Recover()
                public ResponseEntity<String> reliable() {
                    return new ResponseEntity<String>(
                            "The downstream application is unavailable and the circuit is open", HttpStatus.OK);
                }
                
                
            }

this is the main class where i have placed the endpoints.这是我放置端点的主类。 I am also making use of AppStore which is the downstream app and same enpoints are configured there.我也在使用 AppStore,它是下游应用程序,并且在那里配置了相同的端点。

@EnableHystrixDashboard
@EnableCircuitBreaker
@RestController
@SpringBootApplication
public class DavinciCircuitbreakerApplication {
    
      @Autowired
      private AppService appService;
      
      @Bean
      public RestTemplate rest(RestTemplateBuilder builder) {
      return builder.build();
      }

          
      @RequestMapping("/to-answer/404")
      public ResponseEntity<String> toAnswer() {
          ResponseEntity<String> response = null;
        try{
            response = appService.answerList();
        }catch(Exception e){
            System.out.println("excpetion"+ e.getMessage());
            return new ResponseEntity<String>("failure", HttpStatus.valueOf(500));
        }


      return response;
      }

    @RequestMapping("/to-answer/503")
    public ResponseEntity<String> toAnswer503() {
        ResponseEntity<String> response = null;
        try{
            response = appService.answerList503();
        }catch(Exception e){
            System.out.println("excpetion"+ e.getMessage());
            return new ResponseEntity<String>("failure", HttpStatus.valueOf(503));
        }


        return response;
    }
    
    @RequestMapping("/to-answer/500")
    public ResponseEntity<String> toAnswer500() {
        ResponseEntity<String> response = null;
        try{
            response = appService.getServiceCallResponse(null, response);
        }catch(Exception e){
            System.out.println("excpetion"+ e.getMessage());
            return new ResponseEntity<String>("Internal Server Error", HttpStatus.valueOf(500));
        }


    return response;
}

public static void main(String[] args) {
      SpringApplication.run(DavinciCircuitbreakerApplication.class, args);
    }

} }

You can use HystrixCircuitBreaker.Factory.getInstance(...) to get instance of HystrixCommand.您可以使用HystrixCircuitBreaker.Factory.getInstance(...)来获取 HystrixCommand 的实例。 Refer to link for more details.有关详细信息,请参阅链接

Further you can call isCircuitBreakerOpen() on this HystrixCommand instance.此外,您可以在此HystrixCommand实例上调用isCircuitBreakerOpen()

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

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