Spring Cloud services to build micro-architecture: protection service fault-tolerant Hystrix service degradations

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/IT_Luobin/article/details/102756503

In the micro-services architecture, the system will be split into a number of service units, each unit between applications depend on each other through the service registration and subscription basis. Since each unit is running in a different process, call-dependent manner by remote execution, so there is a failure or delay in calling may occur because the network reasons or dependent services their own problems, and these problems will directly lead to the caller's Foreign Service also delays at this time if the caller's request is increasing, and finally there will be a failure waiting for a relying party to form a task in response to the backlog, the thread resources can not be released, eventually leading to paralysis of their own services, or even further spread of the failed final resulting in paralysis of the entire system. If such a framework exists such a serious hazard, even more so compared with the traditional architecture of instability. To solve this problem, thus creating a series of circuit breakers and other protection services.

In response to these problems, to achieve a series of service protection thread isolation, circuit breakers, etc. in Spring Cloud Hystrix in. It is also based on open source Netflix framework of Hystrix implemented, the framework aims by controlling access to those remote node systems, services and third-party libraries, providing a more robust fault tolerance for delay and failure. Hystrix have a service degradation, service fuse, thread isolation, request caching, request merging and service monitoring and other powerful features.

Next, we began to learn and use for Spring Cloud Hystrix from a simple example.

Try hands

Before you start using Spring Cloud Hystrix achieve breaker, something we acquire as a basis prior to implementation, including:

  • eureka-serverProject: Registration Service Center, Port: 1001
  • eureka-clientProject: Service providers are two examples of start port 2001

Now we can copy it prior to implementation of a consumer service: eureka-consumer-ribbonnamed eureka-consumer-ribbon-hystrix. Here we begin to change them at:

The first step: pom.xmlThe node dependencies introduced spring-cloud-starter-hystrixdependency:

<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>

Step 2: Use the main class of the application @EnableCircuitBreakeror @EnableHystrixannotated open Hystrix use of:

@EnableCircuitBreaker
@EnableDiscoveryClient
@SpringBootApplication
public class Application {

	@Bean
	@LoadBalanced
	public RestTemplate restTemplate() {
		return new RestTemplate();
	}

	public static void main(String[] args) {
		new SpringApplicationBuilder(Application.class).web(true).run(args);
	}

}

Note: Here we can also use Spring Cloud applications @SpringCloudApplicationare modified Main Class annotation, the annotation shown specifically defined below. We can see that the annotation contains notes on our three cited, this also means that a standard application should include Spring Cloud service discovery and circuit breakers.

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootApplication
@EnableDiscoveryClient
@EnableCircuitBreaker
public @interface SpringCloudApplication {
}

The third step: the transformation of service consumption, the new ConsumerServiceclass, and then in Controllerthe last logical migration. Finally, on the specific function to perform logical increase @HystrixCommandannotation to specify the method to downgrade services, such as:

@RestController
public class DcController {

    @Autowired
    ConsumerService consumerService;

    @GetMapping("/consumer")
    public String dc() {
        return consumerService.consumer();
    }

    class ConsumerService {

        @Autowired
        RestTemplate restTemplate;

        @HystrixCommand(fallbackMethod = "fallback")
        public String consumer() {
            return restTemplate.getForObject("http://eureka-client/dc", String.class);
        }

        public String fallback() {
            return "fallback";
        }

    }

}

Let's look at some basic features to verify the above Hystrix brings. We first covered services are starting up, and then access localhost:2101/consumer, then you can get a normal return, such as: Services: [eureka-consumer-ribbon-hystrix, eureka-client].

In order to trigger service degradation logic, we can service providers eureka-clientlogical add some delay, such as:

@GetMapping("/dc")
public String dc() throws InterruptedException {
    Thread.sleep(5000L);
    String services = "Services: " + discoveryClient.getServices();
    System.out.println(services);
    return services;
}

Restart eureka-clientafter, and then try to access localhost:2101/consumer, then we will return the results obtained are: fallback. We from eureka-clientthe console, you can see the results of the output of the service provider had to be returned, but due to the delay of 5 seconds before returning, while the service consumer triggers a service request timeout exceptions, service consumers annotation specified by HystrixCommand execution logic degraded, so the results of the request returns fallback. Such a mechanism of self-service served to protect the foundation, but also provides automatic switching of service degradation mechanism is abnormal.

Guess you like

Origin blog.csdn.net/IT_Luobin/article/details/102756503