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 understand service breaker and downgrade Hystrix in SpringCloud

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

This article mainly explains "how to understand service breakers and downgrade Hystrix in SpringCloud". The explanation in this article is simple and clear and easy to learn and understand. please follow the editor's train of thought to study and learn "how to understand service breakers and downgrade Hystrix in SpringCloud".

1. Hystrix circuit breaker 1. What is Hystrix

Problems faced by distributed systems

Applications in complex distributed architectures have dozens of dependencies, each of which will inevitably fail at some point. Service avalanche when calling between multiple micro-services, suppose that micro-service An invokes micro-service B and micro-service C, and micro-service B and micro-service C invoke other micro-services, which is called "fan out". If the response time of a micro-service call on the fan-out link is too long or unavailable, the call to micro-service A will consume more and more system resources and cause the system to crash, the so-called "avalanche effect". For high-traffic applications, a single back-end dependency can cause all resources on all servers to be saturated in seconds. Worse than failure, these applications may also lead to increased latency between services, strain on backup queues, threads, and other system resources, and more cascading failures across the system. All of these indicate the need to isolate and manage failures and delays so that the failure of a single dependency cannot cancel the entire application or system. Note: in general, there are three solutions for the protection of service dependence: (1) fuse mode: this mode is mainly a reference circuit fuse, if a line voltage is too high, the fuse will fuse to prevent fire. Put into our system, if the invocation of a target service is slow or there is a large number of timeouts, the call to the service will be broken, and for subsequent invocation requests, the target service will not be called again, and the resources will be released quickly. If the target service improves, the call is resumed. (2) isolation mode: this mode is like dividing system requests into small islands according to their types. When one island is exposed by fire, it will not affect other islands. For example, you can use thread pools to isolate resources for different types of requests, and each type of request does not affect each other. If one type of request thread resource is exhausted, subsequent requests of that type are returned directly and subsequent resources are no longer called. There are many scenarios for this model, such as taking a service apart, deploying a separate server for important services, or multicenter, which the company has recently promoted. (3) current limiting mode: the above fuse mode and isolation mode belong to the fault tolerant processing mechanism after error, and the current limiting mode can be called prevention mode. The current limit mode is mainly to set the highest QPS threshold for each type of request in advance. If it is higher than the set threshold, the request will be returned directly, and subsequent resources will no longer be called. This model can not solve the problem of service dependence, but can only solve the problem of resource allocation of the system as a whole, because requests without flow restrictions may still cause avalanche effect. Hystrix is an open source library used to deal with delay and fault tolerance of distributed systems. In distributed systems, many dependencies will inevitably fail, such as timeouts, exceptions and so on. Hystrix can ensure that in a dependency problem, it will not lead to overall service failure and avoid cascading failures to improve the flexibility of distributed systems. The "circuit breaker" itself is a switching device. When a service unit fails, it returns an expected and manageable alternative response (FallBack) to the caller through the fault monitoring of the circuit breaker (similar to a fuse), rather than waiting for a long time or throwing an exception that the caller cannot handle, thus ensuring that the thread of the service caller will not be occupied unnecessarily for a long time. As a result, the spread of faults in distributed systems and even avalanches are avoided. Service degradation, service circuit breaker, service current limit, near real-time monitoring 2. Service circuit breaker mechanism is a micro-service link protection mechanism to deal with avalanche effect. When a micro-service of the fan-out link is unavailable or the response time is too long, the service will be degraded, and then the call of the micro-service of the node will be broken, and the response information of "error" will be returned quickly. The calling link is resumed when the microservice call response of the node is detected. In the SpringCloud framework, the circuit breaker mechanism is realized by Hystrix. Hystrix monitors the status of calls between microservices. When failed calls reach a certain threshold, the default is 20 failed calls within 5 seconds to activate the circuit breaker mechanism. The annotation for the circuit breaker mechanism is @ HystrixCommand. = handling exception business logic = provider client handling =

2.1> create a new cloud-provider-dept-8001-hystrix by referring to cloud-provider-dept-8001

2.2 >, POM added

Org.springframework.cloud spring-cloud-starter-hystrix

2.3 >, YML modification

The name displayed in the list of eureka: instance: instance-id: cloud-dept8001-hystirx # eureka services-- the hystix prefer-ip-address: true # access path can display the IP address

2.4 >, modify DeptController

Once the call to the service method fails and the error message is excluded, the specified method in the @ HystrixCommand annotated fallbackMethod invocation class is automatically called. @ HystrixCommand (fallbackMethod = "getHystrixCommand") @ RequestMapping (value= "/ dept/get/ {id}", method=RequestMethod.GET) public Dept get (@ PathVariable ("id") Long id) {if (id > 200) {throw new RuntimeException ();} return service.get (id) } / / parameters must be the same public Dept getHystrixCommand (@ PathVariable ("id") Long id) {return new Dept () .setDname ("this is a null department.");}

Modify the main startup class APP

Package com.lee.cloud;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;import org.springframework.cloud.netflix.eureka.EnableEurekaClient;@EnableCircuitBreaker// support for hystrixR circuit breaker @ EnableEurekaClient / / this service will automatically register in the eureka service @ SpringBootApplicationpublic class DeptProvider8001_APP_hystrix {public static void main (String [] args) {SpringApplication.run (DeptProvider8001_APP_hystrix.class,args);}}

Test:

1 >, start 3 Eureka services 2 >, start cloud-provider-dept-8001-hystrix3 >, start cloud-consumer-dept-804 >, visit http://localhost:80/consumer/dept/get/9999 result: {"deptno": null, "dname": "this is a null department.", "db_source": null} thinking: service breaker, easy to cause method expansion, how to solve it? 3. Service degradation

The service degradation is implemented on the client side and has nothing to do with the server side.

The overall resources are running out, so we can bear to shut down some services until we tide over the difficulties and then turn them back on. = = shut down unimportant services = consumer client processing =

Modify the service interface of cloud-consumer-dept-80 project

According to the existing DeptFeignService interface, create a new class DeptFeignServiceFallbackFactorypackage com.lee.cloud.feign.service;import com.lee.cloud.entity.Dept;import feign.hystrix.FallbackFactory;import org.springframework.stereotype.Component;import java.util.List that implements the FallbackFactory interface. @ Componentpublic class DeptFeignServiceFallbackFactory implements FallbackFactory {@ Override public DeptFeignService create (Throwable throwable) {return new DeptFeignService () {@ Override public Dept get (long id) {return new Dept (). SetDname ("the service has been downgraded.") .setDb _ source ("Service downgrade did not find database.");} @ Override public List list () {return null;} @ Override public boolean add (Dept dept) {return false;};}}

The API DeptFeignService adds the value of the fallbackFactory attribute to the annotation @ FeignClient

@ FeignClient (value = "CLOUD-DEPT", fallbackFactory = DeptFeignServiceFallbackFactory.class)

3. 3 > cloud-consumer-dept-80-feign Project Modification yml

Add feign: hystrix: enabled: true

Test:

1 ", start 3 eureka services 2", start the service provider cloud-provider-dept-8001 service, note that it is not cloud-provider-dept-8001-hystrix3 ", start cloud-consumer-dept-80-feign4", normal access test http://localhost:80/consumer/dept/get/15 ", intentionally close cloud-provider-dept-80016", and the client calls the prompt result: {"deptno": null, "dname": "the service has been degraded." , "db_source": "Service downgrade No database found."} think: what's the difference between a service breaker and a service downgrade? [service breaker] is usually caused by a service failure or exception, similar to a real-world "fuse". When an abnormal condition is punished, the entire service is directly disconnected instead of waiting for the service to time out. [service degradation] the so-called downgrade is generally considered in terms of the overall load, that is, when a service is disconnected, the server will no longer be called. At this point, the client can prepare a local fallback callback and return a default value. In this way, although the level of service is declining, it is at least available, which is better than hanging up directly. 4. Service Monitoring HystrixDashboard in addition to isolating calls that depend on services, Hystrix also provides quasi-real-time call monitoring (HystrixDashboard). Hystrix continuously records the execution information of all requests initiated through Hystrix and displays them to users in the form of statistical reports and graphs, including how many requests are executed per second, how many successful, how many failures, and so on. Netflix realizes the monitoring of the above indicators through the hystrix-metrics-event-stream project. Spring Cloud also provides the integration of Hystrix Dashboard, turning the monitoring content into a visual interface.

Create a new module,cloud-consumer-dept-9001-hystirx-dashboard

4.2 >, POM file

Com.lee cloud-api ${project.version} org.springframework.boot spring-boot-starter-web org.springframework springloaded org.springframework.boot spring-boot-devtools org.springframework.cloud spring-cloud-starter-eureka org.springframework.cloud spring-cloud-starter-ribbon org.springframework.cloud spring-cloud -starter-config org.springframework.cloud spring-cloud-starter-feign org.springframework.cloud spring-cloud-starter-hystrix org.springframework.cloud spring-cloud-starter-hystrix-dashboard

4. 3 >, YML file

Server: port: 9001

4.4 >, main startup class

Package com.lee.cloud;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;@EnableHystrixDashboard@SpringBootApplicationpublic class DeptConsumer_DashBoard_9001_App {public static void main (String [] args) {SpringApplication.run (DeptConsumer_DashBoard_9001_App.class,args);}}

4.5 > all provider micro service providers need to add monitoring dependencies

Org.springframework.boot spring-boot-starter-actuator

Test:

1. Start cloud-consumer-dept-9001-hystrix-dashboard access: http://localhost:9001/hystrix2, start 3 eureka clusters, start cloud-provider-dept-8001-hystrix access: http://localhost8001/dept/list4, http://localhost:8001/hystrix.stream delay:2000ms title: demo1

Thank you for your reading. The above is the content of "how to understand service breakers and downgrade Hystrix in SpringCloud". After the study of this article, I believe you have a deeper understanding of how to understand the problem of service breakers and downgrade Hystrix in SpringCloud, and the specific usage needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

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

Internet Technology

Wechat

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

12
Report