如何使用Netflix Hystrix获取断路器状态?

huangapple go评论79阅读模式
英文:

How to get status for circuit breaker status with netflix hystrix?

问题

以下是您的AppService类的翻译部分:

@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();
    }

    // ...其他方法的翻译...

    @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) {
        // ...方法内容...
    }

    // ...其他方法的翻译...

    @Recover()
    public ResponseEntity<String> reliable() {
        return new ResponseEntity<String>(
                "The downstream application is unavailable and the circuit is open", HttpStatus.OK);
    }
}

这是您的主类的翻译部分:

@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() {
        // ...方法内容...
    }

    @RequestMapping("/to-answer/503")
    public ResponseEntity<String> toAnswer503() {
        // ...方法内容...
    }

    @RequestMapping("/to-answer/500")
    public ResponseEntity<String> toAnswer500() {
        // ...方法内容...
    }

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

请注意,由于您要求只返回翻译后的内容,我已将代码中的方法内容省略。如果您需要完整的翻译,请随时告诉我。

英文:

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. Also, i have made use of ignoreExceptions but seems like trouble is there. Just new to coding and this feature and unable to get an appropriate answer. I am not sure how to use 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 = &quot;reliable&quot;, commandProperties= {
@HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_ERROR_THRESHOLD_PERCENTAGE, value = &quot;100&quot;),
@HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_SLEEP_WINDOW_IN_MILLISECONDS, value = &quot;10000&quot;),
@HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_REQUEST_VOLUME_THRESHOLD, value = &quot;10&quot;)
})
public ResponseEntity&lt;String&gt; answerList() throws Exception {
return callingDownStreamService404();
}
@HystrixCommand(fallbackMethod = &quot;reliable&quot;, commandProperties= {
@HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_ERROR_THRESHOLD_PERCENTAGE, value = &quot;100&quot;),
@HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_SLEEP_WINDOW_IN_MILLISECONDS, value = &quot;10000&quot;),
@HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_REQUEST_VOLUME_THRESHOLD, value = &quot;10&quot;)
})
public ResponseEntity&lt;String&gt; answerList503() throws Exception {
return callingDownStreamService503();
}
private ResponseEntity&lt;String&gt; callingDownStreamService404() throws Exception {
URI uri = URI.create(&quot;http://localhost:8090/recommended/404&quot;);
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
HttpEntity&lt;Object&gt; entity = new HttpEntity&lt;Object&gt;(headers);
ResponseEntity&lt;String&gt; out = restTemplate.exchange(uri, HttpMethod.GET, entity, String.class);
System.out.println(&quot;Application code : &quot; + out.getStatusCode());
return out;
}
private ResponseEntity&lt;String&gt; callingDownStreamService503() throws Exception {
URI uri = URI.create(&quot;http://localhost:8090/recommended/503&quot;);
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
HttpEntity&lt;Object&gt; entity = new HttpEntity&lt;Object&gt;(headers);
ResponseEntity&lt;String&gt; out = restTemplate.exchange(uri, HttpMethod.GET, entity, String.class);
System.out.println(&quot;Application code : &quot; + out.getStatusCode());
if (out.getStatusCode().toString().startsWith(&quot;5&quot;)) {
throw new HystrixBadRequestException(&quot;bad request messageg&quot;);
}
return out;
}
@HystrixCommand(commandKey = &quot;MyHystrixCommand&quot;,fallbackMethod = &quot;myHystrixFallback&quot;, threadPoolKey = &quot;ThreadPoolKey&quot;,commandProperties= {
@HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_ERROR_THRESHOLD_PERCENTAGE, value = &quot;100&quot;),
@HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_SLEEP_WINDOW_IN_MILLISECONDS, value = &quot;10000&quot;),
@HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_REQUEST_VOLUME_THRESHOLD, value = &quot;10&quot;)},
ignoreExceptions = {HttpServerErrorException.class, HystrixBadRequestException.class, HttpClientErrorException.class})
public ResponseEntity&lt;String&gt; getServiceCallResponse(String serviceUrl, HttpEntity&lt;?&gt; entity) {
serviceUrl = &quot;http://localhost:8090/recommended/500&quot;;
ResponseEntity&lt;String&gt; resp = null;
try {
System.out.println(&quot;Calling -----&quot; + serviceUrl);
resp = restTemplate.exchange(serviceUrl, HttpMethod.POST, entity, String.class);
}
catch(RestClientException e) {
System.out.println(&quot;Calling -----&quot; + serviceUrl + &quot;Exception is this&quot; + e.getRootCause());
handleExceptionForHystrix(&quot;getServiceCallResponse&quot;, 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(&quot;Hystrix Bad Request Exception Occurred&quot; + httpStatusCode, e);
}
throw new RuntimeException(function, e);
}
throw new RuntimeException(function, e);
}
public ResponseEntity&lt;String&gt; myHystrixFallback(String serviceUrl, HttpEntity&lt;?&gt; entity, Throwable hystrixCommandExp) {
return new ResponseEntity&lt;String&gt;(HttpStatus.INTERNAL_SERVER_ERROR);
}
@Recover()
public ResponseEntity&lt;String&gt; reliable() {
return new ResponseEntity&lt;String&gt;(
&quot;The downstream application is unavailable and the circuit is open&quot;, 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.

@EnableHystrixDashboard
@EnableCircuitBreaker
@RestController
@SpringBootApplication
public class DavinciCircuitbreakerApplication {
@Autowired
private AppService appService;
@Bean
public RestTemplate rest(RestTemplateBuilder builder) {
return builder.build();
}
@RequestMapping(&quot;/to-answer/404&quot;)
public ResponseEntity&lt;String&gt; toAnswer() {
ResponseEntity&lt;String&gt; response = null;
try{
response = appService.answerList();
}catch(Exception e){
System.out.println(&quot;excpetion&quot;+ e.getMessage());
return new ResponseEntity&lt;String&gt;(&quot;failure&quot;, HttpStatus.valueOf(500));
}
return response;
}
@RequestMapping(&quot;/to-answer/503&quot;)
public ResponseEntity&lt;String&gt; toAnswer503() {
ResponseEntity&lt;String&gt; response = null;
try{
response = appService.answerList503();
}catch(Exception e){
System.out.println(&quot;excpetion&quot;+ e.getMessage());
return new ResponseEntity&lt;String&gt;(&quot;failure&quot;, HttpStatus.valueOf(503));
}
return response;
}
@RequestMapping(&quot;/to-answer/500&quot;)
public ResponseEntity&lt;String&gt; toAnswer500() {
ResponseEntity&lt;String&gt; response = null;
try{
response = appService.getServiceCallResponse(null, response);
}catch(Exception e){
System.out.println(&quot;excpetion&quot;+ e.getMessage());
return new ResponseEntity&lt;String&gt;(&quot;Internal Server Error&quot;, HttpStatus.valueOf(500));
}
return response;
}
public static void main(String[] args) {
SpringApplication.run(DavinciCircuitbreakerApplication.class, args);
}

}

答案1

得分: 2

你可以使用 HystrixCircuitBreaker.Factory.getInstance(...) 来获取 HystrixCommand 的实例。更多细节请参考 链接

此外,你可以在这个 HystrixCommand 实例上调用 isCircuitBreakerOpen()

英文:

You can use HystrixCircuitBreaker.Factory.getInstance(...) to get instance of HystrixCommand. Refer to link for more details.

Further you can call isCircuitBreakerOpen() on this HystrixCommand instance.

huangapple
  • 本文由 发表于 2020年10月2日 17:02:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/64168872.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定