Spring cloud learning (3)

Time:2019-12-23

This article integrates hystrix and continues to build demo.

Avalanche effect:
In microservice architecture, there are usually multiple service layer calls. The failure of basic services may lead to cascading failures, which will lead to the unavailability of the whole system. This phenomenon is called service avalanche effect. Service avalanche effect is a process in which the unavailability of service provider leads to the unavailability of service consumer, and the unavailability is enlarged gradually.

As shown in the figure below: A as the service provider, B as the service consumer of a, C and D as the service consumer of B. A unavailability causes B unavailability, and the avalanche effect is formed when the unavailability is amplified to C and d like a snowball.

Spring cloud learning (3)

Fuse:
The principle of fuse is very simple, just like power overload protector. It can realize fast failure. If it detects many similar errors in a period of time, it will force its subsequent multiple calls to fail quickly, and no longer access the remote server, so as to prevent the application from constantly trying to perform operations that may fail, so that the application continues to execute without waiting for the error to be corrected, or wasting CPU time to wait for a long timeout Produce. Fuses also enable the application to diagnose if the error has been fixed, and if so, the application attempts to invoke the operation again.

Fuse mode is like an agent for operations that are prone to error. This agent can record the number of errors that occurred in the most recent call, and then decide to continue with the allow operation, or return the error immediately.
The logic of mutual conversion of fuse switches is as follows:

Spring cloud learning (3)

Hystrix fuse:
1. Circuit breaker mechanism

The circuit breaker has a good understanding. When the number of failures of the hystrix command to request back-end services exceeds a certain proportion (default 50%), the circuit breaker will switch to the open state. At this time, all requests will fail directly and will not be sent to the back-end services. After the circuit breaker remains in the open state for a period of time (default 5 seconds), it will automatically switch to the half open state (half-open). At this time, the return of the next request will be judged If the request is successful, the circuit breaker will switch back to the closed state, otherwise it will switch back to the open state. The circuit breaker of hystrix is like the fuse in our home circuit. Once the back-end service is unavailable, the circuit breaker will directly cut the request chain to avoid sending a large number of invalid requests affecting the system throughput, and the circuit breaker has the ability of self detection and recovery

2.Fallback

For query operation, we can implement a fallback method. When there is an exception in the request back-end service, we can use the value returned by the fallback method. The return value of the fallback method is generally the default value set or from the cache

3. Resource isolation

In hystrix, resource isolation is mainly realized by thread pool. Usually, when using, we will divide multiple thread pools according to the called remote service. For example, the command calling product service will be put into thread pool a, and the command calling account service will be put into thread pool B. the main advantage of this is that the running environment is isolated. In this way, even if the code calling service has bugs or When the thread pool is exhausted due to other reasons, it will not affect other services of the system. However, the cost is that maintaining multiple thread pools will bring additional performance overhead to the system. If there are strict performance requirements and you are sure that the client code that you call the service will not have problems, you can use the semaphores of hystrix to separate them Out of resources.

We use hystirx in the movie microservice and create the following directory

Spring cloud learning (3)

In the controller, you can directly use the hystrix annotation, and customize the fallback function. When there is an exception in the request back-end service, you can use the value returned by the fallback method

 @GetMapping("/movie/{id}")
    @HystrixCommand(fallbackMethod = "fallbackMovie",commandProperties = @HystrixProperty(name = "execution.isolation.strategy",value = "semaphore"))
    public User findmovie(@PathVariable int id){

        return userFeignClient.find(id);
    }

    public User fallbackMovie(int id){
        User user=new User();
        user.setId(10);
        return  user;
    }

amongcommandProperties = @HystrixProperty(name = "execution.isolation.strategy",value = "semaphore")The value hystrix of is thread by default,
The threads isolated in the thread pool are used by default. To switch to the context where the same thread of the caller uses spring security, the isolation policy must be set to semaphore.
About the spring parent-child container context:
1. Firstly, for a web application, it is deployed in a web container, which provides a global context environment. This context is ServletContext, which provides a host environment for the following spring IOC containers;

2. Secondly, contextloaderlistener will be provided in web.xml. When the web container is started, the container initialization event will be triggered. At this time, the contextloaderlistener will listen to this event, and its contextinitialized method will be called. In this method, spring will initialize a startup context, which is called the root context, namely webapplicationcontext. This is an interface class. Specifically, its actual implementation class is xmlw ebApplicationContext。 This is the IOC container of spring. The configuration of its corresponding bean definition is specified by the context param tag in web.xml. After the IOC container is initialized, spring takes webapplicationcontext.rootwebappplicationcontextattribute as the attribute key, and stores it in ServletContext for easy access;

3. Thirdly, after the initialization of the contextloaderlistener listener, it starts to initialize the servlet configured in web.xml. This servlet can be configured with multiple. Take the most common dispatcher servlet as an example. This servlet is actually a standard front-end controller for forwarding, matching and processing each servlet request. When the dispatcher servlet context is initialized, it will establish its own IOC context to hold spring MVC related beans. When establishing the dispatcher servlet’s own IOC context, webapplicationcontext attribute will be used to first obtain the previous root context (webapplicationcontext) from the servlet context as its own parent context. With this parent context, initialize the context you hold. In its initstrategies method, we can see that the work of initializing its own context of the dispatcher servlet is about initializing the processor mapping, view parsing, etc. The default implementation class of this servlet’s own context is also mlwebapplicationcontext. After initialization, spring uses the attribute key related to the servlet name (here, instead of simply using the servlet name as key, you can view the source code by yourself through some transformations), and also stores it in the ServletContext for subsequent use. In this way, each servlet has its own context, that is, it has its own independent bean space, and each servlet shares the same bean, that is, those beans defined by the root context (the context initialized in step 2).

Using hystrix in feign:

Feign client

@FeignClient(name="userprovider",configuration = FeignClient.class,fallback = HystrixFallbackClient.class)
public interface UserFeignClient {
    @RequestMapping (value = "/user/{id}",method = RequestMethod.GET)
    public User find(@PathVariable("id") int id);
}

The implementation of fallback method by the class hystrixfallbackclient of fallback


@Component
public class HystrixFallbackClient implements UserFeignClient {


    @Override
    public User find(int id) {
        User user=new User();
        user.setId(1);
        return user;
    }
}

If you want to disable the hytrix of a feignclient, you can change the config of feignclient and return feign.bullider. The default is the hytrix’s

FeignConfig:

@Configuration
public class FeignConfig {

    @Bean
    public Contract feignContract(){
         return new feign.Contract.Default();

    }
    @Bean
    @Scope("prototype")
    public Feign.Builder feignBuilder(){

        return  Feign.builder();
    }
}

If you need to access the trigger reason of fallback, hystrix also provides fallbackfactory:

Override the properties of userfeignclient:

@FeignClient(name="userprovider",configuration = FeignClient.class,fallbackFactory = HystrixFallbackFactory.class)
public interface UserFeignClient {
    @RequestMapping (value = "/user/{id}",method = RequestMethod.GET)
    public User find(@PathVariable("id") int id);
}

Create hystrixfallbackfactory and an interface that inherits userfeignclient

HystrixUserFeignClientWithFactory:

public interface HystrixUserFeignClientWithFactory extends UserFeignClient {
}

HystrixFallbackFactory:

@Component
public class HystrixFallbackFactory implements FallbackFactory<UserFeignClient>{

    private static final Logger logger= LoggerFactory.getLogger(HystrixFallbackFactory.class);

    @Override
    public UserFeignClient create(Throwable throwable) {

        This. Logger. Info ("exception reason is {}", throwable. Getmessage());
        return new HystrixUserFeignClientWithFactory() {

            @Override
            public User find(int id) {
                User user=new User();
                user.setId(0);
                return user;
            }
        };
    }
}

Dashboard can be used for the visualization of hystrix real-time monitoring
POM addition of Eureka
`<dependency>

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

</dependency>`

Add the annotation @ enablehystrixdashboard to the application, start Eureka and movie microservice (remember to change the fallback of userfeignclient to fallbackfactory, delete the fallback property and userfeignclient implementation class, or report an error) to access the hystrix

Spring cloud learning (3)

Use movie microservice first, then hystrix can print the log record. Visit http: / / localhost: 8088 / hystrix

Spring cloud learning (3)

Then at http: / / localhost: 8761 / hystrix, enter the address of http: / / localhost: 8088 / hystrix… To monitor successfully

Spring cloud learning (3)

Recommended Today

[reading notes] calculation advertising (Part 3)

By logm This article was originally published at https://segmentfault.com/u/logm/articles and is not allowed to be reproduced~ If the mathematical formula in the article cannot be displayed correctly, please refer to: Tips for displaying the mathematical formula correctly This article isComputing advertising (Second Edition)Reading notes. This part introduces the key technology of online advertising, which is […]