Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Hystrix to realize fault-tolerant processing

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail how to use Hystrix to achieve fault-tolerant processing, the content of the article is of high quality, so the editor will share it for you as a reference. I hope you will have a certain understanding of the relevant knowledge after reading this article.

Create a new Maven project, hystrix-feign-demo, and increase the dependency on Hystrix, as shown below.

Org.springframework.cloudspring-cloud-starter-netflix-hystrix

Add @ EnableHystrix or @ EnableCircuitBreaker to the startup class. Notice that @ EnableHystrix contains @ EnableCircuitBreaker.

Then write a method that invokes the interface, adding an @ HystrixCommand annotation to it to specify the method to be called when the dependent service invocation delays or fails, as shown below.

@ GetMapping ("/ callHello") @ HystrixCommand (fallbackMethod = "defaultCallHello") public String callHello () {String result = restTemplate.getForObject ("http://localhost:8088/house/hello", String.class); return result;}

When the call fails to trigger the circuit breaker, the defaultCallHello method is used to roll back the specific content. The code that defines the default-CallHello method is shown below.

Public String defaultCallHello () {

Return "fail"

}

As long as you don't start the service on port 8088 and call the / callHello interface, you can see that the content returned is "fail", as shown in figure 1.

Remove the @ EnableHystrix from the startup class, restart the service, and call the / callHello API again to see that a 500 error message is returned. At this time, the fallback feature is not used.

{code: 500, message: "http://localhost:8088/house/hello": O error on GET request for" http://localhost:8088/house/hello": Connection refused; nested exception is java.net.ConnectException: Connection refused ", data: null} configuration details

There are many configurations in HystrixCommand besides fallbackMethod. Let's take a look at these configurations, as shown in the following table:

HystrixCommand configuration details

Name description hystrix.command.default.execution.isolation

.strategy this configuration is used to specify isolation policies. There are two specific policies.

THREAD: thread isolation, execution on separate threads, and concurrent requests are controlled by thread pool size.

SEMAPHORE: semaphore isolation, executed on the calling thread, and concurrent requests are limited by semaphore counters.

Hystrix.command.default.execution.isolation

.thread.timeoutInMilliseconds this configuration is used to set the timeout for HystrixCommand execution. When the HystrixCommand execution time exceeds the value set by this configuration, it will enter the service degradation process (in milliseconds). The default value is 1000. Hystrix.command.default.execution

Timeout. Enabled this configuration determines whether the timeout for the execution.isolation.thread.timeoutInMilliseconds setting is enabled, and the default value is true. The execution.isolation.thread.timeoutInMilliseconds configuration will also fail when it is set to false. Hystrix.command.default.execution.isolation

Thread. Thread OnTimeout this configuration is used to determine whether HystrixCommand needs to be interrupted after it times out. The default value is true. Hystrix.command.default.execution.isolation

Thread. EncryptOnCancel this configuration is used to determine whether HystrixCommand execution needs to be interrupted when it is cancelled. The default value is false. Hystrix.command.default.execution.isolation

.semaphore.maxConcurrentRequests this configuration is used to determine the maximum number of concurrent requests when Hystrix uses the semaphore policy. Hystrix.command.default.fallback.isolation

.semaphore.maxConcurrentRequests this configuration is used for if the number of concurrency reaches this set value, the request will be rejected and an exception will be thrown and fallback will not be called. The default value is 10. Hystrix.command.default.fallback.enabled this configuration is used to determine whether a call to hystrixCommand.getFallback () will be attempted when execution fails or the request is rejected. The default value is true. Hystrix.command.default.circuitBreaker.enabled this configuration is used to track the health of circuit and short-circuit request if it does not meet the standard. The default value is true. Hystrix.command.default.circuitBreaker

.requestVolumeThreshold this configuration is used to set the minimum number of requests in a rolling window. If set to 20, when 19 requests are received in a rolling window (for example, 1 rolling window is 10 seconds), even if 19 requests fail, circuit break will not be triggered. The default value is 20. Hystrix.command.default.circuitBreaker

Request WindowInMilliseconds this configuration is used to set a time value to trigger a short circuit. When this value is set to 5000, request will be rejected within 5000 milliseconds after circuit break is triggered, that is, 5000 milliseconds before circuit will be closed. The default value is 5000. Hystrix.command.default.circuitBreaker

.errorThresholdPercentage this configuration is used to set the error rate threshold. When the error rate exceeds this value, all requests will trigger fallback. The default value is 50. If hystrix.command.default.circuitBreaker.forceOpen is configured as true, the fuse will be forced on, and all requests will be rejected in this state. The default value is false. If hystrix.command.default.circuitBreaker.forceClosed is configured as true, the fuse will be forced off, in this state, no matter how high the error rate is, the request is allowed, and the default is false. Hystrix.command.default.metrics

.rollingStats.timeInliseconds sets the time window value for statistics in milliseconds. The opening of circuit break is calculated based on the statistics of 1 rolling window. If rolling window is set to 10,000 milliseconds, rolling window will be divided into multiple buckets, each bucket containing statistics on the number of times success, failure, timeout, and rejection. The default value is 10000 milliseconds. Hystrix.command.default.metrics

.rollingStats.numBuckets sets the number of rolling window to be divided. If numBuckets=10 and rolling window=10 000, then the time of a bucket is 1 second. Must be rolling window%numberBuckets==0 compliant. The default value is 10. Hystrix.command.default.metrics

Whether to enable the calculation and tracking of metrics. The default value is true. Hystrix.command.default.metrics

.rollingPercentile.timeInMilliseconds sets the time of rolling percentile window. The default value is 60,000 milliseconds hystrix.command.default.metrics.

RollingPercentile.numBuckets sets the numberBuckets of rolling percentile window, with a default value of 6. Hystrix.command.default.metrics

.rollingPercentile.bucketSize if bucket size=100, window=10 seconds, if there are 500 executions in these 10 seconds, only the last 100 executions will be counted in bucket. Increasing this value increases memory overhead and sorting overhead. The default value is 100. Hystrix.command.default.metrics

.healthSnapshot.intervalInMilliseconds is used to calculate the interval wait time for healthy snapshots that affect the state of the circuit breaker. The default value is 500 milliseconds. Whether hystrix.command.default.requestCache.enabled enables request caching. The default is true. Hystrix.command.default.requestLog.enabled logs to HystrixRequestLog, and the default value is true. The maximum number of requests for a single batch of hystrix.collapser.default.maxRequestsInBatch, which triggers batch processing. The default is Integer.MAX_VALUE. Hystrix.collapser.default.timerDelayInMilliseconds triggers the delay of the batch, which can also be the sum of the time when the batch was created and the value, with a default value of 10 milliseconds. Whether hystrix.collapser.default.requestCache.enabled enables request caching for HystrixCollapser.execute () and HystrixCollapser.queue (). The default value is true. The maximum number of threads for concurrent execution of hystrix.threadpool.default.coreSize. The default value is 10. The maximum number of queues for the hystrix.threadpool.default.maxQueueSizeBlockingQueue. When set to-1, LinkedBlcokingQueue is used when the SynchronousQueue; value is positive. This setting is only valid during initialization, and the queue size of threadpool cannot be modified after that. The default value is-1. Even if hystrix.threadpool.default.queueSizeRejectionThreshold does not reach maxQueueSize, the request will be rejected if it reaches the value of queueSizeRejectionThreshold. Because maxQueueSize cannot be dynamically modified, the queueSizeRejectionThreshold parameter will allow us to set this value dynamically. If maxQueueSize==-1, this field will not work. Hystrix.threadpool.default.keepAliveTimeMinutes sets the survival time (in minutes). If coreSize is less than maximumSize, then this property controls the time from the utility completion to the release of a thread. The default value is 1 minute. Hystrix.threadpool.default

.allowMaximumSizeToDivergeFromCoreSize this property allows maximumSize's configuration to take effect. Then the value can be equal to or higher than coreSize. Setting coreSize less than maximumSize creates a thread pool that supports maximumSize concurrency but returns threads to the system during periods of relative inactivity. The default is false. Hystrix.threadpool.default.metrics

.rollingStats.timeInliseconds sets the time to scroll the time window in milliseconds, with a default value of 10,000. Hystrix.threadpool.default.metrics

.rollingStats.numBuckets sets the number of barrels to scroll through the time window, with a default value of 10.

For the official configuration information document, please refer to https://github.com/Netflix/Hystrix/wiki/Configuration.

All the configuration information listed above is for Hystrix, so how to use it in Spring Cloud? You only need to use the HystrixCommand annotation on the method of the interface (shown in the following code) to specify the corresponding properties.

@ HystrixCommand (fallbackMethod = "defaultCallHello", commandProperties = {@ HystrixProperty (name= "execution.isolation.strategy", value = "THREAD")}) @ GetMapping ("/ callHello") public String callHello () {String result = restTemplate.getForObject ("http://localhost:8088/house/hello", String.class); return result;} is here on how to use Hystrix to achieve fault-tolerant processing. I hope the above can be helpful and learn more. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report